simplify VT_LONG parsing
[tinycc.git] / tccgen.c
blob292c0914a26ea606ed82aaa5ffeb557466263baf
1 /*
2 * TCC - Tiny C Compiler
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"
23 /********************************************************/
24 /* global variables */
26 /* loc : local variable index
27 ind : output code index
28 rsym: return symbol
29 anon_sym: anonymous symbol index
31 ST_DATA int rsym, anon_sym, ind, loc;
33 ST_DATA Sym *sym_free_first;
34 ST_DATA void **sym_pools;
35 ST_DATA int nb_sym_pools;
37 ST_DATA Sym *global_stack;
38 ST_DATA Sym *local_stack;
39 ST_DATA Sym *define_stack;
40 ST_DATA Sym *global_label_stack;
41 ST_DATA Sym *local_label_stack;
42 static int local_scope;
43 static int in_sizeof;
44 static int section_sym;
46 ST_DATA int vlas_in_scope; /* number of VLAs that are currently in scope */
47 ST_DATA int vla_sp_root_loc; /* vla_sp_loc for SP before any VLAs were pushed */
48 ST_DATA int vla_sp_loc; /* Pointer to variable holding location to store stack pointer on the stack when modifying stack pointer */
50 ST_DATA SValue __vstack[1+VSTACK_SIZE], *vtop, *pvtop;
52 ST_DATA int const_wanted; /* true if constant wanted */
53 ST_DATA int nocode_wanted; /* no code generation wanted */
54 #define NODATA_WANTED (nocode_wanted > 0) /* no static data output wanted either */
55 #define STATIC_DATA_WANTED (nocode_wanted & 0xC0000000) /* only static data output */
56 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
57 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
58 ST_DATA int func_var; /* true if current function is variadic (used by return instruction) */
59 ST_DATA int func_vc;
60 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
61 ST_DATA const char *funcname;
62 ST_DATA int g_debug;
64 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
66 ST_DATA struct switch_t {
67 struct case_t {
68 int64_t v1, v2;
69 int sym;
70 } **p; int n; /* list of case ranges */
71 int def_sym; /* default symbol */
72 } *cur_switch; /* current switch */
74 /* ------------------------------------------------------------------------- */
76 static void gen_cast(CType *type);
77 static void gen_cast_s(int t);
78 static inline CType *pointed_type(CType *type);
79 static int is_compatible_types(CType *type1, CType *type2);
80 static int parse_btype(CType *type, AttributeDef *ad);
81 static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td);
82 static void parse_expr_type(CType *type);
83 static void init_putv(CType *type, Section *sec, unsigned long c);
84 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
85 static void block(int *bsym, int *csym, int is_expr);
86 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, int scope);
87 static void decl(int l);
88 static int decl0(int l, int is_for_loop_init, Sym *);
89 static void expr_eq(void);
90 static void vla_runtime_type_size(CType *type, int *a);
91 static void vla_sp_restore(void);
92 static void vla_sp_restore_root(void);
93 static int is_compatible_unqualified_types(CType *type1, CType *type2);
94 static inline int64_t expr_const64(void);
95 static void vpush64(int ty, unsigned long long v);
96 static void vpush(CType *type);
97 static int gvtst(int inv, int t);
98 static void gen_inline_functions(TCCState *s);
99 static void skip_or_save_block(TokenString **str);
100 static void gv_dup(void);
102 ST_INLN int is_float(int t)
104 int bt;
105 bt = t & VT_BTYPE;
106 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
109 /* we use our own 'finite' function to avoid potential problems with
110 non standard math libs */
111 /* XXX: endianness dependent */
112 ST_FUNC int ieee_finite(double d)
114 int p[4];
115 memcpy(p, &d, sizeof(double));
116 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
119 ST_FUNC void test_lvalue(void)
121 if (!(vtop->r & VT_LVAL))
122 expect("lvalue");
125 ST_FUNC void check_vstack(void)
127 if (pvtop != vtop)
128 tcc_error("internal compiler error: vstack leak (%d)", vtop - pvtop);
131 /* ------------------------------------------------------------------------- */
132 /* vstack debugging aid */
134 #if 0
135 void pv (const char *lbl, int a, int b)
137 int i;
138 for (i = a; i < a + b; ++i) {
139 SValue *p = &vtop[-i];
140 printf("%s vtop[-%d] : type.t:%04x r:%04x r2:%04x c.i:%d\n",
141 lbl, i, p->type.t, p->r, p->r2, (int)p->c.i);
144 #endif
146 /* ------------------------------------------------------------------------- */
147 /* start of translation unit info */
148 ST_FUNC void tcc_debug_start(TCCState *s1)
150 if (s1->do_debug) {
151 char buf[512];
153 /* file info: full path + filename */
154 section_sym = put_elf_sym(symtab_section, 0, 0,
155 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
156 text_section->sh_num, NULL);
157 getcwd(buf, sizeof(buf));
158 #ifdef _WIN32
159 normalize_slashes(buf);
160 #endif
161 pstrcat(buf, sizeof(buf), "/");
162 put_stabs_r(buf, N_SO, 0, 0,
163 text_section->data_offset, text_section, section_sym);
164 put_stabs_r(file->filename, N_SO, 0, 0,
165 text_section->data_offset, text_section, section_sym);
166 last_ind = 0;
167 last_line_num = 0;
170 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
171 symbols can be safely used */
172 put_elf_sym(symtab_section, 0, 0,
173 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
174 SHN_ABS, file->filename);
177 /* put end of translation unit info */
178 ST_FUNC void tcc_debug_end(TCCState *s1)
180 if (!s1->do_debug)
181 return;
182 put_stabs_r(NULL, N_SO, 0, 0,
183 text_section->data_offset, text_section, section_sym);
187 /* generate line number info */
188 ST_FUNC void tcc_debug_line(TCCState *s1)
190 if (!s1->do_debug)
191 return;
192 if ((last_line_num != file->line_num || last_ind != ind)) {
193 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
194 last_ind = ind;
195 last_line_num = file->line_num;
199 /* put function symbol */
200 ST_FUNC void tcc_debug_funcstart(TCCState *s1, Sym *sym)
202 char buf[512];
204 if (!s1->do_debug)
205 return;
207 /* stabs info */
208 /* XXX: we put here a dummy type */
209 snprintf(buf, sizeof(buf), "%s:%c1",
210 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
211 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
212 cur_text_section, sym->c);
213 /* //gr gdb wants a line at the function */
214 put_stabn(N_SLINE, 0, file->line_num, 0);
216 last_ind = 0;
217 last_line_num = 0;
220 /* put function size */
221 ST_FUNC void tcc_debug_funcend(TCCState *s1, int size)
223 if (!s1->do_debug)
224 return;
225 put_stabn(N_FUN, 0, 0, size);
228 /* ------------------------------------------------------------------------- */
229 ST_FUNC int tccgen_compile(TCCState *s1)
231 cur_text_section = NULL;
232 funcname = "";
233 anon_sym = SYM_FIRST_ANOM;
234 section_sym = 0;
235 const_wanted = 0;
236 nocode_wanted = 0x80000000;
238 /* define some often used types */
239 int_type.t = VT_INT;
240 char_pointer_type.t = VT_BYTE;
241 mk_pointer(&char_pointer_type);
242 #if PTR_SIZE == 4
243 size_type.t = VT_INT;
244 #else
245 size_type.t = VT_LLONG;
246 #endif
247 func_old_type.t = VT_FUNC;
248 func_old_type.ref = sym_push(SYM_FIELD, &int_type, 0, 0);
249 func_old_type.ref->f.func_call = FUNC_CDECL;
250 func_old_type.ref->f.func_type = FUNC_OLD;
252 tcc_debug_start(s1);
254 #ifdef TCC_TARGET_ARM
255 arm_init(s1);
256 #endif
258 #ifdef INC_DEBUG
259 printf("%s: **** new file\n", file->filename);
260 #endif
262 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | PARSE_FLAG_TOK_STR;
263 next();
264 decl(VT_CONST);
265 if (tok != TOK_EOF)
266 expect("declaration");
268 gen_inline_functions(s1);
269 check_vstack();
270 /* end of translation unit info */
271 tcc_debug_end(s1);
272 return 0;
275 /* ------------------------------------------------------------------------- */
276 /* apply storage attributes to Elf symbol */
278 static void update_storage(Sym *sym)
280 ElfW(Sym) *esym;
281 if (0 == sym->c)
282 return;
283 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
284 if (sym->a.visibility)
285 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1))
286 | sym->a.visibility;
287 if (sym->a.weak)
288 esym->st_info = ELFW(ST_INFO)(STB_WEAK, ELFW(ST_TYPE)(esym->st_info));
289 #ifdef TCC_TARGET_PE
290 if (sym->a.dllimport)
291 esym->st_other |= ST_PE_IMPORT;
292 if (sym->a.dllexport)
293 esym->st_other |= ST_PE_EXPORT;
294 #endif
295 #if 0
296 printf("storage %s: vis=%d weak=%d exp=%d imp=%d\n",
297 get_tok_str(sym->v, NULL),
298 sym->a.visibility,
299 sym->a.weak,
300 sym->a.dllexport,
301 sym->a.dllimport
303 #endif
306 /* ------------------------------------------------------------------------- */
307 /* update sym->c so that it points to an external symbol in section
308 'section' with value 'value' */
310 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
311 addr_t value, unsigned long size,
312 int can_add_underscore)
314 int sym_type, sym_bind, sh_num, info, other, t;
315 ElfW(Sym) *esym;
316 const char *name;
317 char buf1[256];
318 #ifdef CONFIG_TCC_BCHECK
319 char buf[32];
320 #endif
322 if (section == NULL)
323 sh_num = SHN_UNDEF;
324 else if (section == SECTION_ABS)
325 sh_num = SHN_ABS;
326 else
327 sh_num = section->sh_num;
329 if (!sym->c) {
330 name = get_tok_str(sym->v, NULL);
331 #ifdef CONFIG_TCC_BCHECK
332 if (tcc_state->do_bounds_check) {
333 /* XXX: avoid doing that for statics ? */
334 /* if bound checking is activated, we change some function
335 names by adding the "__bound" prefix */
336 switch(sym->v) {
337 #ifdef TCC_TARGET_PE
338 /* XXX: we rely only on malloc hooks */
339 case TOK_malloc:
340 case TOK_free:
341 case TOK_realloc:
342 case TOK_memalign:
343 case TOK_calloc:
344 #endif
345 case TOK_memcpy:
346 case TOK_memmove:
347 case TOK_memset:
348 case TOK_strlen:
349 case TOK_strcpy:
350 case TOK_alloca:
351 strcpy(buf, "__bound_");
352 strcat(buf, name);
353 name = buf;
354 break;
357 #endif
358 t = sym->type.t;
359 if ((t & VT_BTYPE) == VT_FUNC) {
360 sym_type = STT_FUNC;
361 } else if ((t & VT_BTYPE) == VT_VOID) {
362 sym_type = STT_NOTYPE;
363 } else {
364 sym_type = STT_OBJECT;
366 if (t & VT_STATIC)
367 sym_bind = STB_LOCAL;
368 else
369 sym_bind = STB_GLOBAL;
370 other = 0;
371 #ifdef TCC_TARGET_PE
372 if (sym_type == STT_FUNC && sym->type.ref) {
373 Sym *ref = sym->type.ref;
374 if (ref->f.func_call == FUNC_STDCALL && can_add_underscore) {
375 sprintf(buf1, "_%s@%d", name, ref->f.func_args * PTR_SIZE);
376 name = buf1;
377 other |= ST_PE_STDCALL;
378 can_add_underscore = 0;
381 #endif
382 if (tcc_state->leading_underscore && can_add_underscore) {
383 buf1[0] = '_';
384 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
385 name = buf1;
387 if (sym->asm_label)
388 name = get_tok_str(sym->asm_label, NULL);
389 info = ELFW(ST_INFO)(sym_bind, sym_type);
390 sym->c = set_elf_sym(symtab_section, value, size, info, other, sh_num, name);
391 } else {
392 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
393 esym->st_value = value;
394 esym->st_size = size;
395 esym->st_shndx = sh_num;
397 update_storage(sym);
400 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
401 addr_t value, unsigned long size)
403 put_extern_sym2(sym, section, value, size, 1);
406 /* add a new relocation entry to symbol 'sym' in section 's' */
407 ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type,
408 addr_t addend)
410 int c = 0;
412 if (nocode_wanted && s == cur_text_section)
413 return;
415 if (sym) {
416 if (0 == sym->c)
417 put_extern_sym(sym, NULL, 0, 0);
418 c = sym->c;
421 /* now we can add ELF relocation info */
422 put_elf_reloca(symtab_section, s, offset, type, c, addend);
425 #if PTR_SIZE == 4
426 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
428 greloca(s, sym, offset, type, 0);
430 #endif
432 /* ------------------------------------------------------------------------- */
433 /* symbol allocator */
434 static Sym *__sym_malloc(void)
436 Sym *sym_pool, *sym, *last_sym;
437 int i;
439 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
440 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
442 last_sym = sym_free_first;
443 sym = sym_pool;
444 for(i = 0; i < SYM_POOL_NB; i++) {
445 sym->next = last_sym;
446 last_sym = sym;
447 sym++;
449 sym_free_first = last_sym;
450 return last_sym;
453 static inline Sym *sym_malloc(void)
455 Sym *sym;
456 #ifndef SYM_DEBUG
457 sym = sym_free_first;
458 if (!sym)
459 sym = __sym_malloc();
460 sym_free_first = sym->next;
461 return sym;
462 #else
463 sym = tcc_malloc(sizeof(Sym));
464 return sym;
465 #endif
468 ST_INLN void sym_free(Sym *sym)
470 #ifndef SYM_DEBUG
471 sym->next = sym_free_first;
472 sym_free_first = sym;
473 #else
474 tcc_free(sym);
475 #endif
478 /* push, without hashing */
479 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, int c)
481 Sym *s;
483 s = sym_malloc();
484 memset(s, 0, sizeof *s);
485 s->v = v;
486 s->type.t = t;
487 s->c = c;
488 /* add in stack */
489 s->prev = *ps;
490 *ps = s;
491 return s;
494 /* find a symbol and return its associated structure. 's' is the top
495 of the symbol stack */
496 ST_FUNC Sym *sym_find2(Sym *s, int v)
498 while (s) {
499 if (s->v == v)
500 return s;
501 else if (s->v == -1)
502 return NULL;
503 s = s->prev;
505 return NULL;
508 /* structure lookup */
509 ST_INLN Sym *struct_find(int v)
511 v -= TOK_IDENT;
512 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
513 return NULL;
514 return table_ident[v]->sym_struct;
517 /* find an identifier */
518 ST_INLN Sym *sym_find(int v)
520 v -= TOK_IDENT;
521 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
522 return NULL;
523 return table_ident[v]->sym_identifier;
526 /* push a given symbol on the symbol stack */
527 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
529 Sym *s, **ps;
530 TokenSym *ts;
532 if (local_stack)
533 ps = &local_stack;
534 else
535 ps = &global_stack;
536 s = sym_push2(ps, v, type->t, c);
537 s->type.ref = type->ref;
538 s->r = r;
539 /* don't record fields or anonymous symbols */
540 /* XXX: simplify */
541 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
542 /* record symbol in token array */
543 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
544 if (v & SYM_STRUCT)
545 ps = &ts->sym_struct;
546 else
547 ps = &ts->sym_identifier;
548 s->prev_tok = *ps;
549 *ps = s;
550 s->sym_scope = local_scope;
551 if (s->prev_tok && s->prev_tok->sym_scope == s->sym_scope)
552 tcc_error("redeclaration of '%s'",
553 get_tok_str(v & ~SYM_STRUCT, NULL));
555 return s;
558 /* push a global identifier */
559 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
561 Sym *s, **ps;
562 s = sym_push2(&global_stack, v, t, c);
563 /* don't record anonymous symbol */
564 if (v < SYM_FIRST_ANOM) {
565 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
566 /* modify the top most local identifier, so that
567 sym_identifier will point to 's' when popped */
568 while (*ps != NULL)
569 ps = &(*ps)->prev_tok;
570 s->prev_tok = NULL;
571 *ps = s;
573 return s;
576 /* pop symbols until top reaches 'b'. If KEEP is non-zero don't really
577 pop them yet from the list, but do remove them from the token array. */
578 ST_FUNC void sym_pop(Sym **ptop, Sym *b, int keep)
580 Sym *s, *ss, **ps;
581 TokenSym *ts;
582 int v;
584 s = *ptop;
585 while(s != b) {
586 ss = s->prev;
587 v = s->v;
588 /* remove symbol in token array */
589 /* XXX: simplify */
590 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
591 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
592 if (v & SYM_STRUCT)
593 ps = &ts->sym_struct;
594 else
595 ps = &ts->sym_identifier;
596 *ps = s->prev_tok;
598 if (!keep)
599 sym_free(s);
600 s = ss;
602 if (!keep)
603 *ptop = b;
606 /* ------------------------------------------------------------------------- */
608 static void vsetc(CType *type, int r, CValue *vc)
610 int v;
612 if (vtop >= vstack + (VSTACK_SIZE - 1))
613 tcc_error("memory full (vstack)");
614 /* cannot let cpu flags if other instruction are generated. Also
615 avoid leaving VT_JMP anywhere except on the top of the stack
616 because it would complicate the code generator.
618 Don't do this when nocode_wanted. vtop might come from
619 !nocode_wanted regions (see 88_codeopt.c) and transforming
620 it to a register without actually generating code is wrong
621 as their value might still be used for real. All values
622 we push under nocode_wanted will eventually be popped
623 again, so that the VT_CMP/VT_JMP value will be in vtop
624 when code is unsuppressed again.
626 Same logic below in vswap(); */
627 if (vtop >= vstack && !nocode_wanted) {
628 v = vtop->r & VT_VALMASK;
629 if (v == VT_CMP || (v & ~1) == VT_JMP)
630 gv(RC_INT);
633 vtop++;
634 vtop->type = *type;
635 vtop->r = r;
636 vtop->r2 = VT_CONST;
637 vtop->c = *vc;
638 vtop->sym = NULL;
641 ST_FUNC void vswap(void)
643 SValue tmp;
644 /* cannot vswap cpu flags. See comment at vsetc() above */
645 if (vtop >= vstack && !nocode_wanted) {
646 int v = vtop->r & VT_VALMASK;
647 if (v == VT_CMP || (v & ~1) == VT_JMP)
648 gv(RC_INT);
650 tmp = vtop[0];
651 vtop[0] = vtop[-1];
652 vtop[-1] = tmp;
655 /* pop stack value */
656 ST_FUNC void vpop(void)
658 int v;
659 v = vtop->r & VT_VALMASK;
660 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
661 /* for x86, we need to pop the FP stack */
662 if (v == TREG_ST0) {
663 o(0xd8dd); /* fstp %st(0) */
664 } else
665 #endif
666 if (v == VT_JMP || v == VT_JMPI) {
667 /* need to put correct jump if && or || without test */
668 gsym(vtop->c.i);
670 vtop--;
673 /* push constant of type "type" with useless value */
674 ST_FUNC void vpush(CType *type)
676 vset(type, VT_CONST, 0);
679 /* push integer constant */
680 ST_FUNC void vpushi(int v)
682 CValue cval;
683 cval.i = v;
684 vsetc(&int_type, VT_CONST, &cval);
687 /* push a pointer sized constant */
688 static void vpushs(addr_t v)
690 CValue cval;
691 cval.i = v;
692 vsetc(&size_type, VT_CONST, &cval);
695 /* push arbitrary 64bit constant */
696 ST_FUNC void vpush64(int ty, unsigned long long v)
698 CValue cval;
699 CType ctype;
700 ctype.t = ty;
701 ctype.ref = NULL;
702 cval.i = v;
703 vsetc(&ctype, VT_CONST, &cval);
706 /* push long long constant */
707 static inline void vpushll(long long v)
709 vpush64(VT_LLONG, v);
712 ST_FUNC void vset(CType *type, int r, int v)
714 CValue cval;
716 cval.i = v;
717 vsetc(type, r, &cval);
720 static void vseti(int r, int v)
722 CType type;
723 type.t = VT_INT;
724 type.ref = NULL;
725 vset(&type, r, v);
728 ST_FUNC void vpushv(SValue *v)
730 if (vtop >= vstack + (VSTACK_SIZE - 1))
731 tcc_error("memory full (vstack)");
732 vtop++;
733 *vtop = *v;
736 static void vdup(void)
738 vpushv(vtop);
741 /* rotate n first stack elements to the bottom
742 I1 ... In -> I2 ... In I1 [top is right]
744 ST_FUNC void vrotb(int n)
746 int i;
747 SValue tmp;
749 tmp = vtop[-n + 1];
750 for(i=-n+1;i!=0;i++)
751 vtop[i] = vtop[i+1];
752 vtop[0] = tmp;
755 /* rotate the n elements before entry e towards the top
756 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
758 ST_FUNC void vrote(SValue *e, int n)
760 int i;
761 SValue tmp;
763 tmp = *e;
764 for(i = 0;i < n - 1; i++)
765 e[-i] = e[-i - 1];
766 e[-n + 1] = tmp;
769 /* rotate n first stack elements to the top
770 I1 ... In -> In I1 ... I(n-1) [top is right]
772 ST_FUNC void vrott(int n)
774 vrote(vtop, n);
777 /* push a symbol value of TYPE */
778 static inline void vpushsym(CType *type, Sym *sym)
780 CValue cval;
781 cval.i = 0;
782 vsetc(type, VT_CONST | VT_SYM, &cval);
783 vtop->sym = sym;
786 /* Return a static symbol pointing to a section */
787 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
789 int v;
790 Sym *sym;
792 v = anon_sym++;
793 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
794 sym->type.ref = type->ref;
795 sym->r = VT_CONST | VT_SYM;
796 put_extern_sym(sym, sec, offset, size);
797 return sym;
800 /* push a reference to a section offset by adding a dummy symbol */
801 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
803 vpushsym(type, get_sym_ref(type, sec, offset, size));
806 /* define a new external reference to a symbol 'v' of type 'u' */
807 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
809 Sym *s;
811 s = sym_find(v);
812 if (!s) {
813 /* push forward reference */
814 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
815 s->type.ref = type->ref;
816 s->r = r | VT_CONST | VT_SYM;
818 return s;
821 /* Merge some storage attributes. */
822 static void patch_storage(Sym *sym, AttributeDef *ad, CType *type)
824 if (type && !is_compatible_types(&sym->type, type))
825 tcc_error("incompatible types for redefinition of '%s'",
826 get_tok_str(sym->v, NULL));
827 #ifdef TCC_TARGET_PE
828 if (sym->a.dllimport != ad->a.dllimport)
829 tcc_error("incompatible dll linkage for redefinition of '%s'",
830 get_tok_str(sym->v, NULL));
831 #endif
832 sym->a.dllexport |= ad->a.dllexport;
833 sym->a.weak |= ad->a.weak;
834 if (ad->a.visibility) {
835 int vis = sym->a.visibility;
836 int vis2 = ad->a.visibility;
837 if (vis == STV_DEFAULT)
838 vis = vis2;
839 else if (vis2 != STV_DEFAULT)
840 vis = (vis < vis2) ? vis : vis2;
841 sym->a.visibility = vis;
843 if (ad->a.aligned)
844 sym->a.aligned = ad->a.aligned;
845 if (ad->asm_label)
846 sym->asm_label = ad->asm_label;
847 update_storage(sym);
850 /* define a new external reference to a symbol 'v' */
851 static Sym *external_sym(int v, CType *type, int r, AttributeDef *ad)
853 Sym *s;
854 s = sym_find(v);
855 if (!s) {
856 /* push forward reference */
857 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
858 s->type.t |= VT_EXTERN;
859 s->a = ad->a;
860 s->sym_scope = 0;
861 } else {
862 if (s->type.ref == func_old_type.ref) {
863 s->type.ref = type->ref;
864 s->r = r | VT_CONST | VT_SYM;
865 s->type.t |= VT_EXTERN;
867 patch_storage(s, ad, type);
869 return s;
872 /* push a reference to global symbol v */
873 ST_FUNC void vpush_global_sym(CType *type, int v)
875 vpushsym(type, external_global_sym(v, type, 0));
878 /* save registers up to (vtop - n) stack entry */
879 ST_FUNC void save_regs(int n)
881 SValue *p, *p1;
882 for(p = vstack, p1 = vtop - n; p <= p1; p++)
883 save_reg(p->r);
886 /* save r to the memory stack, and mark it as being free */
887 ST_FUNC void save_reg(int r)
889 save_reg_upstack(r, 0);
892 /* save r to the memory stack, and mark it as being free,
893 if seen up to (vtop - n) stack entry */
894 ST_FUNC void save_reg_upstack(int r, int n)
896 int l, saved, size, align;
897 SValue *p, *p1, sv;
898 CType *type;
900 if ((r &= VT_VALMASK) >= VT_CONST)
901 return;
902 if (nocode_wanted)
903 return;
905 /* modify all stack values */
906 saved = 0;
907 l = 0;
908 for(p = vstack, p1 = vtop - n; p <= p1; p++) {
909 if ((p->r & VT_VALMASK) == r ||
910 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
911 /* must save value on stack if not already done */
912 if (!saved) {
913 /* NOTE: must reload 'r' because r might be equal to r2 */
914 r = p->r & VT_VALMASK;
915 /* store register in the stack */
916 type = &p->type;
917 if ((p->r & VT_LVAL) ||
918 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
919 #if PTR_SIZE == 8
920 type = &char_pointer_type;
921 #else
922 type = &int_type;
923 #endif
924 size = type_size(type, &align);
925 loc = (loc - size) & -align;
926 sv.type.t = type->t;
927 sv.r = VT_LOCAL | VT_LVAL;
928 sv.c.i = loc;
929 store(r, &sv);
930 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
931 /* x86 specific: need to pop fp register ST0 if saved */
932 if (r == TREG_ST0) {
933 o(0xd8dd); /* fstp %st(0) */
935 #endif
936 #if PTR_SIZE == 4
937 /* special long long case */
938 if ((type->t & VT_BTYPE) == VT_LLONG) {
939 sv.c.i += 4;
940 store(p->r2, &sv);
942 #endif
943 l = loc;
944 saved = 1;
946 /* mark that stack entry as being saved on the stack */
947 if (p->r & VT_LVAL) {
948 /* also clear the bounded flag because the
949 relocation address of the function was stored in
950 p->c.i */
951 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
952 } else {
953 p->r = lvalue_type(p->type.t) | VT_LOCAL;
955 p->r2 = VT_CONST;
956 p->c.i = l;
961 #ifdef TCC_TARGET_ARM
962 /* find a register of class 'rc2' with at most one reference on stack.
963 * If none, call get_reg(rc) */
964 ST_FUNC int get_reg_ex(int rc, int rc2)
966 int r;
967 SValue *p;
969 for(r=0;r<NB_REGS;r++) {
970 if (reg_classes[r] & rc2) {
971 int n;
972 n=0;
973 for(p = vstack; p <= vtop; p++) {
974 if ((p->r & VT_VALMASK) == r ||
975 (p->r2 & VT_VALMASK) == r)
976 n++;
978 if (n <= 1)
979 return r;
982 return get_reg(rc);
984 #endif
986 /* find a free register of class 'rc'. If none, save one register */
987 ST_FUNC int get_reg(int rc)
989 int r;
990 SValue *p;
992 /* find a free register */
993 for(r=0;r<NB_REGS;r++) {
994 if (reg_classes[r] & rc) {
995 if (nocode_wanted)
996 return r;
997 for(p=vstack;p<=vtop;p++) {
998 if ((p->r & VT_VALMASK) == r ||
999 (p->r2 & VT_VALMASK) == r)
1000 goto notfound;
1002 return r;
1004 notfound: ;
1007 /* no register left : free the first one on the stack (VERY
1008 IMPORTANT to start from the bottom to ensure that we don't
1009 spill registers used in gen_opi()) */
1010 for(p=vstack;p<=vtop;p++) {
1011 /* look at second register (if long long) */
1012 r = p->r2 & VT_VALMASK;
1013 if (r < VT_CONST && (reg_classes[r] & rc))
1014 goto save_found;
1015 r = p->r & VT_VALMASK;
1016 if (r < VT_CONST && (reg_classes[r] & rc)) {
1017 save_found:
1018 save_reg(r);
1019 return r;
1022 /* Should never comes here */
1023 return -1;
1026 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
1027 if needed */
1028 static void move_reg(int r, int s, int t)
1030 SValue sv;
1032 if (r != s) {
1033 save_reg(r);
1034 sv.type.t = t;
1035 sv.type.ref = NULL;
1036 sv.r = s;
1037 sv.c.i = 0;
1038 load(r, &sv);
1042 /* get address of vtop (vtop MUST BE an lvalue) */
1043 ST_FUNC void gaddrof(void)
1045 vtop->r &= ~VT_LVAL;
1046 /* tricky: if saved lvalue, then we can go back to lvalue */
1047 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
1048 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
1053 #ifdef CONFIG_TCC_BCHECK
1054 /* generate lvalue bound code */
1055 static void gbound(void)
1057 int lval_type;
1058 CType type1;
1060 vtop->r &= ~VT_MUSTBOUND;
1061 /* if lvalue, then use checking code before dereferencing */
1062 if (vtop->r & VT_LVAL) {
1063 /* if not VT_BOUNDED value, then make one */
1064 if (!(vtop->r & VT_BOUNDED)) {
1065 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
1066 /* must save type because we must set it to int to get pointer */
1067 type1 = vtop->type;
1068 vtop->type.t = VT_PTR;
1069 gaddrof();
1070 vpushi(0);
1071 gen_bounded_ptr_add();
1072 vtop->r |= lval_type;
1073 vtop->type = type1;
1075 /* then check for dereferencing */
1076 gen_bounded_ptr_deref();
1079 #endif
1081 static void incr_bf_adr(int o)
1083 vtop->type = char_pointer_type;
1084 gaddrof();
1085 vpushi(o);
1086 gen_op('+');
1087 vtop->type.t = (vtop->type.t & ~(VT_BTYPE|VT_DEFSIGN))
1088 | (VT_BYTE|VT_UNSIGNED);
1089 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
1090 | (VT_LVAL_BYTE|VT_LVAL_UNSIGNED|VT_LVAL);
1093 /* single-byte load mode for packed or otherwise unaligned bitfields */
1094 static void load_packed_bf(CType *type, int bit_pos, int bit_size)
1096 int n, o, bits;
1097 save_reg_upstack(vtop->r, 1);
1098 vpush64(type->t & VT_BTYPE, 0); // B X
1099 bits = 0, o = bit_pos >> 3, bit_pos &= 7;
1100 do {
1101 vswap(); // X B
1102 incr_bf_adr(o);
1103 vdup(); // X B B
1104 n = 8 - bit_pos;
1105 if (n > bit_size)
1106 n = bit_size;
1107 if (bit_pos)
1108 vpushi(bit_pos), gen_op(TOK_SHR), bit_pos = 0; // X B Y
1109 if (n < 8)
1110 vpushi((1 << n) - 1), gen_op('&');
1111 gen_cast(type);
1112 if (bits)
1113 vpushi(bits), gen_op(TOK_SHL);
1114 vrotb(3); // B Y X
1115 gen_op('|'); // B X
1116 bits += n, bit_size -= n, o = 1;
1117 } while (bit_size);
1118 vswap(), vpop();
1119 if (!(type->t & VT_UNSIGNED)) {
1120 n = ((type->t & VT_BTYPE) == VT_LLONG ? 64 : 32) - bits;
1121 vpushi(n), gen_op(TOK_SHL);
1122 vpushi(n), gen_op(TOK_SAR);
1126 /* single-byte store mode for packed or otherwise unaligned bitfields */
1127 static void store_packed_bf(int bit_pos, int bit_size)
1129 int bits, n, o, m, c;
1131 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1132 vswap(); // X B
1133 save_reg_upstack(vtop->r, 1);
1134 bits = 0, o = bit_pos >> 3, bit_pos &= 7;
1135 do {
1136 incr_bf_adr(o); // X B
1137 vswap(); //B X
1138 c ? vdup() : gv_dup(); // B V X
1139 vrott(3); // X B V
1140 if (bits)
1141 vpushi(bits), gen_op(TOK_SHR);
1142 if (bit_pos)
1143 vpushi(bit_pos), gen_op(TOK_SHL);
1144 n = 8 - bit_pos;
1145 if (n > bit_size)
1146 n = bit_size;
1147 if (n < 8) {
1148 m = ((1 << n) - 1) << bit_pos;
1149 vpushi(m), gen_op('&'); // X B V1
1150 vpushv(vtop-1); // X B V1 B
1151 vpushi(m & 0x80 ? ~m & 0x7f : ~m);
1152 gen_op('&'); // X B V1 B1
1153 gen_op('|'); // X B V2
1155 vdup(), vtop[-1] = vtop[-2]; // X B B V2
1156 vstore(), vpop(); // X B
1157 bits += n, bit_size -= n, bit_pos = 0, o = 1;
1158 } while (bit_size);
1159 vpop(), vpop();
1162 static int adjust_bf(SValue *sv, int bit_pos, int bit_size)
1164 int t;
1165 if (0 == sv->type.ref)
1166 return 0;
1167 t = sv->type.ref->auxtype;
1168 if (t != -1 && t != VT_STRUCT) {
1169 sv->type.t = (sv->type.t & ~VT_BTYPE) | t;
1170 sv->r = (sv->r & ~VT_LVAL_TYPE) | lvalue_type(sv->type.t);
1172 return t;
1175 /* store vtop a register belonging to class 'rc'. lvalues are
1176 converted to values. Cannot be used if cannot be converted to
1177 register value (such as structures). */
1178 ST_FUNC int gv(int rc)
1180 int r, bit_pos, bit_size, size, align, rc2;
1182 /* NOTE: get_reg can modify vstack[] */
1183 if (vtop->type.t & VT_BITFIELD) {
1184 CType type;
1186 bit_pos = BIT_POS(vtop->type.t);
1187 bit_size = BIT_SIZE(vtop->type.t);
1188 /* remove bit field info to avoid loops */
1189 vtop->type.t &= ~VT_STRUCT_MASK;
1191 type.ref = NULL;
1192 type.t = vtop->type.t & VT_UNSIGNED;
1193 if ((vtop->type.t & VT_BTYPE) == VT_BOOL)
1194 type.t |= VT_UNSIGNED;
1196 r = adjust_bf(vtop, bit_pos, bit_size);
1198 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
1199 type.t |= VT_LLONG;
1200 else
1201 type.t |= VT_INT;
1203 if (r == VT_STRUCT) {
1204 load_packed_bf(&type, bit_pos, bit_size);
1205 } else {
1206 int bits = (type.t & VT_BTYPE) == VT_LLONG ? 64 : 32;
1207 /* cast to int to propagate signedness in following ops */
1208 gen_cast(&type);
1209 /* generate shifts */
1210 vpushi(bits - (bit_pos + bit_size));
1211 gen_op(TOK_SHL);
1212 vpushi(bits - bit_size);
1213 /* NOTE: transformed to SHR if unsigned */
1214 gen_op(TOK_SAR);
1216 r = gv(rc);
1217 } else {
1218 if (is_float(vtop->type.t) &&
1219 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1220 unsigned long offset;
1221 /* CPUs usually cannot use float constants, so we store them
1222 generically in data segment */
1223 size = type_size(&vtop->type, &align);
1224 if (NODATA_WANTED)
1225 size = 0, align = 1;
1226 offset = section_add(data_section, size, align);
1227 vpush_ref(&vtop->type, data_section, offset, size);
1228 vswap();
1229 init_putv(&vtop->type, data_section, offset);
1230 vtop->r |= VT_LVAL;
1232 #ifdef CONFIG_TCC_BCHECK
1233 if (vtop->r & VT_MUSTBOUND)
1234 gbound();
1235 #endif
1237 r = vtop->r & VT_VALMASK;
1238 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
1239 #ifndef TCC_TARGET_ARM64
1240 if (rc == RC_IRET)
1241 rc2 = RC_LRET;
1242 #ifdef TCC_TARGET_X86_64
1243 else if (rc == RC_FRET)
1244 rc2 = RC_QRET;
1245 #endif
1246 #endif
1247 /* need to reload if:
1248 - constant
1249 - lvalue (need to dereference pointer)
1250 - already a register, but not in the right class */
1251 if (r >= VT_CONST
1252 || (vtop->r & VT_LVAL)
1253 || !(reg_classes[r] & rc)
1254 #if PTR_SIZE == 8
1255 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
1256 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
1257 #else
1258 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
1259 #endif
1262 r = get_reg(rc);
1263 #if PTR_SIZE == 8
1264 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
1265 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
1266 #else
1267 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
1268 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
1269 unsigned long long ll;
1270 #endif
1271 int r2, original_type;
1272 original_type = vtop->type.t;
1273 /* two register type load : expand to two words
1274 temporarily */
1275 #if PTR_SIZE == 4
1276 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1277 /* load constant */
1278 ll = vtop->c.i;
1279 vtop->c.i = ll; /* first word */
1280 load(r, vtop);
1281 vtop->r = r; /* save register value */
1282 vpushi(ll >> 32); /* second word */
1283 } else
1284 #endif
1285 if (vtop->r & VT_LVAL) {
1286 /* We do not want to modifier the long long
1287 pointer here, so the safest (and less
1288 efficient) is to save all the other registers
1289 in the stack. XXX: totally inefficient. */
1290 #if 0
1291 save_regs(1);
1292 #else
1293 /* lvalue_save: save only if used further down the stack */
1294 save_reg_upstack(vtop->r, 1);
1295 #endif
1296 /* load from memory */
1297 vtop->type.t = load_type;
1298 load(r, vtop);
1299 vdup();
1300 vtop[-1].r = r; /* save register value */
1301 /* increment pointer to get second word */
1302 vtop->type.t = addr_type;
1303 gaddrof();
1304 vpushi(load_size);
1305 gen_op('+');
1306 vtop->r |= VT_LVAL;
1307 vtop->type.t = load_type;
1308 } else {
1309 /* move registers */
1310 load(r, vtop);
1311 vdup();
1312 vtop[-1].r = r; /* save register value */
1313 vtop->r = vtop[-1].r2;
1315 /* Allocate second register. Here we rely on the fact that
1316 get_reg() tries first to free r2 of an SValue. */
1317 r2 = get_reg(rc2);
1318 load(r2, vtop);
1319 vpop();
1320 /* write second register */
1321 vtop->r2 = r2;
1322 vtop->type.t = original_type;
1323 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
1324 int t1, t;
1325 /* lvalue of scalar type : need to use lvalue type
1326 because of possible cast */
1327 t = vtop->type.t;
1328 t1 = t;
1329 /* compute memory access type */
1330 if (vtop->r & VT_LVAL_BYTE)
1331 t = VT_BYTE;
1332 else if (vtop->r & VT_LVAL_SHORT)
1333 t = VT_SHORT;
1334 if (vtop->r & VT_LVAL_UNSIGNED)
1335 t |= VT_UNSIGNED;
1336 vtop->type.t = t;
1337 load(r, vtop);
1338 /* restore wanted type */
1339 vtop->type.t = t1;
1340 } else {
1341 /* one register type load */
1342 load(r, vtop);
1345 vtop->r = r;
1346 #ifdef TCC_TARGET_C67
1347 /* uses register pairs for doubles */
1348 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
1349 vtop->r2 = r+1;
1350 #endif
1352 return r;
1355 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
1356 ST_FUNC void gv2(int rc1, int rc2)
1358 int v;
1360 /* generate more generic register first. But VT_JMP or VT_CMP
1361 values must be generated first in all cases to avoid possible
1362 reload errors */
1363 v = vtop[0].r & VT_VALMASK;
1364 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
1365 vswap();
1366 gv(rc1);
1367 vswap();
1368 gv(rc2);
1369 /* test if reload is needed for first register */
1370 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
1371 vswap();
1372 gv(rc1);
1373 vswap();
1375 } else {
1376 gv(rc2);
1377 vswap();
1378 gv(rc1);
1379 vswap();
1380 /* test if reload is needed for first register */
1381 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
1382 gv(rc2);
1387 #ifndef TCC_TARGET_ARM64
1388 /* wrapper around RC_FRET to return a register by type */
1389 static int rc_fret(int t)
1391 #ifdef TCC_TARGET_X86_64
1392 if (t == VT_LDOUBLE) {
1393 return RC_ST0;
1395 #endif
1396 return RC_FRET;
1398 #endif
1400 /* wrapper around REG_FRET to return a register by type */
1401 static int reg_fret(int t)
1403 #ifdef TCC_TARGET_X86_64
1404 if (t == VT_LDOUBLE) {
1405 return TREG_ST0;
1407 #endif
1408 return REG_FRET;
1411 #if PTR_SIZE == 4
1412 /* expand 64bit on stack in two ints */
1413 static void lexpand(void)
1415 int u, v;
1416 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1417 v = vtop->r & (VT_VALMASK | VT_LVAL);
1418 if (v == VT_CONST) {
1419 vdup();
1420 vtop[0].c.i >>= 32;
1421 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1422 vdup();
1423 vtop[0].c.i += 4;
1424 } else {
1425 gv(RC_INT);
1426 vdup();
1427 vtop[0].r = vtop[-1].r2;
1428 vtop[0].r2 = vtop[-1].r2 = VT_CONST;
1430 vtop[0].type.t = vtop[-1].type.t = VT_INT | u;
1432 #endif
1434 #ifdef TCC_TARGET_ARM
1435 /* expand long long on stack */
1436 ST_FUNC void lexpand_nr(void)
1438 int u,v;
1440 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1441 vdup();
1442 vtop->r2 = VT_CONST;
1443 vtop->type.t = VT_INT | u;
1444 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1445 if (v == VT_CONST) {
1446 vtop[-1].c.i = vtop->c.i;
1447 vtop->c.i = vtop->c.i >> 32;
1448 vtop->r = VT_CONST;
1449 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1450 vtop->c.i += 4;
1451 vtop->r = vtop[-1].r;
1452 } else if (v > VT_CONST) {
1453 vtop--;
1454 lexpand();
1455 } else
1456 vtop->r = vtop[-1].r2;
1457 vtop[-1].r2 = VT_CONST;
1458 vtop[-1].type.t = VT_INT | u;
1460 #endif
1462 #if PTR_SIZE == 4
1463 /* build a long long from two ints */
1464 static void lbuild(int t)
1466 gv2(RC_INT, RC_INT);
1467 vtop[-1].r2 = vtop[0].r;
1468 vtop[-1].type.t = t;
1469 vpop();
1471 #endif
1473 /* convert stack entry to register and duplicate its value in another
1474 register */
1475 static void gv_dup(void)
1477 int rc, t, r, r1;
1478 SValue sv;
1480 t = vtop->type.t;
1481 #if PTR_SIZE == 4
1482 if ((t & VT_BTYPE) == VT_LLONG) {
1483 if (t & VT_BITFIELD) {
1484 gv(RC_INT);
1485 t = vtop->type.t;
1487 lexpand();
1488 gv_dup();
1489 vswap();
1490 vrotb(3);
1491 gv_dup();
1492 vrotb(4);
1493 /* stack: H L L1 H1 */
1494 lbuild(t);
1495 vrotb(3);
1496 vrotb(3);
1497 vswap();
1498 lbuild(t);
1499 vswap();
1500 } else
1501 #endif
1503 /* duplicate value */
1504 rc = RC_INT;
1505 sv.type.t = VT_INT;
1506 if (is_float(t)) {
1507 rc = RC_FLOAT;
1508 #ifdef TCC_TARGET_X86_64
1509 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1510 rc = RC_ST0;
1512 #endif
1513 sv.type.t = t;
1515 r = gv(rc);
1516 r1 = get_reg(rc);
1517 sv.r = r;
1518 sv.c.i = 0;
1519 load(r1, &sv); /* move r to r1 */
1520 vdup();
1521 /* duplicates value */
1522 if (r != r1)
1523 vtop->r = r1;
1527 /* Generate value test
1529 * Generate a test for any value (jump, comparison and integers) */
1530 ST_FUNC int gvtst(int inv, int t)
1532 int v = vtop->r & VT_VALMASK;
1533 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1534 vpushi(0);
1535 gen_op(TOK_NE);
1537 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1538 /* constant jmp optimization */
1539 if ((vtop->c.i != 0) != inv)
1540 t = gjmp(t);
1541 vtop--;
1542 return t;
1544 return gtst(inv, t);
1547 #if PTR_SIZE == 4
1548 /* generate CPU independent (unsigned) long long operations */
1549 static void gen_opl(int op)
1551 int t, a, b, op1, c, i;
1552 int func;
1553 unsigned short reg_iret = REG_IRET;
1554 unsigned short reg_lret = REG_LRET;
1555 SValue tmp;
1557 switch(op) {
1558 case '/':
1559 case TOK_PDIV:
1560 func = TOK___divdi3;
1561 goto gen_func;
1562 case TOK_UDIV:
1563 func = TOK___udivdi3;
1564 goto gen_func;
1565 case '%':
1566 func = TOK___moddi3;
1567 goto gen_mod_func;
1568 case TOK_UMOD:
1569 func = TOK___umoddi3;
1570 gen_mod_func:
1571 #ifdef TCC_ARM_EABI
1572 reg_iret = TREG_R2;
1573 reg_lret = TREG_R3;
1574 #endif
1575 gen_func:
1576 /* call generic long long function */
1577 vpush_global_sym(&func_old_type, func);
1578 vrott(3);
1579 gfunc_call(2);
1580 vpushi(0);
1581 vtop->r = reg_iret;
1582 vtop->r2 = reg_lret;
1583 break;
1584 case '^':
1585 case '&':
1586 case '|':
1587 case '*':
1588 case '+':
1589 case '-':
1590 //pv("gen_opl A",0,2);
1591 t = vtop->type.t;
1592 vswap();
1593 lexpand();
1594 vrotb(3);
1595 lexpand();
1596 /* stack: L1 H1 L2 H2 */
1597 tmp = vtop[0];
1598 vtop[0] = vtop[-3];
1599 vtop[-3] = tmp;
1600 tmp = vtop[-2];
1601 vtop[-2] = vtop[-3];
1602 vtop[-3] = tmp;
1603 vswap();
1604 /* stack: H1 H2 L1 L2 */
1605 //pv("gen_opl B",0,4);
1606 if (op == '*') {
1607 vpushv(vtop - 1);
1608 vpushv(vtop - 1);
1609 gen_op(TOK_UMULL);
1610 lexpand();
1611 /* stack: H1 H2 L1 L2 ML MH */
1612 for(i=0;i<4;i++)
1613 vrotb(6);
1614 /* stack: ML MH H1 H2 L1 L2 */
1615 tmp = vtop[0];
1616 vtop[0] = vtop[-2];
1617 vtop[-2] = tmp;
1618 /* stack: ML MH H1 L2 H2 L1 */
1619 gen_op('*');
1620 vrotb(3);
1621 vrotb(3);
1622 gen_op('*');
1623 /* stack: ML MH M1 M2 */
1624 gen_op('+');
1625 gen_op('+');
1626 } else if (op == '+' || op == '-') {
1627 /* XXX: add non carry method too (for MIPS or alpha) */
1628 if (op == '+')
1629 op1 = TOK_ADDC1;
1630 else
1631 op1 = TOK_SUBC1;
1632 gen_op(op1);
1633 /* stack: H1 H2 (L1 op L2) */
1634 vrotb(3);
1635 vrotb(3);
1636 gen_op(op1 + 1); /* TOK_xxxC2 */
1637 } else {
1638 gen_op(op);
1639 /* stack: H1 H2 (L1 op L2) */
1640 vrotb(3);
1641 vrotb(3);
1642 /* stack: (L1 op L2) H1 H2 */
1643 gen_op(op);
1644 /* stack: (L1 op L2) (H1 op H2) */
1646 /* stack: L H */
1647 lbuild(t);
1648 break;
1649 case TOK_SAR:
1650 case TOK_SHR:
1651 case TOK_SHL:
1652 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1653 t = vtop[-1].type.t;
1654 vswap();
1655 lexpand();
1656 vrotb(3);
1657 /* stack: L H shift */
1658 c = (int)vtop->c.i;
1659 /* constant: simpler */
1660 /* NOTE: all comments are for SHL. the other cases are
1661 done by swapping words */
1662 vpop();
1663 if (op != TOK_SHL)
1664 vswap();
1665 if (c >= 32) {
1666 /* stack: L H */
1667 vpop();
1668 if (c > 32) {
1669 vpushi(c - 32);
1670 gen_op(op);
1672 if (op != TOK_SAR) {
1673 vpushi(0);
1674 } else {
1675 gv_dup();
1676 vpushi(31);
1677 gen_op(TOK_SAR);
1679 vswap();
1680 } else {
1681 vswap();
1682 gv_dup();
1683 /* stack: H L L */
1684 vpushi(c);
1685 gen_op(op);
1686 vswap();
1687 vpushi(32 - c);
1688 if (op == TOK_SHL)
1689 gen_op(TOK_SHR);
1690 else
1691 gen_op(TOK_SHL);
1692 vrotb(3);
1693 /* stack: L L H */
1694 vpushi(c);
1695 if (op == TOK_SHL)
1696 gen_op(TOK_SHL);
1697 else
1698 gen_op(TOK_SHR);
1699 gen_op('|');
1701 if (op != TOK_SHL)
1702 vswap();
1703 lbuild(t);
1704 } else {
1705 /* XXX: should provide a faster fallback on x86 ? */
1706 switch(op) {
1707 case TOK_SAR:
1708 func = TOK___ashrdi3;
1709 goto gen_func;
1710 case TOK_SHR:
1711 func = TOK___lshrdi3;
1712 goto gen_func;
1713 case TOK_SHL:
1714 func = TOK___ashldi3;
1715 goto gen_func;
1718 break;
1719 default:
1720 /* compare operations */
1721 t = vtop->type.t;
1722 vswap();
1723 lexpand();
1724 vrotb(3);
1725 lexpand();
1726 /* stack: L1 H1 L2 H2 */
1727 tmp = vtop[-1];
1728 vtop[-1] = vtop[-2];
1729 vtop[-2] = tmp;
1730 /* stack: L1 L2 H1 H2 */
1731 /* compare high */
1732 op1 = op;
1733 /* when values are equal, we need to compare low words. since
1734 the jump is inverted, we invert the test too. */
1735 if (op1 == TOK_LT)
1736 op1 = TOK_LE;
1737 else if (op1 == TOK_GT)
1738 op1 = TOK_GE;
1739 else if (op1 == TOK_ULT)
1740 op1 = TOK_ULE;
1741 else if (op1 == TOK_UGT)
1742 op1 = TOK_UGE;
1743 a = 0;
1744 b = 0;
1745 gen_op(op1);
1746 if (op == TOK_NE) {
1747 b = gvtst(0, 0);
1748 } else {
1749 a = gvtst(1, 0);
1750 if (op != TOK_EQ) {
1751 /* generate non equal test */
1752 vpushi(TOK_NE);
1753 vtop->r = VT_CMP;
1754 b = gvtst(0, 0);
1757 /* compare low. Always unsigned */
1758 op1 = op;
1759 if (op1 == TOK_LT)
1760 op1 = TOK_ULT;
1761 else if (op1 == TOK_LE)
1762 op1 = TOK_ULE;
1763 else if (op1 == TOK_GT)
1764 op1 = TOK_UGT;
1765 else if (op1 == TOK_GE)
1766 op1 = TOK_UGE;
1767 gen_op(op1);
1768 a = gvtst(1, a);
1769 gsym(b);
1770 vseti(VT_JMPI, a);
1771 break;
1774 #endif
1776 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1778 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1779 return (a ^ b) >> 63 ? -x : x;
1782 static int gen_opic_lt(uint64_t a, uint64_t b)
1784 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1787 /* handle integer constant optimizations and various machine
1788 independent opt */
1789 static void gen_opic(int op)
1791 SValue *v1 = vtop - 1;
1792 SValue *v2 = vtop;
1793 int t1 = v1->type.t & VT_BTYPE;
1794 int t2 = v2->type.t & VT_BTYPE;
1795 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1796 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1797 uint64_t l1 = c1 ? v1->c.i : 0;
1798 uint64_t l2 = c2 ? v2->c.i : 0;
1799 int shm = (t1 == VT_LLONG) ? 63 : 31;
1801 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1802 l1 = ((uint32_t)l1 |
1803 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1804 if (t2 != VT_LLONG && (PTR_SIZE != 8 || t2 != VT_PTR))
1805 l2 = ((uint32_t)l2 |
1806 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1808 if (c1 && c2) {
1809 switch(op) {
1810 case '+': l1 += l2; break;
1811 case '-': l1 -= l2; break;
1812 case '&': l1 &= l2; break;
1813 case '^': l1 ^= l2; break;
1814 case '|': l1 |= l2; break;
1815 case '*': l1 *= l2; break;
1817 case TOK_PDIV:
1818 case '/':
1819 case '%':
1820 case TOK_UDIV:
1821 case TOK_UMOD:
1822 /* if division by zero, generate explicit division */
1823 if (l2 == 0) {
1824 if (const_wanted)
1825 tcc_error("division by zero in constant");
1826 goto general_case;
1828 switch(op) {
1829 default: l1 = gen_opic_sdiv(l1, l2); break;
1830 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1831 case TOK_UDIV: l1 = l1 / l2; break;
1832 case TOK_UMOD: l1 = l1 % l2; break;
1834 break;
1835 case TOK_SHL: l1 <<= (l2 & shm); break;
1836 case TOK_SHR: l1 >>= (l2 & shm); break;
1837 case TOK_SAR:
1838 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1839 break;
1840 /* tests */
1841 case TOK_ULT: l1 = l1 < l2; break;
1842 case TOK_UGE: l1 = l1 >= l2; break;
1843 case TOK_EQ: l1 = l1 == l2; break;
1844 case TOK_NE: l1 = l1 != l2; break;
1845 case TOK_ULE: l1 = l1 <= l2; break;
1846 case TOK_UGT: l1 = l1 > l2; break;
1847 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1848 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1849 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1850 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1851 /* logical */
1852 case TOK_LAND: l1 = l1 && l2; break;
1853 case TOK_LOR: l1 = l1 || l2; break;
1854 default:
1855 goto general_case;
1857 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1858 l1 = ((uint32_t)l1 |
1859 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1860 v1->c.i = l1;
1861 vtop--;
1862 } else {
1863 /* if commutative ops, put c2 as constant */
1864 if (c1 && (op == '+' || op == '&' || op == '^' ||
1865 op == '|' || op == '*')) {
1866 vswap();
1867 c2 = c1; //c = c1, c1 = c2, c2 = c;
1868 l2 = l1; //l = l1, l1 = l2, l2 = l;
1870 if (!const_wanted &&
1871 c1 && ((l1 == 0 &&
1872 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1873 (l1 == -1 && op == TOK_SAR))) {
1874 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1875 vtop--;
1876 } else if (!const_wanted &&
1877 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1878 (op == '|' &&
1879 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))) ||
1880 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1881 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1882 if (l2 == 1)
1883 vtop->c.i = 0;
1884 vswap();
1885 vtop--;
1886 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1887 op == TOK_PDIV) &&
1888 l2 == 1) ||
1889 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1890 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1891 l2 == 0) ||
1892 (op == '&' &&
1893 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))))) {
1894 /* filter out NOP operations like x*1, x-0, x&-1... */
1895 vtop--;
1896 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1897 /* try to use shifts instead of muls or divs */
1898 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1899 int n = -1;
1900 while (l2) {
1901 l2 >>= 1;
1902 n++;
1904 vtop->c.i = n;
1905 if (op == '*')
1906 op = TOK_SHL;
1907 else if (op == TOK_PDIV)
1908 op = TOK_SAR;
1909 else
1910 op = TOK_SHR;
1912 goto general_case;
1913 } else if (c2 && (op == '+' || op == '-') &&
1914 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1915 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1916 /* symbol + constant case */
1917 if (op == '-')
1918 l2 = -l2;
1919 l2 += vtop[-1].c.i;
1920 /* The backends can't always deal with addends to symbols
1921 larger than +-1<<31. Don't construct such. */
1922 if ((int)l2 != l2)
1923 goto general_case;
1924 vtop--;
1925 vtop->c.i = l2;
1926 } else {
1927 general_case:
1928 /* call low level op generator */
1929 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1930 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1931 gen_opl(op);
1932 else
1933 gen_opi(op);
1938 /* generate a floating point operation with constant propagation */
1939 static void gen_opif(int op)
1941 int c1, c2;
1942 SValue *v1, *v2;
1943 #if defined _MSC_VER && defined _AMD64_
1944 /* avoid bad optimization with f1 -= f2 for f1:-0.0, f2:0.0 */
1945 volatile
1946 #endif
1947 long double f1, f2;
1949 v1 = vtop - 1;
1950 v2 = vtop;
1951 /* currently, we cannot do computations with forward symbols */
1952 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1953 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1954 if (c1 && c2) {
1955 if (v1->type.t == VT_FLOAT) {
1956 f1 = v1->c.f;
1957 f2 = v2->c.f;
1958 } else if (v1->type.t == VT_DOUBLE) {
1959 f1 = v1->c.d;
1960 f2 = v2->c.d;
1961 } else {
1962 f1 = v1->c.ld;
1963 f2 = v2->c.ld;
1966 /* NOTE: we only do constant propagation if finite number (not
1967 NaN or infinity) (ANSI spec) */
1968 if (!ieee_finite(f1) || !ieee_finite(f2))
1969 goto general_case;
1971 switch(op) {
1972 case '+': f1 += f2; break;
1973 case '-': f1 -= f2; break;
1974 case '*': f1 *= f2; break;
1975 case '/':
1976 if (f2 == 0.0) {
1977 if (const_wanted)
1978 tcc_error("division by zero in constant");
1979 goto general_case;
1981 f1 /= f2;
1982 break;
1983 /* XXX: also handles tests ? */
1984 default:
1985 goto general_case;
1987 /* XXX: overflow test ? */
1988 if (v1->type.t == VT_FLOAT) {
1989 v1->c.f = f1;
1990 } else if (v1->type.t == VT_DOUBLE) {
1991 v1->c.d = f1;
1992 } else {
1993 v1->c.ld = f1;
1995 vtop--;
1996 } else {
1997 general_case:
1998 gen_opf(op);
2002 static int pointed_size(CType *type)
2004 int align;
2005 return type_size(pointed_type(type), &align);
2008 static void vla_runtime_pointed_size(CType *type)
2010 int align;
2011 vla_runtime_type_size(pointed_type(type), &align);
2014 static inline int is_null_pointer(SValue *p)
2016 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
2017 return 0;
2018 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
2019 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
2020 ((p->type.t & VT_BTYPE) == VT_PTR &&
2021 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
2024 static inline int is_integer_btype(int bt)
2026 return (bt == VT_BYTE || bt == VT_SHORT ||
2027 bt == VT_INT || bt == VT_LLONG);
2030 /* check types for comparison or subtraction of pointers */
2031 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
2033 CType *type1, *type2, tmp_type1, tmp_type2;
2034 int bt1, bt2;
2036 /* null pointers are accepted for all comparisons as gcc */
2037 if (is_null_pointer(p1) || is_null_pointer(p2))
2038 return;
2039 type1 = &p1->type;
2040 type2 = &p2->type;
2041 bt1 = type1->t & VT_BTYPE;
2042 bt2 = type2->t & VT_BTYPE;
2043 /* accept comparison between pointer and integer with a warning */
2044 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
2045 if (op != TOK_LOR && op != TOK_LAND )
2046 tcc_warning("comparison between pointer and integer");
2047 return;
2050 /* both must be pointers or implicit function pointers */
2051 if (bt1 == VT_PTR) {
2052 type1 = pointed_type(type1);
2053 } else if (bt1 != VT_FUNC)
2054 goto invalid_operands;
2056 if (bt2 == VT_PTR) {
2057 type2 = pointed_type(type2);
2058 } else if (bt2 != VT_FUNC) {
2059 invalid_operands:
2060 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
2062 if ((type1->t & VT_BTYPE) == VT_VOID ||
2063 (type2->t & VT_BTYPE) == VT_VOID)
2064 return;
2065 tmp_type1 = *type1;
2066 tmp_type2 = *type2;
2067 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2068 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2069 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2070 /* gcc-like error if '-' is used */
2071 if (op == '-')
2072 goto invalid_operands;
2073 else
2074 tcc_warning("comparison of distinct pointer types lacks a cast");
2078 /* generic gen_op: handles types problems */
2079 ST_FUNC void gen_op(int op)
2081 int u, t1, t2, bt1, bt2, t;
2082 CType type1;
2084 redo:
2085 t1 = vtop[-1].type.t;
2086 t2 = vtop[0].type.t;
2087 bt1 = t1 & VT_BTYPE;
2088 bt2 = t2 & VT_BTYPE;
2090 if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
2091 tcc_error("operation on a struct");
2092 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
2093 if (bt2 == VT_FUNC) {
2094 mk_pointer(&vtop->type);
2095 gaddrof();
2097 if (bt1 == VT_FUNC) {
2098 vswap();
2099 mk_pointer(&vtop->type);
2100 gaddrof();
2101 vswap();
2103 goto redo;
2104 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
2105 /* at least one operand is a pointer */
2106 /* relational op: must be both pointers */
2107 if (op >= TOK_ULT && op <= TOK_LOR) {
2108 check_comparison_pointer_types(vtop - 1, vtop, op);
2109 /* pointers are handled are unsigned */
2110 #if PTR_SIZE == 8
2111 t = VT_LLONG | VT_UNSIGNED;
2112 #else
2113 t = VT_INT | VT_UNSIGNED;
2114 #endif
2115 goto std_op;
2117 /* if both pointers, then it must be the '-' op */
2118 if (bt1 == VT_PTR && bt2 == VT_PTR) {
2119 if (op != '-')
2120 tcc_error("cannot use pointers here");
2121 check_comparison_pointer_types(vtop - 1, vtop, op);
2122 /* XXX: check that types are compatible */
2123 if (vtop[-1].type.t & VT_VLA) {
2124 vla_runtime_pointed_size(&vtop[-1].type);
2125 } else {
2126 vpushi(pointed_size(&vtop[-1].type));
2128 vrott(3);
2129 gen_opic(op);
2130 /* set to integer type */
2131 #if PTR_SIZE == 8
2132 vtop->type.t = VT_LLONG;
2133 #else
2134 vtop->type.t = VT_INT;
2135 #endif
2136 vswap();
2137 gen_op(TOK_PDIV);
2138 } else {
2139 /* exactly one pointer : must be '+' or '-'. */
2140 if (op != '-' && op != '+')
2141 tcc_error("cannot use pointers here");
2142 /* Put pointer as first operand */
2143 if (bt2 == VT_PTR) {
2144 vswap();
2145 t = t1, t1 = t2, t2 = t;
2147 #if PTR_SIZE == 4
2148 if ((vtop[0].type.t & VT_BTYPE) == VT_LLONG)
2149 /* XXX: truncate here because gen_opl can't handle ptr + long long */
2150 gen_cast_s(VT_INT);
2151 #endif
2152 type1 = vtop[-1].type;
2153 type1.t &= ~VT_ARRAY;
2154 if (vtop[-1].type.t & VT_VLA)
2155 vla_runtime_pointed_size(&vtop[-1].type);
2156 else {
2157 u = pointed_size(&vtop[-1].type);
2158 if (u < 0)
2159 tcc_error("unknown array element size");
2160 #if PTR_SIZE == 8
2161 vpushll(u);
2162 #else
2163 /* XXX: cast to int ? (long long case) */
2164 vpushi(u);
2165 #endif
2167 gen_op('*');
2168 #if 0
2169 /* #ifdef CONFIG_TCC_BCHECK
2170 The main reason to removing this code:
2171 #include <stdio.h>
2172 int main ()
2174 int v[10];
2175 int i = 10;
2176 int j = 9;
2177 fprintf(stderr, "v+i-j = %p\n", v+i-j);
2178 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
2180 When this code is on. then the output looks like
2181 v+i-j = 0xfffffffe
2182 v+(i-j) = 0xbff84000
2184 /* if evaluating constant expression, no code should be
2185 generated, so no bound check */
2186 if (tcc_state->do_bounds_check && !const_wanted) {
2187 /* if bounded pointers, we generate a special code to
2188 test bounds */
2189 if (op == '-') {
2190 vpushi(0);
2191 vswap();
2192 gen_op('-');
2194 gen_bounded_ptr_add();
2195 } else
2196 #endif
2198 gen_opic(op);
2200 /* put again type if gen_opic() swaped operands */
2201 vtop->type = type1;
2203 } else if (is_float(bt1) || is_float(bt2)) {
2204 /* compute bigger type and do implicit casts */
2205 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
2206 t = VT_LDOUBLE;
2207 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
2208 t = VT_DOUBLE;
2209 } else {
2210 t = VT_FLOAT;
2212 /* floats can only be used for a few operations */
2213 if (op != '+' && op != '-' && op != '*' && op != '/' &&
2214 (op < TOK_ULT || op > TOK_GT))
2215 tcc_error("invalid operands for binary operation");
2216 goto std_op;
2217 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
2218 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
2219 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (t | VT_UNSIGNED))
2220 t |= VT_UNSIGNED;
2221 goto std_op;
2222 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
2223 /* cast to biggest op */
2224 t = VT_LLONG;
2225 /* check if we need to keep type as long or as long long */
2226 if ((t1 & VT_LONG && (t2 & (VT_BTYPE | VT_LONG)) != VT_LLONG) ||
2227 (t2 & VT_LONG && (t1 & (VT_BTYPE | VT_LONG)) != VT_LLONG))
2228 t |= VT_LONG;
2229 /* convert to unsigned if it does not fit in a long long */
2230 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED) ||
2231 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED))
2232 t |= VT_UNSIGNED;
2233 goto std_op;
2234 } else {
2235 /* integer operations */
2236 t = VT_INT;
2238 if ((t1 & VT_LONG) || (t2 & VT_LONG))
2239 t |= VT_LONG;
2241 /* convert to unsigned if it does not fit in an integer */
2242 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED) ||
2243 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED))
2244 t |= VT_UNSIGNED;
2245 std_op:
2246 /* XXX: currently, some unsigned operations are explicit, so
2247 we modify them here */
2248 if (t & VT_UNSIGNED) {
2249 if (op == TOK_SAR)
2250 op = TOK_SHR;
2251 else if (op == '/')
2252 op = TOK_UDIV;
2253 else if (op == '%')
2254 op = TOK_UMOD;
2255 else if (op == TOK_LT)
2256 op = TOK_ULT;
2257 else if (op == TOK_GT)
2258 op = TOK_UGT;
2259 else if (op == TOK_LE)
2260 op = TOK_ULE;
2261 else if (op == TOK_GE)
2262 op = TOK_UGE;
2264 vswap();
2265 type1.t = t;
2266 type1.ref = NULL;
2267 gen_cast(&type1);
2268 vswap();
2269 /* special case for shifts and long long: we keep the shift as
2270 an integer */
2271 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
2272 type1.t = VT_INT;
2273 gen_cast(&type1);
2274 if (is_float(t))
2275 gen_opif(op);
2276 else
2277 gen_opic(op);
2278 if (op >= TOK_ULT && op <= TOK_GT) {
2279 /* relational op: the result is an int */
2280 vtop->type.t = VT_INT;
2281 } else {
2282 vtop->type.t = t;
2285 // Make sure that we have converted to an rvalue:
2286 if (vtop->r & VT_LVAL)
2287 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
2290 #ifndef TCC_TARGET_ARM
2291 /* generic itof for unsigned long long case */
2292 static void gen_cvt_itof1(int t)
2294 #ifdef TCC_TARGET_ARM64
2295 gen_cvt_itof(t);
2296 #else
2297 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
2298 (VT_LLONG | VT_UNSIGNED)) {
2300 if (t == VT_FLOAT)
2301 vpush_global_sym(&func_old_type, TOK___floatundisf);
2302 #if LDOUBLE_SIZE != 8
2303 else if (t == VT_LDOUBLE)
2304 vpush_global_sym(&func_old_type, TOK___floatundixf);
2305 #endif
2306 else
2307 vpush_global_sym(&func_old_type, TOK___floatundidf);
2308 vrott(2);
2309 gfunc_call(1);
2310 vpushi(0);
2311 vtop->r = reg_fret(t);
2312 } else {
2313 gen_cvt_itof(t);
2315 #endif
2317 #endif
2319 /* generic ftoi for unsigned long long case */
2320 static void gen_cvt_ftoi1(int t)
2322 #ifdef TCC_TARGET_ARM64
2323 gen_cvt_ftoi(t);
2324 #else
2325 int st;
2327 if (t == (VT_LLONG | VT_UNSIGNED)) {
2328 /* not handled natively */
2329 st = vtop->type.t & VT_BTYPE;
2330 if (st == VT_FLOAT)
2331 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
2332 #if LDOUBLE_SIZE != 8
2333 else if (st == VT_LDOUBLE)
2334 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
2335 #endif
2336 else
2337 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
2338 vrott(2);
2339 gfunc_call(1);
2340 vpushi(0);
2341 vtop->r = REG_IRET;
2342 vtop->r2 = REG_LRET;
2343 } else {
2344 gen_cvt_ftoi(t);
2346 #endif
2349 /* force char or short cast */
2350 static void force_charshort_cast(int t)
2352 int bits, dbt;
2354 /* cannot cast static initializers */
2355 if (STATIC_DATA_WANTED)
2356 return;
2358 dbt = t & VT_BTYPE;
2359 /* XXX: add optimization if lvalue : just change type and offset */
2360 if (dbt == VT_BYTE)
2361 bits = 8;
2362 else
2363 bits = 16;
2364 if (t & VT_UNSIGNED) {
2365 vpushi((1 << bits) - 1);
2366 gen_op('&');
2367 } else {
2368 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
2369 bits = 64 - bits;
2370 else
2371 bits = 32 - bits;
2372 vpushi(bits);
2373 gen_op(TOK_SHL);
2374 /* result must be signed or the SAR is converted to an SHL
2375 This was not the case when "t" was a signed short
2376 and the last value on the stack was an unsigned int */
2377 vtop->type.t &= ~VT_UNSIGNED;
2378 vpushi(bits);
2379 gen_op(TOK_SAR);
2383 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
2384 static void gen_cast_s(int t)
2386 CType type;
2387 type.t = t;
2388 type.ref = NULL;
2389 gen_cast(&type);
2392 static void gen_cast(CType *type)
2394 int sbt, dbt, sf, df, c, p;
2396 /* special delayed cast for char/short */
2397 /* XXX: in some cases (multiple cascaded casts), it may still
2398 be incorrect */
2399 if (vtop->r & VT_MUSTCAST) {
2400 vtop->r &= ~VT_MUSTCAST;
2401 force_charshort_cast(vtop->type.t);
2404 /* bitfields first get cast to ints */
2405 if (vtop->type.t & VT_BITFIELD) {
2406 gv(RC_INT);
2409 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
2410 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
2412 if (sbt != dbt) {
2413 sf = is_float(sbt);
2414 df = is_float(dbt);
2415 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2416 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
2417 if (c) {
2418 /* constant case: we can do it now */
2419 /* XXX: in ISOC, cannot do it if error in convert */
2420 if (sbt == VT_FLOAT)
2421 vtop->c.ld = vtop->c.f;
2422 else if (sbt == VT_DOUBLE)
2423 vtop->c.ld = vtop->c.d;
2425 if (df) {
2426 if ((sbt & VT_BTYPE) == VT_LLONG) {
2427 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
2428 vtop->c.ld = vtop->c.i;
2429 else
2430 vtop->c.ld = -(long double)-vtop->c.i;
2431 } else if(!sf) {
2432 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2433 vtop->c.ld = (uint32_t)vtop->c.i;
2434 else
2435 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2438 if (dbt == VT_FLOAT)
2439 vtop->c.f = (float)vtop->c.ld;
2440 else if (dbt == VT_DOUBLE)
2441 vtop->c.d = (double)vtop->c.ld;
2442 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2443 vtop->c.i = vtop->c.ld;
2444 } else if (sf && dbt == VT_BOOL) {
2445 vtop->c.i = (vtop->c.ld != 0);
2446 } else {
2447 if(sf)
2448 vtop->c.i = vtop->c.ld;
2449 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2451 else if (sbt & VT_UNSIGNED)
2452 vtop->c.i = (uint32_t)vtop->c.i;
2453 #if PTR_SIZE == 8
2454 else if (sbt == VT_PTR)
2456 #endif
2457 else if (sbt != VT_LLONG)
2458 vtop->c.i = ((uint32_t)vtop->c.i |
2459 -(vtop->c.i & 0x80000000));
2461 if (dbt == (VT_LLONG|VT_UNSIGNED))
2463 else if (dbt == VT_BOOL)
2464 vtop->c.i = (vtop->c.i != 0);
2465 #if PTR_SIZE == 8
2466 else if (dbt == VT_PTR)
2468 #endif
2469 else if (dbt != VT_LLONG) {
2470 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2471 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2472 0xffffffff);
2473 vtop->c.i &= m;
2474 if (!(dbt & VT_UNSIGNED))
2475 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2478 } else if (p && dbt == VT_BOOL) {
2479 vtop->r = VT_CONST;
2480 vtop->c.i = 1;
2481 } else {
2482 /* non constant case: generate code */
2483 if (sf && df) {
2484 /* convert from fp to fp */
2485 gen_cvt_ftof(dbt);
2486 } else if (df) {
2487 /* convert int to fp */
2488 gen_cvt_itof1(dbt);
2489 } else if (sf) {
2490 /* convert fp to int */
2491 if (dbt == VT_BOOL) {
2492 vpushi(0);
2493 gen_op(TOK_NE);
2494 } else {
2495 /* we handle char/short/etc... with generic code */
2496 if (dbt != (VT_INT | VT_UNSIGNED) &&
2497 dbt != (VT_LLONG | VT_UNSIGNED) &&
2498 dbt != VT_LLONG)
2499 dbt = VT_INT;
2500 gen_cvt_ftoi1(dbt);
2501 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2502 /* additional cast for char/short... */
2503 vtop->type.t = dbt;
2504 gen_cast(type);
2507 #if PTR_SIZE == 4
2508 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2509 if ((sbt & VT_BTYPE) != VT_LLONG) {
2510 /* scalar to long long */
2511 /* machine independent conversion */
2512 gv(RC_INT);
2513 /* generate high word */
2514 if (sbt == (VT_INT | VT_UNSIGNED)) {
2515 vpushi(0);
2516 gv(RC_INT);
2517 } else {
2518 if (sbt == VT_PTR) {
2519 /* cast from pointer to int before we apply
2520 shift operation, which pointers don't support*/
2521 gen_cast_s(VT_INT);
2523 gv_dup();
2524 vpushi(31);
2525 gen_op(TOK_SAR);
2527 /* patch second register */
2528 vtop[-1].r2 = vtop->r;
2529 vpop();
2531 #else
2532 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2533 (dbt & VT_BTYPE) == VT_PTR ||
2534 (dbt & VT_BTYPE) == VT_FUNC) {
2535 if ((sbt & VT_BTYPE) != VT_LLONG &&
2536 (sbt & VT_BTYPE) != VT_PTR &&
2537 (sbt & VT_BTYPE) != VT_FUNC) {
2538 /* need to convert from 32bit to 64bit */
2539 gv(RC_INT);
2540 if (sbt != (VT_INT | VT_UNSIGNED)) {
2541 #if defined(TCC_TARGET_ARM64)
2542 gen_cvt_sxtw();
2543 #elif defined(TCC_TARGET_X86_64)
2544 int r = gv(RC_INT);
2545 /* x86_64 specific: movslq */
2546 o(0x6348);
2547 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2548 #else
2549 #error
2550 #endif
2553 #endif
2554 } else if (dbt == VT_BOOL) {
2555 /* scalar to bool */
2556 vpushi(0);
2557 gen_op(TOK_NE);
2558 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2559 (dbt & VT_BTYPE) == VT_SHORT) {
2560 if (sbt == VT_PTR) {
2561 vtop->type.t = VT_INT;
2562 tcc_warning("nonportable conversion from pointer to char/short");
2564 force_charshort_cast(dbt);
2565 #if PTR_SIZE == 4
2566 } else if ((dbt & VT_BTYPE) == VT_INT) {
2567 /* scalar to int */
2568 if ((sbt & VT_BTYPE) == VT_LLONG) {
2569 /* from long long: just take low order word */
2570 lexpand();
2571 vpop();
2573 /* if lvalue and single word type, nothing to do because
2574 the lvalue already contains the real type size (see
2575 VT_LVAL_xxx constants) */
2576 #endif
2579 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2580 /* if we are casting between pointer types,
2581 we must update the VT_LVAL_xxx size */
2582 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2583 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2585 vtop->type = *type;
2588 /* return type size as known at compile time. Put alignment at 'a' */
2589 ST_FUNC int type_size(CType *type, int *a)
2591 Sym *s;
2592 int bt;
2594 bt = type->t & VT_BTYPE;
2595 if (bt == VT_STRUCT) {
2596 /* struct/union */
2597 s = type->ref;
2598 *a = s->r;
2599 return s->c;
2600 } else if (bt == VT_PTR) {
2601 if (type->t & VT_ARRAY) {
2602 int ts;
2604 s = type->ref;
2605 ts = type_size(&s->type, a);
2607 if (ts < 0 && s->c < 0)
2608 ts = -ts;
2610 return ts * s->c;
2611 } else {
2612 *a = PTR_SIZE;
2613 return PTR_SIZE;
2615 } else if (IS_ENUM(type->t) && type->ref->c == -1) {
2616 return -1; /* incomplete enum */
2617 } else if (bt == VT_LDOUBLE) {
2618 *a = LDOUBLE_ALIGN;
2619 return LDOUBLE_SIZE;
2620 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2621 #ifdef TCC_TARGET_I386
2622 #ifdef TCC_TARGET_PE
2623 *a = 8;
2624 #else
2625 *a = 4;
2626 #endif
2627 #elif defined(TCC_TARGET_ARM)
2628 #ifdef TCC_ARM_EABI
2629 *a = 8;
2630 #else
2631 *a = 4;
2632 #endif
2633 #else
2634 *a = 8;
2635 #endif
2636 return 8;
2637 } else if (bt == VT_INT || bt == VT_FLOAT) {
2638 *a = 4;
2639 return 4;
2640 } else if (bt == VT_SHORT) {
2641 *a = 2;
2642 return 2;
2643 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2644 *a = 8;
2645 return 16;
2646 } else {
2647 /* char, void, function, _Bool */
2648 *a = 1;
2649 return 1;
2653 /* push type size as known at runtime time on top of value stack. Put
2654 alignment at 'a' */
2655 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2657 if (type->t & VT_VLA) {
2658 type_size(&type->ref->type, a);
2659 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2660 } else {
2661 vpushi(type_size(type, a));
2665 static void vla_sp_restore(void) {
2666 if (vlas_in_scope) {
2667 gen_vla_sp_restore(vla_sp_loc);
2671 static void vla_sp_restore_root(void) {
2672 if (vlas_in_scope) {
2673 gen_vla_sp_restore(vla_sp_root_loc);
2677 /* return the pointed type of t */
2678 static inline CType *pointed_type(CType *type)
2680 return &type->ref->type;
2683 /* modify type so that its it is a pointer to type. */
2684 ST_FUNC void mk_pointer(CType *type)
2686 Sym *s;
2687 s = sym_push(SYM_FIELD, type, 0, -1);
2688 type->t = VT_PTR | (type->t & VT_STORAGE);
2689 type->ref = s;
2692 /* compare function types. OLD functions match any new functions */
2693 static int is_compatible_func(CType *type1, CType *type2)
2695 Sym *s1, *s2;
2697 s1 = type1->ref;
2698 s2 = type2->ref;
2699 if (!is_compatible_types(&s1->type, &s2->type))
2700 return 0;
2701 /* check func_call */
2702 if (s1->f.func_call != s2->f.func_call)
2703 return 0;
2704 /* XXX: not complete */
2705 if (s1->f.func_type == FUNC_OLD || s2->f.func_type == FUNC_OLD)
2706 return 1;
2707 if (s1->f.func_type != s2->f.func_type)
2708 return 0;
2709 while (s1 != NULL) {
2710 if (s2 == NULL)
2711 return 0;
2712 if (!is_compatible_unqualified_types(&s1->type, &s2->type))
2713 return 0;
2714 s1 = s1->next;
2715 s2 = s2->next;
2717 if (s2)
2718 return 0;
2719 return 1;
2722 /* return true if type1 and type2 are the same. If unqualified is
2723 true, qualifiers on the types are ignored.
2725 - enums are not checked as gcc __builtin_types_compatible_p ()
2727 static int compare_types(CType *type1, CType *type2, int unqualified)
2729 int bt1, t1, t2;
2731 t1 = type1->t & VT_TYPE;
2732 t2 = type2->t & VT_TYPE;
2733 if (unqualified) {
2734 /* strip qualifiers before comparing */
2735 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2736 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2739 /* Default Vs explicit signedness only matters for char */
2740 if ((t1 & VT_BTYPE) != VT_BYTE) {
2741 t1 &= ~VT_DEFSIGN;
2742 t2 &= ~VT_DEFSIGN;
2745 /* XXX: bitfields ? */
2746 if (t1 != t2)
2747 return 0;
2748 /* test more complicated cases */
2749 bt1 = t1 & VT_BTYPE;
2750 if (bt1 == VT_PTR) {
2751 type1 = pointed_type(type1);
2752 type2 = pointed_type(type2);
2753 return is_compatible_types(type1, type2);
2754 } else if (bt1 == VT_STRUCT) {
2755 return (type1->ref == type2->ref);
2756 } else if (bt1 == VT_FUNC) {
2757 return is_compatible_func(type1, type2);
2758 } else {
2759 return 1;
2763 /* return true if type1 and type2 are exactly the same (including
2764 qualifiers).
2766 static int is_compatible_types(CType *type1, CType *type2)
2768 return compare_types(type1,type2,0);
2771 /* return true if type1 and type2 are the same (ignoring qualifiers).
2773 static int is_compatible_unqualified_types(CType *type1, CType *type2)
2775 return compare_types(type1,type2,1);
2778 /* print a type. If 'varstr' is not NULL, then the variable is also
2779 printed in the type */
2780 /* XXX: union */
2781 /* XXX: add array and function pointers */
2782 static void type_to_str(char *buf, int buf_size,
2783 CType *type, const char *varstr)
2785 int bt, v, t;
2786 Sym *s, *sa;
2787 char buf1[256];
2788 const char *tstr;
2790 t = type->t;
2791 bt = t & VT_BTYPE;
2792 buf[0] = '\0';
2793 if (t & VT_CONSTANT)
2794 pstrcat(buf, buf_size, "const ");
2795 if (t & VT_VOLATILE)
2796 pstrcat(buf, buf_size, "volatile ");
2797 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2798 pstrcat(buf, buf_size, "unsigned ");
2799 else if (t & VT_DEFSIGN)
2800 pstrcat(buf, buf_size, "signed ");
2801 if (t & VT_EXTERN)
2802 pstrcat(buf, buf_size, "extern ");
2803 if (t & VT_STATIC)
2804 pstrcat(buf, buf_size, "static ");
2805 if (t & VT_TYPEDEF)
2806 pstrcat(buf, buf_size, "typedef ");
2807 if (t & VT_INLINE)
2808 pstrcat(buf, buf_size, "inline ");
2809 buf_size -= strlen(buf);
2810 buf += strlen(buf);
2811 if (IS_ENUM(t)) {
2812 tstr = "enum ";
2813 goto tstruct;
2816 if (!bt && VT_LONG & t) {
2817 tstr = "long";
2818 goto add_tstr;
2821 switch(bt) {
2822 case VT_VOID:
2823 tstr = "void";
2824 goto add_tstr;
2825 case VT_BOOL:
2826 tstr = "_Bool";
2827 goto add_tstr;
2828 case VT_BYTE:
2829 tstr = "char";
2830 goto add_tstr;
2831 case VT_SHORT:
2832 tstr = "short";
2833 goto add_tstr;
2834 case VT_INT:
2835 tstr = "int";
2836 goto add_tstr;
2837 case VT_LLONG:
2838 tstr = "long long";
2839 goto add_tstr;
2840 case VT_FLOAT:
2841 tstr = "float";
2842 goto add_tstr;
2843 case VT_DOUBLE:
2844 tstr = "double";
2845 goto add_tstr;
2846 case VT_LDOUBLE:
2847 tstr = "long double";
2848 add_tstr:
2849 pstrcat(buf, buf_size, tstr);
2850 break;
2851 case VT_STRUCT:
2852 tstr = "struct ";
2853 if (IS_UNION(t))
2854 tstr = "union ";
2855 tstruct:
2856 pstrcat(buf, buf_size, tstr);
2857 v = type->ref->v & ~SYM_STRUCT;
2858 if (v >= SYM_FIRST_ANOM)
2859 pstrcat(buf, buf_size, "<anonymous>");
2860 else
2861 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2862 break;
2863 case VT_FUNC:
2864 s = type->ref;
2865 type_to_str(buf, buf_size, &s->type, varstr);
2866 pstrcat(buf, buf_size, "(");
2867 sa = s->next;
2868 while (sa != NULL) {
2869 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2870 pstrcat(buf, buf_size, buf1);
2871 sa = sa->next;
2872 if (sa)
2873 pstrcat(buf, buf_size, ", ");
2875 pstrcat(buf, buf_size, ")");
2876 goto no_var;
2877 case VT_PTR:
2878 s = type->ref;
2879 if (t & VT_ARRAY) {
2880 snprintf(buf1, sizeof(buf1), "%s[%d]", varstr ? varstr : "", s->c);
2881 type_to_str(buf, buf_size, &s->type, buf1);
2882 goto no_var;
2884 pstrcpy(buf1, sizeof(buf1), "*");
2885 if (t & VT_CONSTANT)
2886 pstrcat(buf1, buf_size, "const ");
2887 if (t & VT_VOLATILE)
2888 pstrcat(buf1, buf_size, "volatile ");
2889 if (varstr)
2890 pstrcat(buf1, sizeof(buf1), varstr);
2891 type_to_str(buf, buf_size, &s->type, buf1);
2892 goto no_var;
2894 if (varstr) {
2895 pstrcat(buf, buf_size, " ");
2896 pstrcat(buf, buf_size, varstr);
2898 no_var: ;
2901 /* verify type compatibility to store vtop in 'dt' type, and generate
2902 casts if needed. */
2903 static void gen_assign_cast(CType *dt)
2905 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2906 char buf1[256], buf2[256];
2907 int dbt, sbt;
2909 st = &vtop->type; /* source type */
2910 dbt = dt->t & VT_BTYPE;
2911 sbt = st->t & VT_BTYPE;
2912 if (sbt == VT_VOID || dbt == VT_VOID) {
2913 if (sbt == VT_VOID && dbt == VT_VOID)
2914 ; /*
2915 It is Ok if both are void
2916 A test program:
2917 void func1() {}
2918 void func2() {
2919 return func1();
2921 gcc accepts this program
2923 else
2924 tcc_error("cannot cast from/to void");
2926 if (dt->t & VT_CONSTANT)
2927 tcc_warning("assignment of read-only location");
2928 switch(dbt) {
2929 case VT_PTR:
2930 /* special cases for pointers */
2931 /* '0' can also be a pointer */
2932 if (is_null_pointer(vtop))
2933 goto type_ok;
2934 /* accept implicit pointer to integer cast with warning */
2935 if (is_integer_btype(sbt)) {
2936 tcc_warning("assignment makes pointer from integer without a cast");
2937 goto type_ok;
2939 type1 = pointed_type(dt);
2940 /* a function is implicitly a function pointer */
2941 if (sbt == VT_FUNC) {
2942 if ((type1->t & VT_BTYPE) != VT_VOID &&
2943 !is_compatible_types(pointed_type(dt), st))
2944 tcc_warning("assignment from incompatible pointer type");
2945 goto type_ok;
2947 if (sbt != VT_PTR)
2948 goto error;
2949 type2 = pointed_type(st);
2950 if ((type1->t & VT_BTYPE) == VT_VOID ||
2951 (type2->t & VT_BTYPE) == VT_VOID) {
2952 /* void * can match anything */
2953 } else {
2954 //printf("types %08x %08x\n", type1->t, type2->t);
2955 /* exact type match, except for qualifiers */
2956 if (!is_compatible_unqualified_types(type1, type2)) {
2957 /* Like GCC don't warn by default for merely changes
2958 in pointer target signedness. Do warn for different
2959 base types, though, in particular for unsigned enums
2960 and signed int targets. */
2961 if ((type1->t & VT_BTYPE) != (type2->t & VT_BTYPE)
2962 || IS_ENUM(type1->t) || IS_ENUM(type2->t)
2964 tcc_warning("assignment from incompatible pointer type");
2967 /* check const and volatile */
2968 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2969 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2970 tcc_warning("assignment discards qualifiers from pointer target type");
2971 break;
2972 case VT_BYTE:
2973 case VT_SHORT:
2974 case VT_INT:
2975 case VT_LLONG:
2976 if (sbt == VT_PTR || sbt == VT_FUNC) {
2977 tcc_warning("assignment makes integer from pointer without a cast");
2978 } else if (sbt == VT_STRUCT) {
2979 goto case_VT_STRUCT;
2981 /* XXX: more tests */
2982 break;
2983 case VT_STRUCT:
2984 case_VT_STRUCT:
2985 tmp_type1 = *dt;
2986 tmp_type2 = *st;
2987 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2988 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2989 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2990 error:
2991 type_to_str(buf1, sizeof(buf1), st, NULL);
2992 type_to_str(buf2, sizeof(buf2), dt, NULL);
2993 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2995 break;
2997 type_ok:
2998 gen_cast(dt);
3001 /* store vtop in lvalue pushed on stack */
3002 ST_FUNC void vstore(void)
3004 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
3006 ft = vtop[-1].type.t;
3007 sbt = vtop->type.t & VT_BTYPE;
3008 dbt = ft & VT_BTYPE;
3009 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
3010 (sbt == VT_INT && dbt == VT_SHORT))
3011 && !(vtop->type.t & VT_BITFIELD)) {
3012 /* optimize char/short casts */
3013 delayed_cast = VT_MUSTCAST;
3014 vtop->type.t = ft & VT_TYPE;
3015 /* XXX: factorize */
3016 if (ft & VT_CONSTANT)
3017 tcc_warning("assignment of read-only location");
3018 } else {
3019 delayed_cast = 0;
3020 if (!(ft & VT_BITFIELD))
3021 gen_assign_cast(&vtop[-1].type);
3024 if (sbt == VT_STRUCT) {
3025 /* if structure, only generate pointer */
3026 /* structure assignment : generate memcpy */
3027 /* XXX: optimize if small size */
3028 size = type_size(&vtop->type, &align);
3030 /* destination */
3031 vswap();
3032 vtop->type.t = VT_PTR;
3033 gaddrof();
3035 /* address of memcpy() */
3036 #ifdef TCC_ARM_EABI
3037 if(!(align & 7))
3038 vpush_global_sym(&func_old_type, TOK_memcpy8);
3039 else if(!(align & 3))
3040 vpush_global_sym(&func_old_type, TOK_memcpy4);
3041 else
3042 #endif
3043 /* Use memmove, rather than memcpy, as dest and src may be same: */
3044 vpush_global_sym(&func_old_type, TOK_memmove);
3046 vswap();
3047 /* source */
3048 vpushv(vtop - 2);
3049 vtop->type.t = VT_PTR;
3050 gaddrof();
3051 /* type size */
3052 vpushi(size);
3053 gfunc_call(3);
3055 /* leave source on stack */
3056 } else if (ft & VT_BITFIELD) {
3057 /* bitfield store handling */
3059 /* save lvalue as expression result (example: s.b = s.a = n;) */
3060 vdup(), vtop[-1] = vtop[-2];
3062 bit_pos = BIT_POS(ft);
3063 bit_size = BIT_SIZE(ft);
3064 /* remove bit field info to avoid loops */
3065 vtop[-1].type.t = ft & ~VT_STRUCT_MASK;
3067 if ((ft & VT_BTYPE) == VT_BOOL) {
3068 gen_cast(&vtop[-1].type);
3069 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
3072 r = adjust_bf(vtop - 1, bit_pos, bit_size);
3073 if (r == VT_STRUCT) {
3074 gen_cast_s((ft & VT_BTYPE) == VT_LLONG ? VT_LLONG : VT_INT);
3075 store_packed_bf(bit_pos, bit_size);
3076 } else {
3077 unsigned long long mask = (1ULL << bit_size) - 1;
3078 if ((ft & VT_BTYPE) != VT_BOOL) {
3079 /* mask source */
3080 if ((vtop[-1].type.t & VT_BTYPE) == VT_LLONG)
3081 vpushll(mask);
3082 else
3083 vpushi((unsigned)mask);
3084 gen_op('&');
3086 /* shift source */
3087 vpushi(bit_pos);
3088 gen_op(TOK_SHL);
3089 vswap();
3090 /* duplicate destination */
3091 vdup();
3092 vrott(3);
3093 /* load destination, mask and or with source */
3094 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
3095 vpushll(~(mask << bit_pos));
3096 else
3097 vpushi(~((unsigned)mask << bit_pos));
3098 gen_op('&');
3099 gen_op('|');
3100 /* store result */
3101 vstore();
3102 /* ... and discard */
3103 vpop();
3105 } else {
3106 #ifdef CONFIG_TCC_BCHECK
3107 /* bound check case */
3108 if (vtop[-1].r & VT_MUSTBOUND) {
3109 vswap();
3110 gbound();
3111 vswap();
3113 #endif
3114 rc = RC_INT;
3115 if (is_float(ft)) {
3116 rc = RC_FLOAT;
3117 #ifdef TCC_TARGET_X86_64
3118 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
3119 rc = RC_ST0;
3120 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
3121 rc = RC_FRET;
3123 #endif
3125 r = gv(rc); /* generate value */
3126 /* if lvalue was saved on stack, must read it */
3127 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
3128 SValue sv;
3129 t = get_reg(RC_INT);
3130 #if PTR_SIZE == 8
3131 sv.type.t = VT_PTR;
3132 #else
3133 sv.type.t = VT_INT;
3134 #endif
3135 sv.r = VT_LOCAL | VT_LVAL;
3136 sv.c.i = vtop[-1].c.i;
3137 load(t, &sv);
3138 vtop[-1].r = t | VT_LVAL;
3140 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
3141 #if PTR_SIZE == 8
3142 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
3143 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
3144 #else
3145 if ((ft & VT_BTYPE) == VT_LLONG) {
3146 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
3147 #endif
3148 vtop[-1].type.t = load_type;
3149 store(r, vtop - 1);
3150 vswap();
3151 /* convert to int to increment easily */
3152 vtop->type.t = addr_type;
3153 gaddrof();
3154 vpushi(load_size);
3155 gen_op('+');
3156 vtop->r |= VT_LVAL;
3157 vswap();
3158 vtop[-1].type.t = load_type;
3159 /* XXX: it works because r2 is spilled last ! */
3160 store(vtop->r2, vtop - 1);
3161 } else {
3162 store(r, vtop - 1);
3165 vswap();
3166 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
3167 vtop->r |= delayed_cast;
3171 /* post defines POST/PRE add. c is the token ++ or -- */
3172 ST_FUNC void inc(int post, int c)
3174 test_lvalue();
3175 vdup(); /* save lvalue */
3176 if (post) {
3177 gv_dup(); /* duplicate value */
3178 vrotb(3);
3179 vrotb(3);
3181 /* add constant */
3182 vpushi(c - TOK_MID);
3183 gen_op('+');
3184 vstore(); /* store value */
3185 if (post)
3186 vpop(); /* if post op, return saved value */
3189 ST_FUNC void parse_mult_str (CString *astr, const char *msg)
3191 /* read the string */
3192 if (tok != TOK_STR)
3193 expect(msg);
3194 cstr_new(astr);
3195 while (tok == TOK_STR) {
3196 /* XXX: add \0 handling too ? */
3197 cstr_cat(astr, tokc.str.data, -1);
3198 next();
3200 cstr_ccat(astr, '\0');
3203 /* If I is >= 1 and a power of two, returns log2(i)+1.
3204 If I is 0 returns 0. */
3205 static int exact_log2p1(int i)
3207 int ret;
3208 if (!i)
3209 return 0;
3210 for (ret = 1; i >= 1 << 8; ret += 8)
3211 i >>= 8;
3212 if (i >= 1 << 4)
3213 ret += 4, i >>= 4;
3214 if (i >= 1 << 2)
3215 ret += 2, i >>= 2;
3216 if (i >= 1 << 1)
3217 ret++;
3218 return ret;
3221 /* Parse __attribute__((...)) GNUC extension. */
3222 static void parse_attribute(AttributeDef *ad)
3224 int t, n;
3225 CString astr;
3227 redo:
3228 if (tok != TOK_ATTRIBUTE1 && tok != TOK_ATTRIBUTE2)
3229 return;
3230 next();
3231 skip('(');
3232 skip('(');
3233 while (tok != ')') {
3234 if (tok < TOK_IDENT)
3235 expect("attribute name");
3236 t = tok;
3237 next();
3238 switch(t) {
3239 case TOK_SECTION1:
3240 case TOK_SECTION2:
3241 skip('(');
3242 parse_mult_str(&astr, "section name");
3243 ad->section = find_section(tcc_state, (char *)astr.data);
3244 skip(')');
3245 cstr_free(&astr);
3246 break;
3247 case TOK_ALIAS1:
3248 case TOK_ALIAS2:
3249 skip('(');
3250 parse_mult_str(&astr, "alias(\"target\")");
3251 ad->alias_target = /* save string as token, for later */
3252 tok_alloc((char*)astr.data, astr.size-1)->tok;
3253 skip(')');
3254 cstr_free(&astr);
3255 break;
3256 case TOK_VISIBILITY1:
3257 case TOK_VISIBILITY2:
3258 skip('(');
3259 parse_mult_str(&astr,
3260 "visibility(\"default|hidden|internal|protected\")");
3261 if (!strcmp (astr.data, "default"))
3262 ad->a.visibility = STV_DEFAULT;
3263 else if (!strcmp (astr.data, "hidden"))
3264 ad->a.visibility = STV_HIDDEN;
3265 else if (!strcmp (astr.data, "internal"))
3266 ad->a.visibility = STV_INTERNAL;
3267 else if (!strcmp (astr.data, "protected"))
3268 ad->a.visibility = STV_PROTECTED;
3269 else
3270 expect("visibility(\"default|hidden|internal|protected\")");
3271 skip(')');
3272 cstr_free(&astr);
3273 break;
3274 case TOK_ALIGNED1:
3275 case TOK_ALIGNED2:
3276 if (tok == '(') {
3277 next();
3278 n = expr_const();
3279 if (n <= 0 || (n & (n - 1)) != 0)
3280 tcc_error("alignment must be a positive power of two");
3281 skip(')');
3282 } else {
3283 n = MAX_ALIGN;
3285 ad->a.aligned = exact_log2p1(n);
3286 if (n != 1 << (ad->a.aligned - 1))
3287 tcc_error("alignment of %d is larger than implemented", n);
3288 break;
3289 case TOK_PACKED1:
3290 case TOK_PACKED2:
3291 ad->a.packed = 1;
3292 break;
3293 case TOK_WEAK1:
3294 case TOK_WEAK2:
3295 ad->a.weak = 1;
3296 break;
3297 case TOK_UNUSED1:
3298 case TOK_UNUSED2:
3299 /* currently, no need to handle it because tcc does not
3300 track unused objects */
3301 break;
3302 case TOK_NORETURN1:
3303 case TOK_NORETURN2:
3304 /* currently, no need to handle it because tcc does not
3305 track unused objects */
3306 break;
3307 case TOK_CDECL1:
3308 case TOK_CDECL2:
3309 case TOK_CDECL3:
3310 ad->f.func_call = FUNC_CDECL;
3311 break;
3312 case TOK_STDCALL1:
3313 case TOK_STDCALL2:
3314 case TOK_STDCALL3:
3315 ad->f.func_call = FUNC_STDCALL;
3316 break;
3317 #ifdef TCC_TARGET_I386
3318 case TOK_REGPARM1:
3319 case TOK_REGPARM2:
3320 skip('(');
3321 n = expr_const();
3322 if (n > 3)
3323 n = 3;
3324 else if (n < 0)
3325 n = 0;
3326 if (n > 0)
3327 ad->f.func_call = FUNC_FASTCALL1 + n - 1;
3328 skip(')');
3329 break;
3330 case TOK_FASTCALL1:
3331 case TOK_FASTCALL2:
3332 case TOK_FASTCALL3:
3333 ad->f.func_call = FUNC_FASTCALLW;
3334 break;
3335 #endif
3336 case TOK_MODE:
3337 skip('(');
3338 switch(tok) {
3339 case TOK_MODE_DI:
3340 ad->attr_mode = VT_LLONG + 1;
3341 break;
3342 case TOK_MODE_QI:
3343 ad->attr_mode = VT_BYTE + 1;
3344 break;
3345 case TOK_MODE_HI:
3346 ad->attr_mode = VT_SHORT + 1;
3347 break;
3348 case TOK_MODE_SI:
3349 case TOK_MODE_word:
3350 ad->attr_mode = VT_INT + 1;
3351 break;
3352 default:
3353 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
3354 break;
3356 next();
3357 skip(')');
3358 break;
3359 case TOK_DLLEXPORT:
3360 ad->a.dllexport = 1;
3361 break;
3362 case TOK_DLLIMPORT:
3363 ad->a.dllimport = 1;
3364 break;
3365 default:
3366 if (tcc_state->warn_unsupported)
3367 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
3368 /* skip parameters */
3369 if (tok == '(') {
3370 int parenthesis = 0;
3371 do {
3372 if (tok == '(')
3373 parenthesis++;
3374 else if (tok == ')')
3375 parenthesis--;
3376 next();
3377 } while (parenthesis && tok != -1);
3379 break;
3381 if (tok != ',')
3382 break;
3383 next();
3385 skip(')');
3386 skip(')');
3387 goto redo;
3390 static Sym * find_field (CType *type, int v)
3392 Sym *s = type->ref;
3393 v |= SYM_FIELD;
3394 while ((s = s->next) != NULL) {
3395 if ((s->v & SYM_FIELD) &&
3396 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3397 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3398 Sym *ret = find_field (&s->type, v);
3399 if (ret)
3400 return ret;
3402 if (s->v == v)
3403 break;
3405 return s;
3408 static void struct_add_offset (Sym *s, int offset)
3410 while ((s = s->next) != NULL) {
3411 if ((s->v & SYM_FIELD) &&
3412 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3413 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3414 struct_add_offset(s->type.ref, offset);
3415 } else
3416 s->c += offset;
3420 static void struct_layout(CType *type, AttributeDef *ad)
3422 int size, align, maxalign, offset, c, bit_pos, bit_size;
3423 int packed, a, bt, prevbt, prev_bit_size;
3424 int pcc = !tcc_state->ms_bitfields;
3425 int pragma_pack = *tcc_state->pack_stack_ptr;
3426 Sym *f;
3428 maxalign = 1;
3429 offset = 0;
3430 c = 0;
3431 bit_pos = 0;
3432 prevbt = VT_STRUCT; /* make it never match */
3433 prev_bit_size = 0;
3435 //#define BF_DEBUG
3437 for (f = type->ref->next; f; f = f->next) {
3438 if (f->type.t & VT_BITFIELD)
3439 bit_size = BIT_SIZE(f->type.t);
3440 else
3441 bit_size = -1;
3442 size = type_size(&f->type, &align);
3443 a = f->a.aligned ? 1 << (f->a.aligned - 1) : 0;
3444 packed = 0;
3446 if (pcc && bit_size == 0) {
3447 /* in pcc mode, packing does not affect zero-width bitfields */
3449 } else {
3450 /* in pcc mode, attribute packed overrides if set. */
3451 if (pcc && (f->a.packed || ad->a.packed))
3452 align = packed = 1;
3454 /* pragma pack overrides align if lesser and packs bitfields always */
3455 if (pragma_pack) {
3456 packed = 1;
3457 if (pragma_pack < align)
3458 align = pragma_pack;
3459 /* in pcc mode pragma pack also overrides individual align */
3460 if (pcc && pragma_pack < a)
3461 a = 0;
3464 /* some individual align was specified */
3465 if (a)
3466 align = a;
3468 if (type->ref->type.t == VT_UNION) {
3469 if (pcc && bit_size >= 0)
3470 size = (bit_size + 7) >> 3;
3471 offset = 0;
3472 if (size > c)
3473 c = size;
3475 } else if (bit_size < 0) {
3476 if (pcc)
3477 c += (bit_pos + 7) >> 3;
3478 c = (c + align - 1) & -align;
3479 offset = c;
3480 if (size > 0)
3481 c += size;
3482 bit_pos = 0;
3483 prevbt = VT_STRUCT;
3484 prev_bit_size = 0;
3486 } else {
3487 /* A bit-field. Layout is more complicated. There are two
3488 options: PCC (GCC) compatible and MS compatible */
3489 if (pcc) {
3490 /* In PCC layout a bit-field is placed adjacent to the
3491 preceding bit-fields, except if:
3492 - it has zero-width
3493 - an individual alignment was given
3494 - it would overflow its base type container and
3495 there is no packing */
3496 if (bit_size == 0) {
3497 new_field:
3498 c = (c + ((bit_pos + 7) >> 3) + align - 1) & -align;
3499 bit_pos = 0;
3500 } else if (f->a.aligned) {
3501 goto new_field;
3502 } else if (!packed) {
3503 int a8 = align * 8;
3504 int ofs = ((c * 8 + bit_pos) % a8 + bit_size + a8 - 1) / a8;
3505 if (ofs > size / align)
3506 goto new_field;
3509 /* in pcc mode, long long bitfields have type int if they fit */
3510 if (size == 8 && bit_size <= 32)
3511 f->type.t = (f->type.t & ~VT_BTYPE) | VT_INT, size = 4;
3513 while (bit_pos >= align * 8)
3514 c += align, bit_pos -= align * 8;
3515 offset = c;
3517 /* In PCC layout named bit-fields influence the alignment
3518 of the containing struct using the base types alignment,
3519 except for packed fields (which here have correct align). */
3520 if (f->v & SYM_FIRST_ANOM
3521 // && bit_size // ??? gcc on ARM/rpi does that
3523 align = 1;
3525 } else {
3526 bt = f->type.t & VT_BTYPE;
3527 if ((bit_pos + bit_size > size * 8)
3528 || (bit_size > 0) == (bt != prevbt)
3530 c = (c + align - 1) & -align;
3531 offset = c;
3532 bit_pos = 0;
3533 /* In MS bitfield mode a bit-field run always uses
3534 at least as many bits as the underlying type.
3535 To start a new run it's also required that this
3536 or the last bit-field had non-zero width. */
3537 if (bit_size || prev_bit_size)
3538 c += size;
3540 /* In MS layout the records alignment is normally
3541 influenced by the field, except for a zero-width
3542 field at the start of a run (but by further zero-width
3543 fields it is again). */
3544 if (bit_size == 0 && prevbt != bt)
3545 align = 1;
3546 prevbt = bt;
3547 prev_bit_size = bit_size;
3550 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3551 | (bit_pos << VT_STRUCT_SHIFT);
3552 bit_pos += bit_size;
3554 if (align > maxalign)
3555 maxalign = align;
3557 #ifdef BF_DEBUG
3558 printf("set field %s offset %-2d size %-2d align %-2d",
3559 get_tok_str(f->v & ~SYM_FIELD, NULL), offset, size, align);
3560 if (f->type.t & VT_BITFIELD) {
3561 printf(" pos %-2d bits %-2d",
3562 BIT_POS(f->type.t),
3563 BIT_SIZE(f->type.t)
3566 printf("\n");
3567 #endif
3569 if (f->v & SYM_FIRST_ANOM && (f->type.t & VT_BTYPE) == VT_STRUCT) {
3570 Sym *ass;
3571 /* An anonymous struct/union. Adjust member offsets
3572 to reflect the real offset of our containing struct.
3573 Also set the offset of this anon member inside
3574 the outer struct to be zero. Via this it
3575 works when accessing the field offset directly
3576 (from base object), as well as when recursing
3577 members in initializer handling. */
3578 int v2 = f->type.ref->v;
3579 if (!(v2 & SYM_FIELD) &&
3580 (v2 & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3581 Sym **pps;
3582 /* This happens only with MS extensions. The
3583 anon member has a named struct type, so it
3584 potentially is shared with other references.
3585 We need to unshare members so we can modify
3586 them. */
3587 ass = f->type.ref;
3588 f->type.ref = sym_push(anon_sym++ | SYM_FIELD,
3589 &f->type.ref->type, 0,
3590 f->type.ref->c);
3591 pps = &f->type.ref->next;
3592 while ((ass = ass->next) != NULL) {
3593 *pps = sym_push(ass->v, &ass->type, 0, ass->c);
3594 pps = &((*pps)->next);
3596 *pps = NULL;
3598 struct_add_offset(f->type.ref, offset);
3599 f->c = 0;
3600 } else {
3601 f->c = offset;
3604 f->r = 0;
3607 if (pcc)
3608 c += (bit_pos + 7) >> 3;
3610 /* store size and alignment */
3611 a = bt = ad->a.aligned ? 1 << (ad->a.aligned - 1) : 1;
3612 if (a < maxalign)
3613 a = maxalign;
3614 type->ref->r = a;
3615 if (pragma_pack && pragma_pack < maxalign && 0 == pcc) {
3616 /* can happen if individual align for some member was given. In
3617 this case MSVC ignores maxalign when aligning the size */
3618 a = pragma_pack;
3619 if (a < bt)
3620 a = bt;
3622 c = (c + a - 1) & -a;
3623 type->ref->c = c;
3625 #ifdef BF_DEBUG
3626 printf("struct size %-2d align %-2d\n\n", c, a), fflush(stdout);
3627 #endif
3629 /* check whether we can access bitfields by their type */
3630 for (f = type->ref->next; f; f = f->next) {
3631 int s, px, cx, c0;
3632 CType t;
3634 if (0 == (f->type.t & VT_BITFIELD))
3635 continue;
3636 f->type.ref = f;
3637 f->auxtype = -1;
3638 bit_size = BIT_SIZE(f->type.t);
3639 if (bit_size == 0)
3640 continue;
3641 bit_pos = BIT_POS(f->type.t);
3642 size = type_size(&f->type, &align);
3643 if (bit_pos + bit_size <= size * 8 && f->c + size <= c)
3644 continue;
3646 /* try to access the field using a differnt type */
3647 c0 = -1, s = align = 1;
3648 for (;;) {
3649 px = f->c * 8 + bit_pos;
3650 cx = (px >> 3) & -align;
3651 px = px - (cx << 3);
3652 if (c0 == cx)
3653 break;
3654 s = (px + bit_size + 7) >> 3;
3655 if (s > 4) {
3656 t.t = VT_LLONG;
3657 } else if (s > 2) {
3658 t.t = VT_INT;
3659 } else if (s > 1) {
3660 t.t = VT_SHORT;
3661 } else {
3662 t.t = VT_BYTE;
3664 s = type_size(&t, &align);
3665 c0 = cx;
3668 if (px + bit_size <= s * 8 && cx + s <= c) {
3669 /* update offset and bit position */
3670 f->c = cx;
3671 bit_pos = px;
3672 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3673 | (bit_pos << VT_STRUCT_SHIFT);
3674 if (s != size)
3675 f->auxtype = t.t;
3676 #ifdef BF_DEBUG
3677 printf("FIX field %s offset %-2d size %-2d align %-2d "
3678 "pos %-2d bits %-2d\n",
3679 get_tok_str(f->v & ~SYM_FIELD, NULL),
3680 cx, s, align, px, bit_size);
3681 #endif
3682 } else {
3683 /* fall back to load/store single-byte wise */
3684 f->auxtype = VT_STRUCT;
3685 #ifdef BF_DEBUG
3686 printf("FIX field %s : load byte-wise\n",
3687 get_tok_str(f->v & ~SYM_FIELD, NULL));
3688 #endif
3693 /* enum/struct/union declaration. u is VT_ENUM/VT_STRUCT/VT_UNION */
3694 static void struct_decl(CType *type, int u)
3696 int v, c, size, align, flexible;
3697 int bit_size, bsize, bt;
3698 Sym *s, *ss, **ps;
3699 AttributeDef ad, ad1;
3700 CType type1, btype;
3702 memset(&ad, 0, sizeof ad);
3703 next();
3704 parse_attribute(&ad);
3705 if (tok != '{') {
3706 v = tok;
3707 next();
3708 /* struct already defined ? return it */
3709 if (v < TOK_IDENT)
3710 expect("struct/union/enum name");
3711 s = struct_find(v);
3712 if (s && (s->sym_scope == local_scope || tok != '{')) {
3713 if (u == s->type.t)
3714 goto do_decl;
3715 if (u == VT_ENUM && IS_ENUM(s->type.t))
3716 goto do_decl;
3717 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
3719 } else {
3720 v = anon_sym++;
3722 /* Record the original enum/struct/union token. */
3723 type1.t = u == VT_ENUM ? u | VT_INT | VT_UNSIGNED : u;
3724 type1.ref = NULL;
3725 /* we put an undefined size for struct/union */
3726 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
3727 s->r = 0; /* default alignment is zero as gcc */
3728 do_decl:
3729 type->t = s->type.t;
3730 type->ref = s;
3732 if (tok == '{') {
3733 next();
3734 if (s->c != -1)
3735 tcc_error("struct/union/enum already defined");
3736 /* cannot be empty */
3737 /* non empty enums are not allowed */
3738 ps = &s->next;
3739 if (u == VT_ENUM) {
3740 long long ll = 0, pl = 0, nl = 0;
3741 CType t;
3742 t.ref = s;
3743 /* enum symbols have static storage */
3744 t.t = VT_INT|VT_STATIC|VT_ENUM_VAL;
3745 for(;;) {
3746 v = tok;
3747 if (v < TOK_UIDENT)
3748 expect("identifier");
3749 ss = sym_find(v);
3750 if (ss && !local_stack)
3751 tcc_error("redefinition of enumerator '%s'",
3752 get_tok_str(v, NULL));
3753 next();
3754 if (tok == '=') {
3755 next();
3756 ll = expr_const64();
3758 ss = sym_push(v, &t, VT_CONST, 0);
3759 ss->enum_val = ll;
3760 *ps = ss, ps = &ss->next;
3761 if (ll < nl)
3762 nl = ll;
3763 if (ll > pl)
3764 pl = ll;
3765 if (tok != ',')
3766 break;
3767 next();
3768 ll++;
3769 /* NOTE: we accept a trailing comma */
3770 if (tok == '}')
3771 break;
3773 skip('}');
3774 /* set integral type of the enum */
3775 t.t = VT_INT;
3776 if (nl >= 0) {
3777 if (pl != (unsigned)pl)
3778 t.t = VT_LLONG;
3779 t.t |= VT_UNSIGNED;
3780 } else if (pl != (int)pl || nl != (int)nl)
3781 t.t = VT_LLONG;
3782 s->type.t = type->t = t.t | VT_ENUM;
3783 s->c = 0;
3784 /* set type for enum members */
3785 for (ss = s->next; ss; ss = ss->next) {
3786 ll = ss->enum_val;
3787 if (ll == (int)ll) /* default is int if it fits */
3788 continue;
3789 if (t.t & VT_UNSIGNED) {
3790 ss->type.t |= VT_UNSIGNED;
3791 if (ll == (unsigned)ll)
3792 continue;
3794 ss->type.t = (ss->type.t & ~VT_BTYPE) | VT_LLONG;
3796 } else {
3797 c = 0;
3798 flexible = 0;
3799 while (tok != '}') {
3800 if (!parse_btype(&btype, &ad1)) {
3801 skip(';');
3802 continue;
3804 while (1) {
3805 if (flexible)
3806 tcc_error("flexible array member '%s' not at the end of struct",
3807 get_tok_str(v, NULL));
3808 bit_size = -1;
3809 v = 0;
3810 type1 = btype;
3811 if (tok != ':') {
3812 if (tok != ';')
3813 type_decl(&type1, &ad1, &v, TYPE_DIRECT);
3814 if (v == 0) {
3815 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3816 expect("identifier");
3817 else {
3818 int v = btype.ref->v;
3819 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3820 if (tcc_state->ms_extensions == 0)
3821 expect("identifier");
3825 if (type_size(&type1, &align) < 0) {
3826 if ((u == VT_STRUCT) && (type1.t & VT_ARRAY) && c)
3827 flexible = 1;
3828 else
3829 tcc_error("field '%s' has incomplete type",
3830 get_tok_str(v, NULL));
3832 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3833 (type1.t & VT_STORAGE))
3834 tcc_error("invalid type for '%s'",
3835 get_tok_str(v, NULL));
3837 if (tok == ':') {
3838 next();
3839 bit_size = expr_const();
3840 /* XXX: handle v = 0 case for messages */
3841 if (bit_size < 0)
3842 tcc_error("negative width in bit-field '%s'",
3843 get_tok_str(v, NULL));
3844 if (v && bit_size == 0)
3845 tcc_error("zero width for bit-field '%s'",
3846 get_tok_str(v, NULL));
3847 parse_attribute(&ad1);
3849 size = type_size(&type1, &align);
3850 if (bit_size >= 0) {
3851 bt = type1.t & VT_BTYPE;
3852 if (bt != VT_INT &&
3853 bt != VT_BYTE &&
3854 bt != VT_SHORT &&
3855 bt != VT_BOOL &&
3856 bt != VT_LLONG)
3857 tcc_error("bitfields must have scalar type");
3858 bsize = size * 8;
3859 if (bit_size > bsize) {
3860 tcc_error("width of '%s' exceeds its type",
3861 get_tok_str(v, NULL));
3862 } else if (bit_size == bsize
3863 && !ad.a.packed && !ad1.a.packed) {
3864 /* no need for bit fields */
3866 } else if (bit_size == 64) {
3867 tcc_error("field width 64 not implemented");
3868 } else {
3869 type1.t = (type1.t & ~VT_STRUCT_MASK)
3870 | VT_BITFIELD
3871 | (bit_size << (VT_STRUCT_SHIFT + 6));
3874 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3875 /* Remember we've seen a real field to check
3876 for placement of flexible array member. */
3877 c = 1;
3879 /* If member is a struct or bit-field, enforce
3880 placing into the struct (as anonymous). */
3881 if (v == 0 &&
3882 ((type1.t & VT_BTYPE) == VT_STRUCT ||
3883 bit_size >= 0)) {
3884 v = anon_sym++;
3886 if (v) {
3887 ss = sym_push(v | SYM_FIELD, &type1, 0, 0);
3888 ss->a = ad1.a;
3889 *ps = ss;
3890 ps = &ss->next;
3892 if (tok == ';' || tok == TOK_EOF)
3893 break;
3894 skip(',');
3896 skip(';');
3898 skip('}');
3899 parse_attribute(&ad);
3900 struct_layout(type, &ad);
3905 static void sym_to_attr(AttributeDef *ad, Sym *s)
3907 if (s->a.aligned && 0 == ad->a.aligned)
3908 ad->a.aligned = s->a.aligned;
3909 if (s->f.func_call && 0 == ad->f.func_call)
3910 ad->f.func_call = s->f.func_call;
3911 if (s->f.func_type && 0 == ad->f.func_type)
3912 ad->f.func_type = s->f.func_type;
3913 if (s->a.packed)
3914 ad->a.packed = 1;
3917 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3918 are added to the element type, copied because it could be a typedef. */
3919 static void parse_btype_qualify(CType *type, int qualifiers)
3921 while (type->t & VT_ARRAY) {
3922 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3923 type = &type->ref->type;
3925 type->t |= qualifiers;
3928 /* return 0 if no type declaration. otherwise, return the basic type
3929 and skip it.
3931 static int parse_btype(CType *type, AttributeDef *ad)
3933 int t, u, bt, st, type_found, typespec_found, g;
3934 Sym *s;
3935 CType type1;
3937 memset(ad, 0, sizeof(AttributeDef));
3938 type_found = 0;
3939 typespec_found = 0;
3940 t = VT_INT;
3941 bt = st = -1;
3942 type->ref = NULL;
3944 while(1) {
3945 switch(tok) {
3946 case TOK_EXTENSION:
3947 /* currently, we really ignore extension */
3948 next();
3949 continue;
3951 /* basic types */
3952 case TOK_CHAR:
3953 u = VT_BYTE;
3954 basic_type:
3955 next();
3956 basic_type1:
3957 if (u == VT_SHORT) {
3958 if (st != -1 || (bt != -1 && bt != VT_INT))
3959 tmbt: tcc_error("too many basic types");
3960 st = u;
3961 } else {
3962 if (bt != -1 || (st != -1 && u != VT_INT))
3963 goto tmbt;
3964 bt = u;
3966 if (u != VT_INT)
3967 t = (t & ~VT_BTYPE) | u;
3968 typespec_found = 1;
3969 break;
3970 case TOK_VOID:
3971 u = VT_VOID;
3972 goto basic_type;
3973 case TOK_SHORT:
3974 u = VT_SHORT;
3975 goto basic_type;
3976 case TOK_INT:
3977 u = VT_INT;
3978 goto basic_type;
3979 case TOK_LONG:
3980 if ((t & VT_BTYPE) == VT_DOUBLE) {
3981 #ifndef TCC_TARGET_PE
3982 t = (t & ~(VT_LONG | VT_BTYPE)) | VT_LDOUBLE;
3983 #endif
3984 } else if (t & VT_LONG) {
3985 t = (t & ~(VT_LONG | VT_BTYPE)) | VT_LLONG;
3986 } else {
3987 t |= VT_LONG;
3988 typespec_found = 1;
3990 next();
3991 break;
3992 #ifdef TCC_TARGET_ARM64
3993 case TOK_UINT128:
3994 /* GCC's __uint128_t appears in some Linux header files. Make it a
3995 synonym for long double to get the size and alignment right. */
3996 u = VT_LDOUBLE;
3997 goto basic_type;
3998 #endif
3999 case TOK_BOOL:
4000 u = VT_BOOL;
4001 goto basic_type;
4002 case TOK_FLOAT:
4003 u = VT_FLOAT;
4004 goto basic_type;
4005 case TOK_DOUBLE:
4006 if (t & VT_LONG) {
4007 #ifdef TCC_TARGET_PE
4008 t = (t & ~(VT_LONG | VT_BTYPE)) | VT_DOUBLE;
4009 #else
4010 t = (t & ~(VT_LONG | VT_BTYPE)) | VT_LDOUBLE;
4011 #endif
4012 } else {
4013 u = VT_DOUBLE;
4014 goto basic_type;
4016 next();
4017 break;
4018 case TOK_ENUM:
4019 struct_decl(&type1, VT_ENUM);
4020 basic_type2:
4021 u = type1.t;
4022 type->ref = type1.ref;
4023 goto basic_type1;
4024 case TOK_STRUCT:
4025 struct_decl(&type1, VT_STRUCT);
4026 goto basic_type2;
4027 case TOK_UNION:
4028 struct_decl(&type1, VT_UNION);
4029 goto basic_type2;
4031 /* type modifiers */
4032 case TOK_CONST1:
4033 case TOK_CONST2:
4034 case TOK_CONST3:
4035 type->t = t;
4036 parse_btype_qualify(type, VT_CONSTANT);
4037 t = type->t;
4038 next();
4039 break;
4040 case TOK_VOLATILE1:
4041 case TOK_VOLATILE2:
4042 case TOK_VOLATILE3:
4043 type->t = t;
4044 parse_btype_qualify(type, VT_VOLATILE);
4045 t = type->t;
4046 next();
4047 break;
4048 case TOK_SIGNED1:
4049 case TOK_SIGNED2:
4050 case TOK_SIGNED3:
4051 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
4052 tcc_error("signed and unsigned modifier");
4053 t |= VT_DEFSIGN;
4054 next();
4055 typespec_found = 1;
4056 break;
4057 case TOK_REGISTER:
4058 case TOK_AUTO:
4059 case TOK_RESTRICT1:
4060 case TOK_RESTRICT2:
4061 case TOK_RESTRICT3:
4062 next();
4063 break;
4064 case TOK_UNSIGNED:
4065 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
4066 tcc_error("signed and unsigned modifier");
4067 t |= VT_DEFSIGN | VT_UNSIGNED;
4068 next();
4069 typespec_found = 1;
4070 break;
4072 /* storage */
4073 case TOK_EXTERN:
4074 g = VT_EXTERN;
4075 goto storage;
4076 case TOK_STATIC:
4077 g = VT_STATIC;
4078 goto storage;
4079 case TOK_TYPEDEF:
4080 g = VT_TYPEDEF;
4081 goto storage;
4082 storage:
4083 if (t & (VT_EXTERN|VT_STATIC|VT_TYPEDEF) & ~g)
4084 tcc_error("multiple storage classes");
4085 t |= g;
4086 next();
4087 break;
4088 case TOK_INLINE1:
4089 case TOK_INLINE2:
4090 case TOK_INLINE3:
4091 t |= VT_INLINE;
4092 next();
4093 break;
4095 /* GNUC attribute */
4096 case TOK_ATTRIBUTE1:
4097 case TOK_ATTRIBUTE2:
4098 parse_attribute(ad);
4099 if (ad->attr_mode) {
4100 u = ad->attr_mode -1;
4101 t = (t & ~VT_BTYPE) | u;
4103 break;
4104 /* GNUC typeof */
4105 case TOK_TYPEOF1:
4106 case TOK_TYPEOF2:
4107 case TOK_TYPEOF3:
4108 next();
4109 parse_expr_type(&type1);
4110 /* remove all storage modifiers except typedef */
4111 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
4112 if (type1.ref)
4113 sym_to_attr(ad, type1.ref);
4114 goto basic_type2;
4115 default:
4116 if (typespec_found)
4117 goto the_end;
4118 s = sym_find(tok);
4119 if (!s || !(s->type.t & VT_TYPEDEF))
4120 goto the_end;
4121 t &= ~VT_BTYPE;
4122 u = t & ~(VT_CONSTANT | VT_VOLATILE), t ^= u;
4123 type->t = (s->type.t & ~VT_TYPEDEF) | u;
4124 type->ref = s->type.ref;
4125 if (t)
4126 parse_btype_qualify(type, t);
4127 t = type->t;
4128 /* get attributes from typedef */
4129 sym_to_attr(ad, s);
4130 next();
4131 typespec_found = 1;
4132 st = bt = -2;
4133 break;
4135 type_found = 1;
4137 the_end:
4138 if (tcc_state->char_is_unsigned) {
4139 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
4140 t |= VT_UNSIGNED;
4143 /* long is never used as type */
4144 if (t & VT_LONG)
4145 #if PTR_SIZE == 8 && !defined TCC_TARGET_PE
4146 t = (t & ~VT_BTYPE) | VT_LLONG;
4147 #else
4148 t = (t & ~VT_BTYPE) | VT_INT;
4149 #endif
4150 type->t = t;
4151 return type_found;
4154 /* convert a function parameter type (array to pointer and function to
4155 function pointer) */
4156 static inline void convert_parameter_type(CType *pt)
4158 /* remove const and volatile qualifiers (XXX: const could be used
4159 to indicate a const function parameter */
4160 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
4161 /* array must be transformed to pointer according to ANSI C */
4162 pt->t &= ~VT_ARRAY;
4163 if ((pt->t & VT_BTYPE) == VT_FUNC) {
4164 mk_pointer(pt);
4168 ST_FUNC void parse_asm_str(CString *astr)
4170 skip('(');
4171 parse_mult_str(astr, "string constant");
4174 /* Parse an asm label and return the token */
4175 static int asm_label_instr(void)
4177 int v;
4178 CString astr;
4180 next();
4181 parse_asm_str(&astr);
4182 skip(')');
4183 #ifdef ASM_DEBUG
4184 printf("asm_alias: \"%s\"\n", (char *)astr.data);
4185 #endif
4186 v = tok_alloc(astr.data, astr.size - 1)->tok;
4187 cstr_free(&astr);
4188 return v;
4191 static int post_type(CType *type, AttributeDef *ad, int storage, int td)
4193 int n, l, t1, arg_size, align;
4194 Sym **plast, *s, *first;
4195 AttributeDef ad1;
4196 CType pt;
4198 if (tok == '(') {
4199 /* function type, or recursive declarator (return if so) */
4200 next();
4201 if (td && !(td & TYPE_ABSTRACT))
4202 return 0;
4203 if (tok == ')')
4204 l = 0;
4205 else if (parse_btype(&pt, &ad1))
4206 l = FUNC_NEW;
4207 else if (td)
4208 return 0;
4209 else
4210 l = FUNC_OLD;
4211 first = NULL;
4212 plast = &first;
4213 arg_size = 0;
4214 if (l) {
4215 for(;;) {
4216 /* read param name and compute offset */
4217 if (l != FUNC_OLD) {
4218 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
4219 break;
4220 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
4221 if ((pt.t & VT_BTYPE) == VT_VOID)
4222 tcc_error("parameter declared as void");
4223 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
4224 } else {
4225 n = tok;
4226 if (n < TOK_UIDENT)
4227 expect("identifier");
4228 pt.t = VT_VOID; /* invalid type */
4229 next();
4231 convert_parameter_type(&pt);
4232 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
4233 *plast = s;
4234 plast = &s->next;
4235 if (tok == ')')
4236 break;
4237 skip(',');
4238 if (l == FUNC_NEW && tok == TOK_DOTS) {
4239 l = FUNC_ELLIPSIS;
4240 next();
4241 break;
4243 if (l == FUNC_NEW && !parse_btype(&pt, &ad1))
4244 tcc_error("invalid type");
4246 } else
4247 /* if no parameters, then old type prototype */
4248 l = FUNC_OLD;
4249 skip(')');
4250 /* NOTE: const is ignored in returned type as it has a special
4251 meaning in gcc / C++ */
4252 type->t &= ~VT_CONSTANT;
4253 /* some ancient pre-K&R C allows a function to return an array
4254 and the array brackets to be put after the arguments, such
4255 that "int c()[]" means something like "int[] c()" */
4256 if (tok == '[') {
4257 next();
4258 skip(']'); /* only handle simple "[]" */
4259 mk_pointer(type);
4261 /* we push a anonymous symbol which will contain the function prototype */
4262 ad->f.func_args = arg_size;
4263 ad->f.func_type = l;
4264 s = sym_push(SYM_FIELD, type, 0, 0);
4265 s->a = ad->a;
4266 s->f = ad->f;
4267 s->next = first;
4268 type->t = VT_FUNC;
4269 type->ref = s;
4270 } else if (tok == '[') {
4271 int saved_nocode_wanted = nocode_wanted;
4272 /* array definition */
4273 next();
4274 if (tok == TOK_RESTRICT1)
4275 next();
4276 n = -1;
4277 t1 = 0;
4278 if (tok != ']') {
4279 if (!local_stack || (storage & VT_STATIC))
4280 vpushi(expr_const());
4281 else {
4282 /* VLAs (which can only happen with local_stack && !VT_STATIC)
4283 length must always be evaluated, even under nocode_wanted,
4284 so that its size slot is initialized (e.g. under sizeof
4285 or typeof). */
4286 nocode_wanted = 0;
4287 gexpr();
4289 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4290 n = vtop->c.i;
4291 if (n < 0)
4292 tcc_error("invalid array size");
4293 } else {
4294 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
4295 tcc_error("size of variable length array should be an integer");
4296 t1 = VT_VLA;
4299 skip(']');
4300 /* parse next post type */
4301 post_type(type, ad, storage, 0);
4302 if (type->t == VT_FUNC)
4303 tcc_error("declaration of an array of functions");
4304 t1 |= type->t & VT_VLA;
4306 if (t1 & VT_VLA) {
4307 loc -= type_size(&int_type, &align);
4308 loc &= -align;
4309 n = loc;
4311 vla_runtime_type_size(type, &align);
4312 gen_op('*');
4313 vset(&int_type, VT_LOCAL|VT_LVAL, n);
4314 vswap();
4315 vstore();
4317 if (n != -1)
4318 vpop();
4319 nocode_wanted = saved_nocode_wanted;
4321 /* we push an anonymous symbol which will contain the array
4322 element type */
4323 s = sym_push(SYM_FIELD, type, 0, n);
4324 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
4325 type->ref = s;
4327 return 1;
4330 /* Parse a type declarator (except basic type), and return the type
4331 in 'type'. 'td' is a bitmask indicating which kind of type decl is
4332 expected. 'type' should contain the basic type. 'ad' is the
4333 attribute definition of the basic type. It can be modified by
4334 type_decl(). If this (possibly abstract) declarator is a pointer chain
4335 it returns the innermost pointed to type (equals *type, but is a different
4336 pointer), otherwise returns type itself, that's used for recursive calls. */
4337 static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td)
4339 CType *post, *ret;
4340 int qualifiers, storage;
4342 /* recursive type, remove storage bits first, apply them later again */
4343 storage = type->t & VT_STORAGE;
4344 type->t &= ~VT_STORAGE;
4345 post = ret = type;
4347 while (tok == '*') {
4348 qualifiers = 0;
4349 redo:
4350 next();
4351 switch(tok) {
4352 case TOK_CONST1:
4353 case TOK_CONST2:
4354 case TOK_CONST3:
4355 qualifiers |= VT_CONSTANT;
4356 goto redo;
4357 case TOK_VOLATILE1:
4358 case TOK_VOLATILE2:
4359 case TOK_VOLATILE3:
4360 qualifiers |= VT_VOLATILE;
4361 goto redo;
4362 case TOK_RESTRICT1:
4363 case TOK_RESTRICT2:
4364 case TOK_RESTRICT3:
4365 goto redo;
4366 /* XXX: clarify attribute handling */
4367 case TOK_ATTRIBUTE1:
4368 case TOK_ATTRIBUTE2:
4369 parse_attribute(ad);
4370 break;
4372 mk_pointer(type);
4373 type->t |= qualifiers;
4374 if (ret == type)
4375 /* innermost pointed to type is the one for the first derivation */
4376 ret = pointed_type(type);
4379 if (tok == '(') {
4380 /* This is possibly a parameter type list for abstract declarators
4381 ('int ()'), use post_type for testing this. */
4382 if (!post_type(type, ad, 0, td)) {
4383 /* It's not, so it's a nested declarator, and the post operations
4384 apply to the innermost pointed to type (if any). */
4385 /* XXX: this is not correct to modify 'ad' at this point, but
4386 the syntax is not clear */
4387 parse_attribute(ad);
4388 post = type_decl(type, ad, v, td);
4389 skip(')');
4391 } else if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
4392 /* type identifier */
4393 *v = tok;
4394 next();
4395 } else {
4396 if (!(td & TYPE_ABSTRACT))
4397 expect("identifier");
4398 *v = 0;
4400 post_type(post, ad, storage, 0);
4401 parse_attribute(ad);
4402 type->t |= storage;
4403 return ret;
4406 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
4407 ST_FUNC int lvalue_type(int t)
4409 int bt, r;
4410 r = VT_LVAL;
4411 bt = t & VT_BTYPE;
4412 if (bt == VT_BYTE || bt == VT_BOOL)
4413 r |= VT_LVAL_BYTE;
4414 else if (bt == VT_SHORT)
4415 r |= VT_LVAL_SHORT;
4416 else
4417 return r;
4418 if (t & VT_UNSIGNED)
4419 r |= VT_LVAL_UNSIGNED;
4420 return r;
4423 /* indirection with full error checking and bound check */
4424 ST_FUNC void indir(void)
4426 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
4427 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
4428 return;
4429 expect("pointer");
4431 if (vtop->r & VT_LVAL)
4432 gv(RC_INT);
4433 vtop->type = *pointed_type(&vtop->type);
4434 /* Arrays and functions are never lvalues */
4435 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
4436 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
4437 vtop->r |= lvalue_type(vtop->type.t);
4438 /* if bound checking, the referenced pointer must be checked */
4439 #ifdef CONFIG_TCC_BCHECK
4440 if (tcc_state->do_bounds_check)
4441 vtop->r |= VT_MUSTBOUND;
4442 #endif
4446 /* pass a parameter to a function and do type checking and casting */
4447 static void gfunc_param_typed(Sym *func, Sym *arg)
4449 int func_type;
4450 CType type;
4452 func_type = func->f.func_type;
4453 if (func_type == FUNC_OLD ||
4454 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
4455 /* default casting : only need to convert float to double */
4456 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
4457 gen_cast_s(VT_DOUBLE);
4458 } else if (vtop->type.t & VT_BITFIELD) {
4459 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
4460 type.ref = vtop->type.ref;
4461 gen_cast(&type);
4463 } else if (arg == NULL) {
4464 tcc_error("too many arguments to function");
4465 } else {
4466 type = arg->type;
4467 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4468 gen_assign_cast(&type);
4472 /* parse an expression and return its type without any side effect. */
4473 static void expr_type(CType *type, void (*expr_fn)(void))
4475 nocode_wanted++;
4476 expr_fn();
4477 *type = vtop->type;
4478 vpop();
4479 nocode_wanted--;
4482 /* parse an expression of the form '(type)' or '(expr)' and return its
4483 type */
4484 static void parse_expr_type(CType *type)
4486 int n;
4487 AttributeDef ad;
4489 skip('(');
4490 if (parse_btype(type, &ad)) {
4491 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4492 } else {
4493 expr_type(type, gexpr);
4495 skip(')');
4498 static void parse_type(CType *type)
4500 AttributeDef ad;
4501 int n;
4503 if (!parse_btype(type, &ad)) {
4504 expect("type");
4506 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4509 static void parse_builtin_params(int nc, const char *args)
4511 char c, sep = '(';
4512 CType t;
4513 if (nc)
4514 nocode_wanted++;
4515 next();
4516 while ((c = *args++)) {
4517 skip(sep);
4518 sep = ',';
4519 switch (c) {
4520 case 'e': expr_eq(); continue;
4521 case 't': parse_type(&t); vpush(&t); continue;
4522 default: tcc_error("internal error"); break;
4525 skip(')');
4526 if (nc)
4527 nocode_wanted--;
4530 ST_FUNC void unary(void)
4532 int n, t, align, size, r, sizeof_caller;
4533 CType type;
4534 Sym *s;
4535 AttributeDef ad;
4537 sizeof_caller = in_sizeof;
4538 in_sizeof = 0;
4539 type.ref = NULL;
4540 /* XXX: GCC 2.95.3 does not generate a table although it should be
4541 better here */
4542 tok_next:
4543 switch(tok) {
4544 case TOK_EXTENSION:
4545 next();
4546 goto tok_next;
4547 case TOK_CINT:
4548 case TOK_CCHAR:
4549 case TOK_LCHAR:
4550 t = VT_INT;
4551 push_tokc:
4552 type.t = t;
4553 vsetc(&type, VT_CONST, &tokc);
4554 next();
4555 break;
4556 case TOK_CUINT:
4557 t = VT_INT | VT_UNSIGNED;
4558 goto push_tokc;
4559 case TOK_CLLONG:
4560 t = VT_LLONG;
4561 goto push_tokc;
4562 case TOK_CULLONG:
4563 t = VT_LLONG | VT_UNSIGNED;
4564 goto push_tokc;
4565 case TOK_CFLOAT:
4566 t = VT_FLOAT;
4567 goto push_tokc;
4568 case TOK_CDOUBLE:
4569 t = VT_DOUBLE;
4570 goto push_tokc;
4571 case TOK_CLDOUBLE:
4572 t = VT_LDOUBLE;
4573 goto push_tokc;
4574 case TOK_CLONG:
4575 case TOK_CULONG:
4576 #ifdef TCC_LONG_ARE_64_BIT
4577 t = VT_LLONG | VT_LONG;
4578 #else
4579 t = VT_INT | VT_LONG;
4580 #endif
4581 if (tok == TOK_CULONG)
4582 t |= VT_UNSIGNED;
4583 goto push_tokc;
4584 case TOK___FUNCTION__:
4585 if (!gnu_ext)
4586 goto tok_identifier;
4587 /* fall thru */
4588 case TOK___FUNC__:
4590 void *ptr;
4591 int len;
4592 /* special function name identifier */
4593 len = strlen(funcname) + 1;
4594 /* generate char[len] type */
4595 type.t = VT_BYTE;
4596 mk_pointer(&type);
4597 type.t |= VT_ARRAY;
4598 type.ref->c = len;
4599 vpush_ref(&type, data_section, data_section->data_offset, len);
4600 if (!NODATA_WANTED) {
4601 ptr = section_ptr_add(data_section, len);
4602 memcpy(ptr, funcname, len);
4604 next();
4606 break;
4607 case TOK_LSTR:
4608 #ifdef TCC_TARGET_PE
4609 t = VT_SHORT | VT_UNSIGNED;
4610 #else
4611 t = VT_INT;
4612 #endif
4613 goto str_init;
4614 case TOK_STR:
4615 /* string parsing */
4616 t = VT_BYTE;
4617 if (tcc_state->char_is_unsigned)
4618 t = VT_BYTE | VT_UNSIGNED;
4619 str_init:
4620 if (tcc_state->warn_write_strings)
4621 t |= VT_CONSTANT;
4622 type.t = t;
4623 mk_pointer(&type);
4624 type.t |= VT_ARRAY;
4625 memset(&ad, 0, sizeof(AttributeDef));
4626 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
4627 break;
4628 case '(':
4629 next();
4630 /* cast ? */
4631 if (parse_btype(&type, &ad)) {
4632 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
4633 skip(')');
4634 /* check ISOC99 compound literal */
4635 if (tok == '{') {
4636 /* data is allocated locally by default */
4637 if (global_expr)
4638 r = VT_CONST;
4639 else
4640 r = VT_LOCAL;
4641 /* all except arrays are lvalues */
4642 if (!(type.t & VT_ARRAY))
4643 r |= lvalue_type(type.t);
4644 memset(&ad, 0, sizeof(AttributeDef));
4645 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
4646 } else {
4647 if (sizeof_caller) {
4648 vpush(&type);
4649 return;
4651 unary();
4652 gen_cast(&type);
4654 } else if (tok == '{') {
4655 int saved_nocode_wanted = nocode_wanted;
4656 if (const_wanted)
4657 tcc_error("expected constant");
4658 /* save all registers */
4659 save_regs(0);
4660 /* statement expression : we do not accept break/continue
4661 inside as GCC does. We do retain the nocode_wanted state,
4662 as statement expressions can't ever be entered from the
4663 outside, so any reactivation of code emission (from labels
4664 or loop heads) can be disabled again after the end of it. */
4665 block(NULL, NULL, 1);
4666 nocode_wanted = saved_nocode_wanted;
4667 skip(')');
4668 } else {
4669 gexpr();
4670 skip(')');
4672 break;
4673 case '*':
4674 next();
4675 unary();
4676 indir();
4677 break;
4678 case '&':
4679 next();
4680 unary();
4681 /* functions names must be treated as function pointers,
4682 except for unary '&' and sizeof. Since we consider that
4683 functions are not lvalues, we only have to handle it
4684 there and in function calls. */
4685 /* arrays can also be used although they are not lvalues */
4686 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
4687 !(vtop->type.t & VT_ARRAY))
4688 test_lvalue();
4689 mk_pointer(&vtop->type);
4690 gaddrof();
4691 break;
4692 case '!':
4693 next();
4694 unary();
4695 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4696 gen_cast_s(VT_BOOL);
4697 vtop->c.i = !vtop->c.i;
4698 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
4699 vtop->c.i ^= 1;
4700 else {
4701 save_regs(1);
4702 vseti(VT_JMP, gvtst(1, 0));
4704 break;
4705 case '~':
4706 next();
4707 unary();
4708 vpushi(-1);
4709 gen_op('^');
4710 break;
4711 case '+':
4712 next();
4713 unary();
4714 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
4715 tcc_error("pointer not accepted for unary plus");
4716 /* In order to force cast, we add zero, except for floating point
4717 where we really need an noop (otherwise -0.0 will be transformed
4718 into +0.0). */
4719 if (!is_float(vtop->type.t)) {
4720 vpushi(0);
4721 gen_op('+');
4723 break;
4724 case TOK_SIZEOF:
4725 case TOK_ALIGNOF1:
4726 case TOK_ALIGNOF2:
4727 t = tok;
4728 next();
4729 in_sizeof++;
4730 expr_type(&type, unary); /* Perform a in_sizeof = 0; */
4731 s = vtop[1].sym; /* hack: accessing previous vtop */
4732 size = type_size(&type, &align);
4733 if (s && s->a.aligned)
4734 align = 1 << (s->a.aligned - 1);
4735 if (t == TOK_SIZEOF) {
4736 if (!(type.t & VT_VLA)) {
4737 if (size < 0)
4738 tcc_error("sizeof applied to an incomplete type");
4739 vpushs(size);
4740 } else {
4741 vla_runtime_type_size(&type, &align);
4743 } else {
4744 vpushs(align);
4746 vtop->type.t |= VT_UNSIGNED;
4747 break;
4749 case TOK_builtin_expect:
4750 /* __builtin_expect is a no-op for now */
4751 parse_builtin_params(0, "ee");
4752 vpop();
4753 break;
4754 case TOK_builtin_types_compatible_p:
4755 parse_builtin_params(0, "tt");
4756 vtop[-1].type.t &= ~(VT_CONSTANT | VT_VOLATILE);
4757 vtop[0].type.t &= ~(VT_CONSTANT | VT_VOLATILE);
4758 n = is_compatible_types(&vtop[-1].type, &vtop[0].type);
4759 vtop -= 2;
4760 vpushi(n);
4761 break;
4762 case TOK_builtin_choose_expr:
4764 int64_t c;
4765 next();
4766 skip('(');
4767 c = expr_const64();
4768 skip(',');
4769 if (!c) {
4770 nocode_wanted++;
4772 expr_eq();
4773 if (!c) {
4774 vpop();
4775 nocode_wanted--;
4777 skip(',');
4778 if (c) {
4779 nocode_wanted++;
4781 expr_eq();
4782 if (c) {
4783 vpop();
4784 nocode_wanted--;
4786 skip(')');
4788 break;
4789 case TOK_builtin_constant_p:
4790 parse_builtin_params(1, "e");
4791 n = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
4792 vtop--;
4793 vpushi(n);
4794 break;
4795 case TOK_builtin_frame_address:
4796 case TOK_builtin_return_address:
4798 int tok1 = tok;
4799 int level;
4800 next();
4801 skip('(');
4802 if (tok != TOK_CINT) {
4803 tcc_error("%s only takes positive integers",
4804 tok1 == TOK_builtin_return_address ?
4805 "__builtin_return_address" :
4806 "__builtin_frame_address");
4808 level = (uint32_t)tokc.i;
4809 next();
4810 skip(')');
4811 type.t = VT_VOID;
4812 mk_pointer(&type);
4813 vset(&type, VT_LOCAL, 0); /* local frame */
4814 while (level--) {
4815 mk_pointer(&vtop->type);
4816 indir(); /* -> parent frame */
4818 if (tok1 == TOK_builtin_return_address) {
4819 // assume return address is just above frame pointer on stack
4820 vpushi(PTR_SIZE);
4821 gen_op('+');
4822 mk_pointer(&vtop->type);
4823 indir();
4826 break;
4827 #ifdef TCC_TARGET_X86_64
4828 #ifdef TCC_TARGET_PE
4829 case TOK_builtin_va_start:
4830 parse_builtin_params(0, "ee");
4831 r = vtop->r & VT_VALMASK;
4832 if (r == VT_LLOCAL)
4833 r = VT_LOCAL;
4834 if (r != VT_LOCAL)
4835 tcc_error("__builtin_va_start expects a local variable");
4836 vtop->r = r;
4837 vtop->type = char_pointer_type;
4838 vtop->c.i += 8;
4839 vstore();
4840 break;
4841 #else
4842 case TOK_builtin_va_arg_types:
4843 parse_builtin_params(0, "t");
4844 vpushi(classify_x86_64_va_arg(&vtop->type));
4845 vswap();
4846 vpop();
4847 break;
4848 #endif
4849 #endif
4851 #ifdef TCC_TARGET_ARM64
4852 case TOK___va_start: {
4853 parse_builtin_params(0, "ee");
4854 //xx check types
4855 gen_va_start();
4856 vpushi(0);
4857 vtop->type.t = VT_VOID;
4858 break;
4860 case TOK___va_arg: {
4861 parse_builtin_params(0, "et");
4862 type = vtop->type;
4863 vpop();
4864 //xx check types
4865 gen_va_arg(&type);
4866 vtop->type = type;
4867 break;
4869 case TOK___arm64_clear_cache: {
4870 parse_builtin_params(0, "ee");
4871 gen_clear_cache();
4872 vpushi(0);
4873 vtop->type.t = VT_VOID;
4874 break;
4876 #endif
4877 /* pre operations */
4878 case TOK_INC:
4879 case TOK_DEC:
4880 t = tok;
4881 next();
4882 unary();
4883 inc(0, t);
4884 break;
4885 case '-':
4886 next();
4887 unary();
4888 t = vtop->type.t & VT_BTYPE;
4889 if (is_float(t)) {
4890 /* In IEEE negate(x) isn't subtract(0,x), but rather
4891 subtract(-0, x). */
4892 vpush(&vtop->type);
4893 if (t == VT_FLOAT)
4894 vtop->c.f = -1.0 * 0.0;
4895 else if (t == VT_DOUBLE)
4896 vtop->c.d = -1.0 * 0.0;
4897 else
4898 vtop->c.ld = -1.0 * 0.0;
4899 } else
4900 vpushi(0);
4901 vswap();
4902 gen_op('-');
4903 break;
4904 case TOK_LAND:
4905 if (!gnu_ext)
4906 goto tok_identifier;
4907 next();
4908 /* allow to take the address of a label */
4909 if (tok < TOK_UIDENT)
4910 expect("label identifier");
4911 s = label_find(tok);
4912 if (!s) {
4913 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4914 } else {
4915 if (s->r == LABEL_DECLARED)
4916 s->r = LABEL_FORWARD;
4918 if (!s->type.t) {
4919 s->type.t = VT_VOID;
4920 mk_pointer(&s->type);
4921 s->type.t |= VT_STATIC;
4923 vpushsym(&s->type, s);
4924 next();
4925 break;
4927 case TOK_GENERIC:
4929 CType controlling_type;
4930 int has_default = 0;
4931 int has_match = 0;
4932 int learn = 0;
4933 TokenString *str = NULL;
4935 next();
4936 skip('(');
4937 expr_type(&controlling_type, expr_eq);
4938 controlling_type.t &= ~(VT_CONSTANT | VT_VOLATILE | VT_ARRAY);
4939 for (;;) {
4940 learn = 0;
4941 skip(',');
4942 if (tok == TOK_DEFAULT) {
4943 if (has_default)
4944 tcc_error("too many 'default'");
4945 has_default = 1;
4946 if (!has_match)
4947 learn = 1;
4948 next();
4949 } else {
4950 AttributeDef ad_tmp;
4951 int itmp;
4952 CType cur_type;
4953 parse_btype(&cur_type, &ad_tmp);
4954 type_decl(&cur_type, &ad_tmp, &itmp, TYPE_ABSTRACT);
4955 if (compare_types(&controlling_type, &cur_type, 0)) {
4956 if (has_match) {
4957 tcc_error("type match twice");
4959 has_match = 1;
4960 learn = 1;
4963 skip(':');
4964 if (learn) {
4965 if (str)
4966 tok_str_free(str);
4967 skip_or_save_block(&str);
4968 } else {
4969 skip_or_save_block(NULL);
4971 if (tok == ')')
4972 break;
4974 if (!str) {
4975 char buf[60];
4976 type_to_str(buf, sizeof buf, &controlling_type, NULL);
4977 tcc_error("type '%s' does not match any association", buf);
4979 begin_macro(str, 1);
4980 next();
4981 expr_eq();
4982 if (tok != TOK_EOF)
4983 expect(",");
4984 end_macro();
4985 next();
4986 break;
4988 // special qnan , snan and infinity values
4989 case TOK___NAN__:
4990 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4991 next();
4992 break;
4993 case TOK___SNAN__:
4994 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4995 next();
4996 break;
4997 case TOK___INF__:
4998 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4999 next();
5000 break;
5002 default:
5003 tok_identifier:
5004 t = tok;
5005 next();
5006 if (t < TOK_UIDENT)
5007 expect("identifier");
5008 s = sym_find(t);
5009 if (!s) {
5010 const char *name = get_tok_str(t, NULL);
5011 if (tok != '(')
5012 tcc_error("'%s' undeclared", name);
5013 /* for simple function calls, we tolerate undeclared
5014 external reference to int() function */
5015 if (tcc_state->warn_implicit_function_declaration
5016 #ifdef TCC_TARGET_PE
5017 /* people must be warned about using undeclared WINAPI functions
5018 (which usually start with uppercase letter) */
5019 || (name[0] >= 'A' && name[0] <= 'Z')
5020 #endif
5022 tcc_warning("implicit declaration of function '%s'", name);
5023 s = external_global_sym(t, &func_old_type, 0);
5026 r = s->r;
5027 /* A symbol that has a register is a local register variable,
5028 which starts out as VT_LOCAL value. */
5029 if ((r & VT_VALMASK) < VT_CONST)
5030 r = (r & ~VT_VALMASK) | VT_LOCAL;
5032 vset(&s->type, r, s->c);
5033 /* Point to s as backpointer (even without r&VT_SYM).
5034 Will be used by at least the x86 inline asm parser for
5035 regvars. */
5036 vtop->sym = s;
5038 if (r & VT_SYM) {
5039 vtop->c.i = 0;
5040 } else if (r == VT_CONST && IS_ENUM_VAL(s->type.t)) {
5041 vtop->c.i = s->enum_val;
5043 break;
5046 /* post operations */
5047 while (1) {
5048 if (tok == TOK_INC || tok == TOK_DEC) {
5049 inc(1, tok);
5050 next();
5051 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
5052 int qualifiers;
5053 /* field */
5054 if (tok == TOK_ARROW)
5055 indir();
5056 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
5057 test_lvalue();
5058 gaddrof();
5059 /* expect pointer on structure */
5060 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
5061 expect("struct or union");
5062 if (tok == TOK_CDOUBLE)
5063 expect("field name");
5064 next();
5065 if (tok == TOK_CINT || tok == TOK_CUINT)
5066 expect("field name");
5067 s = find_field(&vtop->type, tok);
5068 if (!s)
5069 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
5070 /* add field offset to pointer */
5071 vtop->type = char_pointer_type; /* change type to 'char *' */
5072 vpushi(s->c);
5073 gen_op('+');
5074 /* change type to field type, and set to lvalue */
5075 vtop->type = s->type;
5076 vtop->type.t |= qualifiers;
5077 /* an array is never an lvalue */
5078 if (!(vtop->type.t & VT_ARRAY)) {
5079 vtop->r |= lvalue_type(vtop->type.t);
5080 #ifdef CONFIG_TCC_BCHECK
5081 /* if bound checking, the referenced pointer must be checked */
5082 if (tcc_state->do_bounds_check && (vtop->r & VT_VALMASK) != VT_LOCAL)
5083 vtop->r |= VT_MUSTBOUND;
5084 #endif
5086 next();
5087 } else if (tok == '[') {
5088 next();
5089 gexpr();
5090 gen_op('+');
5091 indir();
5092 skip(']');
5093 } else if (tok == '(') {
5094 SValue ret;
5095 Sym *sa;
5096 int nb_args, ret_nregs, ret_align, regsize, variadic;
5098 /* function call */
5099 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
5100 /* pointer test (no array accepted) */
5101 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
5102 vtop->type = *pointed_type(&vtop->type);
5103 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
5104 goto error_func;
5105 } else {
5106 error_func:
5107 expect("function pointer");
5109 } else {
5110 vtop->r &= ~VT_LVAL; /* no lvalue */
5112 /* get return type */
5113 s = vtop->type.ref;
5114 next();
5115 sa = s->next; /* first parameter */
5116 nb_args = regsize = 0;
5117 ret.r2 = VT_CONST;
5118 /* compute first implicit argument if a structure is returned */
5119 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
5120 variadic = (s->f.func_type == FUNC_ELLIPSIS);
5121 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
5122 &ret_align, &regsize);
5123 if (!ret_nregs) {
5124 /* get some space for the returned structure */
5125 size = type_size(&s->type, &align);
5126 #ifdef TCC_TARGET_ARM64
5127 /* On arm64, a small struct is return in registers.
5128 It is much easier to write it to memory if we know
5129 that we are allowed to write some extra bytes, so
5130 round the allocated space up to a power of 2: */
5131 if (size < 16)
5132 while (size & (size - 1))
5133 size = (size | (size - 1)) + 1;
5134 #endif
5135 loc = (loc - size) & -align;
5136 ret.type = s->type;
5137 ret.r = VT_LOCAL | VT_LVAL;
5138 /* pass it as 'int' to avoid structure arg passing
5139 problems */
5140 vseti(VT_LOCAL, loc);
5141 ret.c = vtop->c;
5142 nb_args++;
5144 } else {
5145 ret_nregs = 1;
5146 ret.type = s->type;
5149 if (ret_nregs) {
5150 /* return in register */
5151 if (is_float(ret.type.t)) {
5152 ret.r = reg_fret(ret.type.t);
5153 #ifdef TCC_TARGET_X86_64
5154 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
5155 ret.r2 = REG_QRET;
5156 #endif
5157 } else {
5158 #ifndef TCC_TARGET_ARM64
5159 #ifdef TCC_TARGET_X86_64
5160 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
5161 #else
5162 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
5163 #endif
5164 ret.r2 = REG_LRET;
5165 #endif
5166 ret.r = REG_IRET;
5168 ret.c.i = 0;
5170 if (tok != ')') {
5171 for(;;) {
5172 expr_eq();
5173 gfunc_param_typed(s, sa);
5174 nb_args++;
5175 if (sa)
5176 sa = sa->next;
5177 if (tok == ')')
5178 break;
5179 skip(',');
5182 if (sa)
5183 tcc_error("too few arguments to function");
5184 skip(')');
5185 gfunc_call(nb_args);
5187 /* return value */
5188 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
5189 vsetc(&ret.type, r, &ret.c);
5190 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
5193 /* handle packed struct return */
5194 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
5195 int addr, offset;
5197 size = type_size(&s->type, &align);
5198 /* We're writing whole regs often, make sure there's enough
5199 space. Assume register size is power of 2. */
5200 if (regsize > align)
5201 align = regsize;
5202 loc = (loc - size) & -align;
5203 addr = loc;
5204 offset = 0;
5205 for (;;) {
5206 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
5207 vswap();
5208 vstore();
5209 vtop--;
5210 if (--ret_nregs == 0)
5211 break;
5212 offset += regsize;
5214 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
5216 } else {
5217 break;
5222 ST_FUNC void expr_prod(void)
5224 int t;
5226 unary();
5227 while (tok == '*' || tok == '/' || tok == '%') {
5228 t = tok;
5229 next();
5230 unary();
5231 gen_op(t);
5235 ST_FUNC void expr_sum(void)
5237 int t;
5239 expr_prod();
5240 while (tok == '+' || tok == '-') {
5241 t = tok;
5242 next();
5243 expr_prod();
5244 gen_op(t);
5248 static void expr_shift(void)
5250 int t;
5252 expr_sum();
5253 while (tok == TOK_SHL || tok == TOK_SAR) {
5254 t = tok;
5255 next();
5256 expr_sum();
5257 gen_op(t);
5261 static void expr_cmp(void)
5263 int t;
5265 expr_shift();
5266 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
5267 tok == TOK_ULT || tok == TOK_UGE) {
5268 t = tok;
5269 next();
5270 expr_shift();
5271 gen_op(t);
5275 static void expr_cmpeq(void)
5277 int t;
5279 expr_cmp();
5280 while (tok == TOK_EQ || tok == TOK_NE) {
5281 t = tok;
5282 next();
5283 expr_cmp();
5284 gen_op(t);
5288 static void expr_and(void)
5290 expr_cmpeq();
5291 while (tok == '&') {
5292 next();
5293 expr_cmpeq();
5294 gen_op('&');
5298 static void expr_xor(void)
5300 expr_and();
5301 while (tok == '^') {
5302 next();
5303 expr_and();
5304 gen_op('^');
5308 static void expr_or(void)
5310 expr_xor();
5311 while (tok == '|') {
5312 next();
5313 expr_xor();
5314 gen_op('|');
5318 static void expr_land(void)
5320 expr_or();
5321 if (tok == TOK_LAND) {
5322 int t = 0;
5323 for(;;) {
5324 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5325 gen_cast_s(VT_BOOL);
5326 if (vtop->c.i) {
5327 vpop();
5328 } else {
5329 nocode_wanted++;
5330 while (tok == TOK_LAND) {
5331 next();
5332 expr_or();
5333 vpop();
5335 nocode_wanted--;
5336 if (t)
5337 gsym(t);
5338 gen_cast_s(VT_INT);
5339 break;
5341 } else {
5342 if (!t)
5343 save_regs(1);
5344 t = gvtst(1, t);
5346 if (tok != TOK_LAND) {
5347 if (t)
5348 vseti(VT_JMPI, t);
5349 else
5350 vpushi(1);
5351 break;
5353 next();
5354 expr_or();
5359 static void expr_lor(void)
5361 expr_land();
5362 if (tok == TOK_LOR) {
5363 int t = 0;
5364 for(;;) {
5365 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5366 gen_cast_s(VT_BOOL);
5367 if (!vtop->c.i) {
5368 vpop();
5369 } else {
5370 nocode_wanted++;
5371 while (tok == TOK_LOR) {
5372 next();
5373 expr_land();
5374 vpop();
5376 nocode_wanted--;
5377 if (t)
5378 gsym(t);
5379 gen_cast_s(VT_INT);
5380 break;
5382 } else {
5383 if (!t)
5384 save_regs(1);
5385 t = gvtst(0, t);
5387 if (tok != TOK_LOR) {
5388 if (t)
5389 vseti(VT_JMP, t);
5390 else
5391 vpushi(0);
5392 break;
5394 next();
5395 expr_land();
5400 /* Assuming vtop is a value used in a conditional context
5401 (i.e. compared with zero) return 0 if it's false, 1 if
5402 true and -1 if it can't be statically determined. */
5403 static int condition_3way(void)
5405 int c = -1;
5406 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST &&
5407 (!(vtop->r & VT_SYM) || !vtop->sym->a.weak)) {
5408 vdup();
5409 gen_cast_s(VT_BOOL);
5410 c = vtop->c.i;
5411 vpop();
5413 return c;
5416 static void expr_cond(void)
5418 int tt, u, r1, r2, rc, t1, t2, bt1, bt2, islv, c, g;
5419 SValue sv;
5420 CType type, type1, type2;
5422 expr_lor();
5423 if (tok == '?') {
5424 next();
5425 c = condition_3way();
5426 g = (tok == ':' && gnu_ext);
5427 if (c < 0) {
5428 /* needed to avoid having different registers saved in
5429 each branch */
5430 if (is_float(vtop->type.t)) {
5431 rc = RC_FLOAT;
5432 #ifdef TCC_TARGET_X86_64
5433 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
5434 rc = RC_ST0;
5436 #endif
5437 } else
5438 rc = RC_INT;
5439 gv(rc);
5440 save_regs(1);
5441 if (g)
5442 gv_dup();
5443 tt = gvtst(1, 0);
5445 } else {
5446 if (!g)
5447 vpop();
5448 tt = 0;
5451 if (1) {
5452 if (c == 0)
5453 nocode_wanted++;
5454 if (!g)
5455 gexpr();
5457 type1 = vtop->type;
5458 sv = *vtop; /* save value to handle it later */
5459 vtop--; /* no vpop so that FP stack is not flushed */
5460 skip(':');
5462 u = 0;
5463 if (c < 0)
5464 u = gjmp(0);
5465 gsym(tt);
5467 if (c == 0)
5468 nocode_wanted--;
5469 if (c == 1)
5470 nocode_wanted++;
5471 expr_cond();
5472 if (c == 1)
5473 nocode_wanted--;
5475 type2 = vtop->type;
5476 t1 = type1.t;
5477 bt1 = t1 & VT_BTYPE;
5478 t2 = type2.t;
5479 bt2 = t2 & VT_BTYPE;
5480 type.ref = NULL;
5482 /* cast operands to correct type according to ISOC rules */
5483 if (is_float(bt1) || is_float(bt2)) {
5484 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5485 type.t = VT_LDOUBLE;
5487 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5488 type.t = VT_DOUBLE;
5489 } else {
5490 type.t = VT_FLOAT;
5492 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5493 /* cast to biggest op */
5494 type.t = VT_LLONG;
5495 /* convert to unsigned if it does not fit in a long long */
5496 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED) ||
5497 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED))
5498 type.t |= VT_UNSIGNED;
5499 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
5500 /* If one is a null ptr constant the result type
5501 is the other. */
5502 if (is_null_pointer (vtop))
5503 type = type1;
5504 else if (is_null_pointer (&sv))
5505 type = type2;
5506 /* XXX: test pointer compatibility, C99 has more elaborate
5507 rules here. */
5508 else
5509 type = type1;
5510 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
5511 /* XXX: test function pointer compatibility */
5512 type = bt1 == VT_FUNC ? type1 : type2;
5513 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
5514 /* XXX: test structure compatibility */
5515 type = bt1 == VT_STRUCT ? type1 : type2;
5516 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
5517 /* NOTE: as an extension, we accept void on only one side */
5518 type.t = VT_VOID;
5519 } else {
5520 /* integer operations */
5521 type.t = VT_INT;
5522 /* convert to unsigned if it does not fit in an integer */
5523 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED) ||
5524 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED))
5525 type.t |= VT_UNSIGNED;
5527 /* keep structs lvalue by transforming `(expr ? a : b)` to `*(expr ? &a : &b)` so
5528 that `(expr ? a : b).mem` does not error with "lvalue expected" */
5529 islv = (vtop->r & VT_LVAL) && (sv.r & VT_LVAL) && VT_STRUCT == (type.t & VT_BTYPE);
5530 islv &= c < 0;
5532 /* now we convert second operand */
5533 if (c != 1) {
5534 gen_cast(&type);
5535 if (islv) {
5536 mk_pointer(&vtop->type);
5537 gaddrof();
5538 } else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5539 gaddrof();
5542 rc = RC_INT;
5543 if (is_float(type.t)) {
5544 rc = RC_FLOAT;
5545 #ifdef TCC_TARGET_X86_64
5546 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
5547 rc = RC_ST0;
5549 #endif
5550 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
5551 /* for long longs, we use fixed registers to avoid having
5552 to handle a complicated move */
5553 rc = RC_IRET;
5556 tt = r2 = 0;
5557 if (c < 0) {
5558 r2 = gv(rc);
5559 tt = gjmp(0);
5561 gsym(u);
5563 /* this is horrible, but we must also convert first
5564 operand */
5565 if (c != 0) {
5566 *vtop = sv;
5567 gen_cast(&type);
5568 if (islv) {
5569 mk_pointer(&vtop->type);
5570 gaddrof();
5571 } else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5572 gaddrof();
5575 if (c < 0) {
5576 r1 = gv(rc);
5577 move_reg(r2, r1, type.t);
5578 vtop->r = r2;
5579 gsym(tt);
5580 if (islv)
5581 indir();
5587 static void expr_eq(void)
5589 int t;
5591 expr_cond();
5592 if (tok == '=' ||
5593 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
5594 tok == TOK_A_XOR || tok == TOK_A_OR ||
5595 tok == TOK_A_SHL || tok == TOK_A_SAR) {
5596 test_lvalue();
5597 t = tok;
5598 next();
5599 if (t == '=') {
5600 expr_eq();
5601 } else {
5602 vdup();
5603 expr_eq();
5604 gen_op(t & 0x7f);
5606 vstore();
5610 ST_FUNC void gexpr(void)
5612 while (1) {
5613 expr_eq();
5614 if (tok != ',')
5615 break;
5616 vpop();
5617 next();
5621 /* parse a constant expression and return value in vtop. */
5622 static void expr_const1(void)
5624 const_wanted++;
5625 nocode_wanted++;
5626 expr_cond();
5627 nocode_wanted--;
5628 const_wanted--;
5631 /* parse an integer constant and return its value. */
5632 static inline int64_t expr_const64(void)
5634 int64_t c;
5635 expr_const1();
5636 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5637 expect("constant expression");
5638 c = vtop->c.i;
5639 vpop();
5640 return c;
5643 /* parse an integer constant and return its value.
5644 Complain if it doesn't fit 32bit (signed or unsigned). */
5645 ST_FUNC int expr_const(void)
5647 int c;
5648 int64_t wc = expr_const64();
5649 c = wc;
5650 if (c != wc && (unsigned)c != wc)
5651 tcc_error("constant exceeds 32 bit");
5652 return c;
5655 /* return the label token if current token is a label, otherwise
5656 return zero */
5657 static int is_label(void)
5659 int last_tok;
5661 /* fast test first */
5662 if (tok < TOK_UIDENT)
5663 return 0;
5664 /* no need to save tokc because tok is an identifier */
5665 last_tok = tok;
5666 next();
5667 if (tok == ':') {
5668 return last_tok;
5669 } else {
5670 unget_tok(last_tok);
5671 return 0;
5675 #ifndef TCC_TARGET_ARM64
5676 static void gfunc_return(CType *func_type)
5678 if ((func_type->t & VT_BTYPE) == VT_STRUCT) {
5679 CType type, ret_type;
5680 int ret_align, ret_nregs, regsize;
5681 ret_nregs = gfunc_sret(func_type, func_var, &ret_type,
5682 &ret_align, &regsize);
5683 if (0 == ret_nregs) {
5684 /* if returning structure, must copy it to implicit
5685 first pointer arg location */
5686 type = *func_type;
5687 mk_pointer(&type);
5688 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
5689 indir();
5690 vswap();
5691 /* copy structure value to pointer */
5692 vstore();
5693 } else {
5694 /* returning structure packed into registers */
5695 int r, size, addr, align;
5696 size = type_size(func_type,&align);
5697 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
5698 (vtop->c.i & (ret_align-1)))
5699 && (align & (ret_align-1))) {
5700 loc = (loc - size) & -ret_align;
5701 addr = loc;
5702 type = *func_type;
5703 vset(&type, VT_LOCAL | VT_LVAL, addr);
5704 vswap();
5705 vstore();
5706 vpop();
5707 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
5709 vtop->type = ret_type;
5710 if (is_float(ret_type.t))
5711 r = rc_fret(ret_type.t);
5712 else
5713 r = RC_IRET;
5715 if (ret_nregs == 1)
5716 gv(r);
5717 else {
5718 for (;;) {
5719 vdup();
5720 gv(r);
5721 vpop();
5722 if (--ret_nregs == 0)
5723 break;
5724 /* We assume that when a structure is returned in multiple
5725 registers, their classes are consecutive values of the
5726 suite s(n) = 2^n */
5727 r <<= 1;
5728 vtop->c.i += regsize;
5732 } else if (is_float(func_type->t)) {
5733 gv(rc_fret(func_type->t));
5734 } else {
5735 gv(RC_IRET);
5737 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5739 #endif
5741 static int case_cmp(const void *pa, const void *pb)
5743 int64_t a = (*(struct case_t**) pa)->v1;
5744 int64_t b = (*(struct case_t**) pb)->v1;
5745 return a < b ? -1 : a > b;
5748 static void gcase(struct case_t **base, int len, int *bsym)
5750 struct case_t *p;
5751 int e;
5752 int ll = (vtop->type.t & VT_BTYPE) == VT_LLONG;
5753 gv(RC_INT);
5754 while (len > 4) {
5755 /* binary search */
5756 p = base[len/2];
5757 vdup();
5758 if (ll)
5759 vpushll(p->v2);
5760 else
5761 vpushi(p->v2);
5762 gen_op(TOK_LE);
5763 e = gtst(1, 0);
5764 vdup();
5765 if (ll)
5766 vpushll(p->v1);
5767 else
5768 vpushi(p->v1);
5769 gen_op(TOK_GE);
5770 gtst_addr(0, p->sym); /* v1 <= x <= v2 */
5771 /* x < v1 */
5772 gcase(base, len/2, bsym);
5773 if (cur_switch->def_sym)
5774 gjmp_addr(cur_switch->def_sym);
5775 else
5776 *bsym = gjmp(*bsym);
5777 /* x > v2 */
5778 gsym(e);
5779 e = len/2 + 1;
5780 base += e; len -= e;
5782 /* linear scan */
5783 while (len--) {
5784 p = *base++;
5785 vdup();
5786 if (ll)
5787 vpushll(p->v2);
5788 else
5789 vpushi(p->v2);
5790 if (p->v1 == p->v2) {
5791 gen_op(TOK_EQ);
5792 gtst_addr(0, p->sym);
5793 } else {
5794 gen_op(TOK_LE);
5795 e = gtst(1, 0);
5796 vdup();
5797 if (ll)
5798 vpushll(p->v1);
5799 else
5800 vpushi(p->v1);
5801 gen_op(TOK_GE);
5802 gtst_addr(0, p->sym);
5803 gsym(e);
5808 static void block(int *bsym, int *csym, int is_expr)
5810 int a, b, c, d, cond;
5811 Sym *s;
5813 /* generate line number info */
5814 if (tcc_state->do_debug)
5815 tcc_debug_line(tcc_state);
5817 if (is_expr) {
5818 /* default return value is (void) */
5819 vpushi(0);
5820 vtop->type.t = VT_VOID;
5823 if (tok == TOK_IF) {
5824 /* if test */
5825 int saved_nocode_wanted = nocode_wanted;
5826 next();
5827 skip('(');
5828 gexpr();
5829 skip(')');
5830 cond = condition_3way();
5831 if (cond == 1)
5832 a = 0, vpop();
5833 else
5834 a = gvtst(1, 0);
5835 if (cond == 0)
5836 nocode_wanted |= 0x20000000;
5837 block(bsym, csym, 0);
5838 if (cond != 1)
5839 nocode_wanted = saved_nocode_wanted;
5840 c = tok;
5841 if (c == TOK_ELSE) {
5842 next();
5843 d = gjmp(0);
5844 gsym(a);
5845 if (cond == 1)
5846 nocode_wanted |= 0x20000000;
5847 block(bsym, csym, 0);
5848 gsym(d); /* patch else jmp */
5849 if (cond != 0)
5850 nocode_wanted = saved_nocode_wanted;
5851 } else
5852 gsym(a);
5853 } else if (tok == TOK_WHILE) {
5854 int saved_nocode_wanted;
5855 nocode_wanted &= ~0x20000000;
5856 next();
5857 d = ind;
5858 vla_sp_restore();
5859 skip('(');
5860 gexpr();
5861 skip(')');
5862 a = gvtst(1, 0);
5863 b = 0;
5864 ++local_scope;
5865 saved_nocode_wanted = nocode_wanted;
5866 block(&a, &b, 0);
5867 nocode_wanted = saved_nocode_wanted;
5868 --local_scope;
5869 gjmp_addr(d);
5870 gsym(a);
5871 gsym_addr(b, d);
5872 } else if (tok == '{') {
5873 Sym *llabel;
5874 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
5876 next();
5877 /* record local declaration stack position */
5878 s = local_stack;
5879 llabel = local_label_stack;
5880 ++local_scope;
5882 /* handle local labels declarations */
5883 if (tok == TOK_LABEL) {
5884 next();
5885 for(;;) {
5886 if (tok < TOK_UIDENT)
5887 expect("label identifier");
5888 label_push(&local_label_stack, tok, LABEL_DECLARED);
5889 next();
5890 if (tok == ',') {
5891 next();
5892 } else {
5893 skip(';');
5894 break;
5898 while (tok != '}') {
5899 if ((a = is_label()))
5900 unget_tok(a);
5901 else
5902 decl(VT_LOCAL);
5903 if (tok != '}') {
5904 if (is_expr)
5905 vpop();
5906 block(bsym, csym, is_expr);
5909 /* pop locally defined labels */
5910 label_pop(&local_label_stack, llabel, is_expr);
5911 /* pop locally defined symbols */
5912 --local_scope;
5913 /* In the is_expr case (a statement expression is finished here),
5914 vtop might refer to symbols on the local_stack. Either via the
5915 type or via vtop->sym. We can't pop those nor any that in turn
5916 might be referred to. To make it easier we don't roll back
5917 any symbols in that case; some upper level call to block() will
5918 do that. We do have to remove such symbols from the lookup
5919 tables, though. sym_pop will do that. */
5920 sym_pop(&local_stack, s, is_expr);
5922 /* Pop VLA frames and restore stack pointer if required */
5923 if (vlas_in_scope > saved_vlas_in_scope) {
5924 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
5925 vla_sp_restore();
5927 vlas_in_scope = saved_vlas_in_scope;
5929 next();
5930 } else if (tok == TOK_RETURN) {
5931 next();
5932 if (tok != ';') {
5933 gexpr();
5934 gen_assign_cast(&func_vt);
5935 gfunc_return(&func_vt);
5937 skip(';');
5938 /* jump unless last stmt in top-level block */
5939 if (tok != '}' || local_scope != 1)
5940 rsym = gjmp(rsym);
5941 nocode_wanted |= 0x20000000;
5942 } else if (tok == TOK_BREAK) {
5943 /* compute jump */
5944 if (!bsym)
5945 tcc_error("cannot break");
5946 *bsym = gjmp(*bsym);
5947 next();
5948 skip(';');
5949 nocode_wanted |= 0x20000000;
5950 } else if (tok == TOK_CONTINUE) {
5951 /* compute jump */
5952 if (!csym)
5953 tcc_error("cannot continue");
5954 vla_sp_restore_root();
5955 *csym = gjmp(*csym);
5956 next();
5957 skip(';');
5958 } else if (tok == TOK_FOR) {
5959 int e;
5960 int saved_nocode_wanted;
5961 nocode_wanted &= ~0x20000000;
5962 next();
5963 skip('(');
5964 s = local_stack;
5965 ++local_scope;
5966 if (tok != ';') {
5967 /* c99 for-loop init decl? */
5968 if (!decl0(VT_LOCAL, 1, NULL)) {
5969 /* no, regular for-loop init expr */
5970 gexpr();
5971 vpop();
5974 skip(';');
5975 d = ind;
5976 c = ind;
5977 vla_sp_restore();
5978 a = 0;
5979 b = 0;
5980 if (tok != ';') {
5981 gexpr();
5982 a = gvtst(1, 0);
5984 skip(';');
5985 if (tok != ')') {
5986 e = gjmp(0);
5987 c = ind;
5988 vla_sp_restore();
5989 gexpr();
5990 vpop();
5991 gjmp_addr(d);
5992 gsym(e);
5994 skip(')');
5995 saved_nocode_wanted = nocode_wanted;
5996 block(&a, &b, 0);
5997 nocode_wanted = saved_nocode_wanted;
5998 gjmp_addr(c);
5999 gsym(a);
6000 gsym_addr(b, c);
6001 --local_scope;
6002 sym_pop(&local_stack, s, 0);
6004 } else
6005 if (tok == TOK_DO) {
6006 int saved_nocode_wanted;
6007 nocode_wanted &= ~0x20000000;
6008 next();
6009 a = 0;
6010 b = 0;
6011 d = ind;
6012 vla_sp_restore();
6013 saved_nocode_wanted = nocode_wanted;
6014 block(&a, &b, 0);
6015 skip(TOK_WHILE);
6016 skip('(');
6017 gsym(b);
6018 gexpr();
6019 c = gvtst(0, 0);
6020 gsym_addr(c, d);
6021 nocode_wanted = saved_nocode_wanted;
6022 skip(')');
6023 gsym(a);
6024 skip(';');
6025 } else
6026 if (tok == TOK_SWITCH) {
6027 struct switch_t *saved, sw;
6028 int saved_nocode_wanted = nocode_wanted;
6029 SValue switchval;
6030 next();
6031 skip('(');
6032 gexpr();
6033 skip(')');
6034 switchval = *vtop--;
6035 a = 0;
6036 b = gjmp(0); /* jump to first case */
6037 sw.p = NULL; sw.n = 0; sw.def_sym = 0;
6038 saved = cur_switch;
6039 cur_switch = &sw;
6040 block(&a, csym, 0);
6041 nocode_wanted = saved_nocode_wanted;
6042 a = gjmp(a); /* add implicit break */
6043 /* case lookup */
6044 gsym(b);
6045 qsort(sw.p, sw.n, sizeof(void*), case_cmp);
6046 for (b = 1; b < sw.n; b++)
6047 if (sw.p[b - 1]->v2 >= sw.p[b]->v1)
6048 tcc_error("duplicate case value");
6049 /* Our switch table sorting is signed, so the compared
6050 value needs to be as well when it's 64bit. */
6051 if ((switchval.type.t & VT_BTYPE) == VT_LLONG)
6052 switchval.type.t &= ~VT_UNSIGNED;
6053 vpushv(&switchval);
6054 gcase(sw.p, sw.n, &a);
6055 vpop();
6056 if (sw.def_sym)
6057 gjmp_addr(sw.def_sym);
6058 dynarray_reset(&sw.p, &sw.n);
6059 cur_switch = saved;
6060 /* break label */
6061 gsym(a);
6062 } else
6063 if (tok == TOK_CASE) {
6064 struct case_t *cr = tcc_malloc(sizeof(struct case_t));
6065 if (!cur_switch)
6066 expect("switch");
6067 nocode_wanted &= ~0x20000000;
6068 next();
6069 cr->v1 = cr->v2 = expr_const64();
6070 if (gnu_ext && tok == TOK_DOTS) {
6071 next();
6072 cr->v2 = expr_const64();
6073 if (cr->v2 < cr->v1)
6074 tcc_warning("empty case range");
6076 cr->sym = ind;
6077 dynarray_add(&cur_switch->p, &cur_switch->n, cr);
6078 skip(':');
6079 is_expr = 0;
6080 goto block_after_label;
6081 } else
6082 if (tok == TOK_DEFAULT) {
6083 next();
6084 skip(':');
6085 if (!cur_switch)
6086 expect("switch");
6087 if (cur_switch->def_sym)
6088 tcc_error("too many 'default'");
6089 cur_switch->def_sym = ind;
6090 is_expr = 0;
6091 goto block_after_label;
6092 } else
6093 if (tok == TOK_GOTO) {
6094 next();
6095 if (tok == '*' && gnu_ext) {
6096 /* computed goto */
6097 next();
6098 gexpr();
6099 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
6100 expect("pointer");
6101 ggoto();
6102 } else if (tok >= TOK_UIDENT) {
6103 s = label_find(tok);
6104 /* put forward definition if needed */
6105 if (!s) {
6106 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
6107 } else {
6108 if (s->r == LABEL_DECLARED)
6109 s->r = LABEL_FORWARD;
6111 vla_sp_restore_root();
6112 if (s->r & LABEL_FORWARD)
6113 s->jnext = gjmp(s->jnext);
6114 else
6115 gjmp_addr(s->jnext);
6116 next();
6117 } else {
6118 expect("label identifier");
6120 skip(';');
6121 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
6122 asm_instr();
6123 } else {
6124 b = is_label();
6125 if (b) {
6126 /* label case */
6127 next();
6128 s = label_find(b);
6129 if (s) {
6130 if (s->r == LABEL_DEFINED)
6131 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
6132 gsym(s->jnext);
6133 s->r = LABEL_DEFINED;
6134 } else {
6135 s = label_push(&global_label_stack, b, LABEL_DEFINED);
6137 s->jnext = ind;
6138 vla_sp_restore();
6139 /* we accept this, but it is a mistake */
6140 block_after_label:
6141 nocode_wanted &= ~0x20000000;
6142 if (tok == '}') {
6143 tcc_warning("deprecated use of label at end of compound statement");
6144 } else {
6145 if (is_expr)
6146 vpop();
6147 block(bsym, csym, is_expr);
6149 } else {
6150 /* expression case */
6151 if (tok != ';') {
6152 if (is_expr) {
6153 vpop();
6154 gexpr();
6155 } else {
6156 gexpr();
6157 vpop();
6160 skip(';');
6165 /* This skips over a stream of tokens containing balanced {} and ()
6166 pairs, stopping at outer ',' ';' and '}' (or matching '}' if we started
6167 with a '{'). If STR then allocates and stores the skipped tokens
6168 in *STR. This doesn't check if () and {} are nested correctly,
6169 i.e. "({)}" is accepted. */
6170 static void skip_or_save_block(TokenString **str)
6172 int braces = tok == '{';
6173 int level = 0;
6174 if (str)
6175 *str = tok_str_alloc();
6177 while ((level > 0 || (tok != '}' && tok != ',' && tok != ';' && tok != ')'))) {
6178 int t;
6179 if (tok == TOK_EOF) {
6180 if (str || level > 0)
6181 tcc_error("unexpected end of file");
6182 else
6183 break;
6185 if (str)
6186 tok_str_add_tok(*str);
6187 t = tok;
6188 next();
6189 if (t == '{' || t == '(') {
6190 level++;
6191 } else if (t == '}' || t == ')') {
6192 level--;
6193 if (level == 0 && braces && t == '}')
6194 break;
6197 if (str) {
6198 tok_str_add(*str, -1);
6199 tok_str_add(*str, 0);
6203 #define EXPR_CONST 1
6204 #define EXPR_ANY 2
6206 static void parse_init_elem(int expr_type)
6208 int saved_global_expr;
6209 switch(expr_type) {
6210 case EXPR_CONST:
6211 /* compound literals must be allocated globally in this case */
6212 saved_global_expr = global_expr;
6213 global_expr = 1;
6214 expr_const1();
6215 global_expr = saved_global_expr;
6216 /* NOTE: symbols are accepted, as well as lvalue for anon symbols
6217 (compound literals). */
6218 if (((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST
6219 && ((vtop->r & (VT_SYM|VT_LVAL)) != (VT_SYM|VT_LVAL)
6220 || vtop->sym->v < SYM_FIRST_ANOM))
6221 #ifdef TCC_TARGET_PE
6222 || ((vtop->r & VT_SYM) && vtop->sym->a.dllimport)
6223 #endif
6225 tcc_error("initializer element is not constant");
6226 break;
6227 case EXPR_ANY:
6228 expr_eq();
6229 break;
6233 /* put zeros for variable based init */
6234 static void init_putz(Section *sec, unsigned long c, int size)
6236 if (sec) {
6237 /* nothing to do because globals are already set to zero */
6238 } else {
6239 vpush_global_sym(&func_old_type, TOK_memset);
6240 vseti(VT_LOCAL, c);
6241 #ifdef TCC_TARGET_ARM
6242 vpushs(size);
6243 vpushi(0);
6244 #else
6245 vpushi(0);
6246 vpushs(size);
6247 #endif
6248 gfunc_call(3);
6252 /* t is the array or struct type. c is the array or struct
6253 address. cur_field is the pointer to the current
6254 field, for arrays the 'c' member contains the current start
6255 index. 'size_only' is true if only size info is needed (only used
6256 in arrays). al contains the already initialized length of the
6257 current container (starting at c). This returns the new length of that. */
6258 static int decl_designator(CType *type, Section *sec, unsigned long c,
6259 Sym **cur_field, int size_only, int al)
6261 Sym *s, *f;
6262 int index, index_last, align, l, nb_elems, elem_size;
6263 unsigned long corig = c;
6265 elem_size = 0;
6266 nb_elems = 1;
6267 if (gnu_ext && (l = is_label()) != 0)
6268 goto struct_field;
6269 /* NOTE: we only support ranges for last designator */
6270 while (nb_elems == 1 && (tok == '[' || tok == '.')) {
6271 if (tok == '[') {
6272 if (!(type->t & VT_ARRAY))
6273 expect("array type");
6274 next();
6275 index = index_last = expr_const();
6276 if (tok == TOK_DOTS && gnu_ext) {
6277 next();
6278 index_last = expr_const();
6280 skip(']');
6281 s = type->ref;
6282 if (index < 0 || (s->c >= 0 && index_last >= s->c) ||
6283 index_last < index)
6284 tcc_error("invalid index");
6285 if (cur_field)
6286 (*cur_field)->c = index_last;
6287 type = pointed_type(type);
6288 elem_size = type_size(type, &align);
6289 c += index * elem_size;
6290 nb_elems = index_last - index + 1;
6291 } else {
6292 next();
6293 l = tok;
6294 struct_field:
6295 next();
6296 if ((type->t & VT_BTYPE) != VT_STRUCT)
6297 expect("struct/union type");
6298 f = find_field(type, l);
6299 if (!f)
6300 expect("field");
6301 if (cur_field)
6302 *cur_field = f;
6303 type = &f->type;
6304 c += f->c;
6306 cur_field = NULL;
6308 if (!cur_field) {
6309 if (tok == '=') {
6310 next();
6311 } else if (!gnu_ext) {
6312 expect("=");
6314 } else {
6315 if (type->t & VT_ARRAY) {
6316 index = (*cur_field)->c;
6317 if (type->ref->c >= 0 && index >= type->ref->c)
6318 tcc_error("index too large");
6319 type = pointed_type(type);
6320 c += index * type_size(type, &align);
6321 } else {
6322 f = *cur_field;
6323 while (f && (f->v & SYM_FIRST_ANOM) && (f->type.t & VT_BITFIELD))
6324 *cur_field = f = f->next;
6325 if (!f)
6326 tcc_error("too many field init");
6327 type = &f->type;
6328 c += f->c;
6331 /* must put zero in holes (note that doing it that way
6332 ensures that it even works with designators) */
6333 if (!size_only && c - corig > al)
6334 init_putz(sec, corig + al, c - corig - al);
6335 decl_initializer(type, sec, c, 0, size_only);
6337 /* XXX: make it more general */
6338 if (!size_only && nb_elems > 1) {
6339 unsigned long c_end;
6340 uint8_t *src, *dst;
6341 int i;
6343 if (!sec) {
6344 vset(type, VT_LOCAL|VT_LVAL, c);
6345 for (i = 1; i < nb_elems; i++) {
6346 vset(type, VT_LOCAL|VT_LVAL, c + elem_size * i);
6347 vswap();
6348 vstore();
6350 vpop();
6351 } else if (!NODATA_WANTED) {
6352 c_end = c + nb_elems * elem_size;
6353 if (c_end > sec->data_allocated)
6354 section_realloc(sec, c_end);
6355 src = sec->data + c;
6356 dst = src;
6357 for(i = 1; i < nb_elems; i++) {
6358 dst += elem_size;
6359 memcpy(dst, src, elem_size);
6363 c += nb_elems * type_size(type, &align);
6364 if (c - corig > al)
6365 al = c - corig;
6366 return al;
6369 /* store a value or an expression directly in global data or in local array */
6370 static void init_putv(CType *type, Section *sec, unsigned long c)
6372 int bt;
6373 void *ptr;
6374 CType dtype;
6376 dtype = *type;
6377 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
6379 if (sec) {
6380 int size, align;
6381 /* XXX: not portable */
6382 /* XXX: generate error if incorrect relocation */
6383 gen_assign_cast(&dtype);
6384 bt = type->t & VT_BTYPE;
6386 if ((vtop->r & VT_SYM)
6387 && bt != VT_PTR
6388 && bt != VT_FUNC
6389 && (bt != (PTR_SIZE == 8 ? VT_LLONG : VT_INT)
6390 || (type->t & VT_BITFIELD))
6391 && !((vtop->r & VT_CONST) && vtop->sym->v >= SYM_FIRST_ANOM)
6393 tcc_error("initializer element is not computable at load time");
6395 if (NODATA_WANTED) {
6396 vtop--;
6397 return;
6400 size = type_size(type, &align);
6401 section_reserve(sec, c + size);
6402 ptr = sec->data + c;
6404 /* XXX: make code faster ? */
6405 if ((vtop->r & (VT_SYM|VT_CONST)) == (VT_SYM|VT_CONST) &&
6406 vtop->sym->v >= SYM_FIRST_ANOM &&
6407 /* XXX This rejects compound literals like
6408 '(void *){ptr}'. The problem is that '&sym' is
6409 represented the same way, which would be ruled out
6410 by the SYM_FIRST_ANOM check above, but also '"string"'
6411 in 'char *p = "string"' is represented the same
6412 with the type being VT_PTR and the symbol being an
6413 anonymous one. That is, there's no difference in vtop
6414 between '(void *){x}' and '&(void *){x}'. Ignore
6415 pointer typed entities here. Hopefully no real code
6416 will every use compound literals with scalar type. */
6417 (vtop->type.t & VT_BTYPE) != VT_PTR) {
6418 /* These come from compound literals, memcpy stuff over. */
6419 Section *ssec;
6420 ElfW(Sym) *esym;
6421 ElfW_Rel *rel;
6422 esym = &((ElfW(Sym) *)symtab_section->data)[vtop->sym->c];
6423 ssec = tcc_state->sections[esym->st_shndx];
6424 memmove (ptr, ssec->data + esym->st_value, size);
6425 if (ssec->reloc) {
6426 /* We need to copy over all memory contents, and that
6427 includes relocations. Use the fact that relocs are
6428 created it order, so look from the end of relocs
6429 until we hit one before the copied region. */
6430 int num_relocs = ssec->reloc->data_offset / sizeof(*rel);
6431 rel = (ElfW_Rel*)(ssec->reloc->data + ssec->reloc->data_offset);
6432 while (num_relocs--) {
6433 rel--;
6434 if (rel->r_offset >= esym->st_value + size)
6435 continue;
6436 if (rel->r_offset < esym->st_value)
6437 break;
6438 /* Note: if the same fields are initialized multiple
6439 times (possible with designators) then we possibly
6440 add multiple relocations for the same offset here.
6441 That would lead to wrong code, the last reloc needs
6442 to win. We clean this up later after the whole
6443 initializer is parsed. */
6444 put_elf_reloca(symtab_section, sec,
6445 c + rel->r_offset - esym->st_value,
6446 ELFW(R_TYPE)(rel->r_info),
6447 ELFW(R_SYM)(rel->r_info),
6448 #if PTR_SIZE == 8
6449 rel->r_addend
6450 #else
6452 #endif
6456 } else {
6457 if (type->t & VT_BITFIELD) {
6458 int bit_pos, bit_size, bits, n;
6459 unsigned char *p, v, m;
6460 bit_pos = BIT_POS(vtop->type.t);
6461 bit_size = BIT_SIZE(vtop->type.t);
6462 p = (unsigned char*)ptr + (bit_pos >> 3);
6463 bit_pos &= 7, bits = 0;
6464 while (bit_size) {
6465 n = 8 - bit_pos;
6466 if (n > bit_size)
6467 n = bit_size;
6468 v = vtop->c.i >> bits << bit_pos;
6469 m = ((1 << n) - 1) << bit_pos;
6470 *p = (*p & ~m) | (v & m);
6471 bits += n, bit_size -= n, bit_pos = 0, ++p;
6473 } else
6474 switch(bt) {
6475 /* XXX: when cross-compiling we assume that each type has the
6476 same representation on host and target, which is likely to
6477 be wrong in the case of long double */
6478 case VT_BOOL:
6479 vtop->c.i = vtop->c.i != 0;
6480 case VT_BYTE:
6481 *(char *)ptr |= vtop->c.i;
6482 break;
6483 case VT_SHORT:
6484 *(short *)ptr |= vtop->c.i;
6485 break;
6486 case VT_FLOAT:
6487 *(float*)ptr = vtop->c.f;
6488 break;
6489 case VT_DOUBLE:
6490 *(double *)ptr = vtop->c.d;
6491 break;
6492 case VT_LDOUBLE:
6493 if (sizeof(long double) == LDOUBLE_SIZE)
6494 *(long double *)ptr = vtop->c.ld;
6495 else if (sizeof(double) == LDOUBLE_SIZE)
6496 *(double *)ptr = (double)vtop->c.ld;
6497 #if (defined __i386__ || defined __x86_64__) && (defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64)
6498 else if (sizeof (long double) >= 10)
6499 memcpy(memset(ptr, 0, LDOUBLE_SIZE), &vtop->c.ld, 10);
6500 #ifdef __TINYC__
6501 else if (sizeof (long double) == sizeof (double))
6502 __asm__("fldl %1\nfstpt %0\n" : "=m"
6503 (memset(ptr, 0, LDOUBLE_SIZE), ptr) : "m" (vtop->c.ld));
6504 #endif
6505 #endif
6506 else
6507 tcc_error("can't cross compile long double constants");
6508 break;
6509 #if PTR_SIZE != 8
6510 case VT_LLONG:
6511 *(long long *)ptr |= vtop->c.i;
6512 break;
6513 #else
6514 case VT_LLONG:
6515 #endif
6516 case VT_PTR:
6518 addr_t val = vtop->c.i;
6519 #if PTR_SIZE == 8
6520 if (vtop->r & VT_SYM)
6521 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6522 else
6523 *(addr_t *)ptr |= val;
6524 #else
6525 if (vtop->r & VT_SYM)
6526 greloc(sec, vtop->sym, c, R_DATA_PTR);
6527 *(addr_t *)ptr |= val;
6528 #endif
6529 break;
6531 default:
6533 int val = vtop->c.i;
6534 #if PTR_SIZE == 8
6535 if (vtop->r & VT_SYM)
6536 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6537 else
6538 *(int *)ptr |= val;
6539 #else
6540 if (vtop->r & VT_SYM)
6541 greloc(sec, vtop->sym, c, R_DATA_PTR);
6542 *(int *)ptr |= val;
6543 #endif
6544 break;
6548 vtop--;
6549 } else {
6550 vset(&dtype, VT_LOCAL|VT_LVAL, c);
6551 vswap();
6552 vstore();
6553 vpop();
6557 /* 't' contains the type and storage info. 'c' is the offset of the
6558 object in section 'sec'. If 'sec' is NULL, it means stack based
6559 allocation. 'first' is true if array '{' must be read (multi
6560 dimension implicit array init handling). 'size_only' is true if
6561 size only evaluation is wanted (only for arrays). */
6562 static void decl_initializer(CType *type, Section *sec, unsigned long c,
6563 int first, int size_only)
6565 int len, n, no_oblock, nb, i;
6566 int size1, align1;
6567 int have_elem;
6568 Sym *s, *f;
6569 Sym indexsym;
6570 CType *t1;
6572 /* If we currently are at an '}' or ',' we have read an initializer
6573 element in one of our callers, and not yet consumed it. */
6574 have_elem = tok == '}' || tok == ',';
6575 if (!have_elem && tok != '{' &&
6576 /* In case of strings we have special handling for arrays, so
6577 don't consume them as initializer value (which would commit them
6578 to some anonymous symbol). */
6579 tok != TOK_LSTR && tok != TOK_STR &&
6580 !size_only) {
6581 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6582 have_elem = 1;
6585 if (have_elem &&
6586 !(type->t & VT_ARRAY) &&
6587 /* Use i_c_parameter_t, to strip toplevel qualifiers.
6588 The source type might have VT_CONSTANT set, which is
6589 of course assignable to non-const elements. */
6590 is_compatible_unqualified_types(type, &vtop->type)) {
6591 init_putv(type, sec, c);
6592 } else if (type->t & VT_ARRAY) {
6593 s = type->ref;
6594 n = s->c;
6595 t1 = pointed_type(type);
6596 size1 = type_size(t1, &align1);
6598 no_oblock = 1;
6599 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
6600 tok == '{') {
6601 if (tok != '{')
6602 tcc_error("character array initializer must be a literal,"
6603 " optionally enclosed in braces");
6604 skip('{');
6605 no_oblock = 0;
6608 /* only parse strings here if correct type (otherwise: handle
6609 them as ((w)char *) expressions */
6610 if ((tok == TOK_LSTR &&
6611 #ifdef TCC_TARGET_PE
6612 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
6613 #else
6614 (t1->t & VT_BTYPE) == VT_INT
6615 #endif
6616 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
6617 len = 0;
6618 while (tok == TOK_STR || tok == TOK_LSTR) {
6619 int cstr_len, ch;
6621 /* compute maximum number of chars wanted */
6622 if (tok == TOK_STR)
6623 cstr_len = tokc.str.size;
6624 else
6625 cstr_len = tokc.str.size / sizeof(nwchar_t);
6626 cstr_len--;
6627 nb = cstr_len;
6628 if (n >= 0 && nb > (n - len))
6629 nb = n - len;
6630 if (!size_only) {
6631 if (cstr_len > nb)
6632 tcc_warning("initializer-string for array is too long");
6633 /* in order to go faster for common case (char
6634 string in global variable, we handle it
6635 specifically */
6636 if (sec && tok == TOK_STR && size1 == 1) {
6637 if (!NODATA_WANTED)
6638 memcpy(sec->data + c + len, tokc.str.data, nb);
6639 } else {
6640 for(i=0;i<nb;i++) {
6641 if (tok == TOK_STR)
6642 ch = ((unsigned char *)tokc.str.data)[i];
6643 else
6644 ch = ((nwchar_t *)tokc.str.data)[i];
6645 vpushi(ch);
6646 init_putv(t1, sec, c + (len + i) * size1);
6650 len += nb;
6651 next();
6653 /* only add trailing zero if enough storage (no
6654 warning in this case since it is standard) */
6655 if (n < 0 || len < n) {
6656 if (!size_only) {
6657 vpushi(0);
6658 init_putv(t1, sec, c + (len * size1));
6660 len++;
6662 len *= size1;
6663 } else {
6664 indexsym.c = 0;
6665 f = &indexsym;
6667 do_init_list:
6668 len = 0;
6669 while (tok != '}' || have_elem) {
6670 len = decl_designator(type, sec, c, &f, size_only, len);
6671 have_elem = 0;
6672 if (type->t & VT_ARRAY) {
6673 ++indexsym.c;
6674 /* special test for multi dimensional arrays (may not
6675 be strictly correct if designators are used at the
6676 same time) */
6677 if (no_oblock && len >= n*size1)
6678 break;
6679 } else {
6680 if (s->type.t == VT_UNION)
6681 f = NULL;
6682 else
6683 f = f->next;
6684 if (no_oblock && f == NULL)
6685 break;
6688 if (tok == '}')
6689 break;
6690 skip(',');
6693 /* put zeros at the end */
6694 if (!size_only && len < n*size1)
6695 init_putz(sec, c + len, n*size1 - len);
6696 if (!no_oblock)
6697 skip('}');
6698 /* patch type size if needed, which happens only for array types */
6699 if (n < 0)
6700 s->c = size1 == 1 ? len : ((len + size1 - 1)/size1);
6701 } else if ((type->t & VT_BTYPE) == VT_STRUCT) {
6702 size1 = 1;
6703 no_oblock = 1;
6704 if (first || tok == '{') {
6705 skip('{');
6706 no_oblock = 0;
6708 s = type->ref;
6709 f = s->next;
6710 n = s->c;
6711 goto do_init_list;
6712 } else if (tok == '{') {
6713 next();
6714 decl_initializer(type, sec, c, first, size_only);
6715 skip('}');
6716 } else if (size_only) {
6717 /* If we supported only ISO C we wouldn't have to accept calling
6718 this on anything than an array size_only==1 (and even then
6719 only on the outermost level, so no recursion would be needed),
6720 because initializing a flex array member isn't supported.
6721 But GNU C supports it, so we need to recurse even into
6722 subfields of structs and arrays when size_only is set. */
6723 /* just skip expression */
6724 skip_or_save_block(NULL);
6725 } else {
6726 if (!have_elem) {
6727 /* This should happen only when we haven't parsed
6728 the init element above for fear of committing a
6729 string constant to memory too early. */
6730 if (tok != TOK_STR && tok != TOK_LSTR)
6731 expect("string constant");
6732 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6734 init_putv(type, sec, c);
6738 /* parse an initializer for type 't' if 'has_init' is non zero, and
6739 allocate space in local or global data space ('r' is either
6740 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
6741 variable 'v' of scope 'scope' is declared before initializers
6742 are parsed. If 'v' is zero, then a reference to the new object
6743 is put in the value stack. If 'has_init' is 2, a special parsing
6744 is done to handle string constants. */
6745 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
6746 int has_init, int v, int scope)
6748 int size, align, addr;
6749 TokenString *init_str = NULL;
6751 Section *sec;
6752 Sym *flexible_array;
6753 Sym *sym = NULL;
6754 int saved_nocode_wanted = nocode_wanted;
6755 #ifdef CONFIG_TCC_BCHECK
6756 int bcheck = tcc_state->do_bounds_check && !NODATA_WANTED;
6757 #endif
6759 if (type->t & VT_STATIC)
6760 nocode_wanted |= NODATA_WANTED ? 0x40000000 : 0x80000000;
6762 flexible_array = NULL;
6763 if ((type->t & VT_BTYPE) == VT_STRUCT) {
6764 Sym *field = type->ref->next;
6765 if (field) {
6766 while (field->next)
6767 field = field->next;
6768 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
6769 flexible_array = field;
6773 size = type_size(type, &align);
6774 /* If unknown size, we must evaluate it before
6775 evaluating initializers because
6776 initializers can generate global data too
6777 (e.g. string pointers or ISOC99 compound
6778 literals). It also simplifies local
6779 initializers handling */
6780 if (size < 0 || (flexible_array && has_init)) {
6781 if (!has_init)
6782 tcc_error("unknown type size");
6783 /* get all init string */
6784 if (has_init == 2) {
6785 init_str = tok_str_alloc();
6786 /* only get strings */
6787 while (tok == TOK_STR || tok == TOK_LSTR) {
6788 tok_str_add_tok(init_str);
6789 next();
6791 tok_str_add(init_str, -1);
6792 tok_str_add(init_str, 0);
6793 } else {
6794 skip_or_save_block(&init_str);
6796 unget_tok(0);
6798 /* compute size */
6799 begin_macro(init_str, 1);
6800 next();
6801 decl_initializer(type, NULL, 0, 1, 1);
6802 /* prepare second initializer parsing */
6803 macro_ptr = init_str->str;
6804 next();
6806 /* if still unknown size, error */
6807 size = type_size(type, &align);
6808 if (size < 0)
6809 tcc_error("unknown type size");
6811 /* If there's a flex member and it was used in the initializer
6812 adjust size. */
6813 if (flexible_array &&
6814 flexible_array->type.ref->c > 0)
6815 size += flexible_array->type.ref->c
6816 * pointed_size(&flexible_array->type);
6817 /* take into account specified alignment if bigger */
6818 if (ad->a.aligned) {
6819 int speca = 1 << (ad->a.aligned - 1);
6820 if (speca > align)
6821 align = speca;
6822 } else if (ad->a.packed) {
6823 align = 1;
6826 if (NODATA_WANTED)
6827 size = 0, align = 1;
6829 if ((r & VT_VALMASK) == VT_LOCAL) {
6830 sec = NULL;
6831 #ifdef CONFIG_TCC_BCHECK
6832 if (bcheck && (type->t & VT_ARRAY)) {
6833 loc--;
6835 #endif
6836 loc = (loc - size) & -align;
6837 addr = loc;
6838 #ifdef CONFIG_TCC_BCHECK
6839 /* handles bounds */
6840 /* XXX: currently, since we do only one pass, we cannot track
6841 '&' operators, so we add only arrays */
6842 if (bcheck && (type->t & VT_ARRAY)) {
6843 addr_t *bounds_ptr;
6844 /* add padding between regions */
6845 loc--;
6846 /* then add local bound info */
6847 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
6848 bounds_ptr[0] = addr;
6849 bounds_ptr[1] = size;
6851 #endif
6852 if (v) {
6853 /* local variable */
6854 #ifdef CONFIG_TCC_ASM
6855 if (ad->asm_label) {
6856 int reg = asm_parse_regvar(ad->asm_label);
6857 if (reg >= 0)
6858 r = (r & ~VT_VALMASK) | reg;
6860 #endif
6861 sym = sym_push(v, type, r, addr);
6862 sym->a = ad->a;
6863 } else {
6864 /* push local reference */
6865 vset(type, r, addr);
6867 } else {
6868 if (v && scope == VT_CONST) {
6869 /* see if the symbol was already defined */
6870 sym = sym_find(v);
6871 if (sym) {
6872 patch_storage(sym, ad, type);
6873 if (sym->type.t & VT_EXTERN) {
6874 /* if the variable is extern, it was not allocated */
6875 sym->type.t &= ~VT_EXTERN;
6876 /* set array size if it was omitted in extern
6877 declaration */
6878 if ((sym->type.t & VT_ARRAY) &&
6879 sym->type.ref->c < 0 &&
6880 type->ref->c >= 0)
6881 sym->type.ref->c = type->ref->c;
6882 } else if (!has_init) {
6883 /* we accept several definitions of the same
6884 global variable. this is tricky, because we
6885 must play with the SHN_COMMON type of the symbol */
6886 /* no init data, we won't add more to the symbol */
6887 goto no_alloc;
6888 } else if (sym->c) {
6889 ElfW(Sym) *esym;
6890 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
6891 if (esym->st_shndx == data_section->sh_num)
6892 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6897 /* allocate symbol in corresponding section */
6898 sec = ad->section;
6899 if (!sec) {
6900 if (has_init)
6901 sec = data_section;
6902 else if (tcc_state->nocommon)
6903 sec = bss_section;
6906 if (sec) {
6907 addr = section_add(sec, size, align);
6908 #ifdef CONFIG_TCC_BCHECK
6909 /* add padding if bound check */
6910 if (bcheck)
6911 section_add(sec, 1, 1);
6912 #endif
6913 } else {
6914 addr = align; /* SHN_COMMON is special, symbol value is align */
6915 sec = common_section;
6918 if (v) {
6919 if (!sym) {
6920 sym = sym_push(v, type, r | VT_SYM, 0);
6921 patch_storage(sym, ad, NULL);
6923 /* Local statics have a scope until now (for
6924 warnings), remove it here. */
6925 sym->sym_scope = 0;
6926 /* update symbol definition */
6927 put_extern_sym(sym, sec, addr, size);
6928 } else {
6929 /* push global reference */
6930 sym = get_sym_ref(type, sec, addr, size);
6931 vpushsym(type, sym);
6932 vtop->r |= r;
6935 #ifdef CONFIG_TCC_BCHECK
6936 /* handles bounds now because the symbol must be defined
6937 before for the relocation */
6938 if (bcheck) {
6939 addr_t *bounds_ptr;
6941 greloca(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR, 0);
6942 /* then add global bound info */
6943 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
6944 bounds_ptr[0] = 0; /* relocated */
6945 bounds_ptr[1] = size;
6947 #endif
6950 if (type->t & VT_VLA) {
6951 int a;
6953 if (NODATA_WANTED)
6954 goto no_alloc;
6956 /* save current stack pointer */
6957 if (vlas_in_scope == 0) {
6958 if (vla_sp_root_loc == -1)
6959 vla_sp_root_loc = (loc -= PTR_SIZE);
6960 gen_vla_sp_save(vla_sp_root_loc);
6963 vla_runtime_type_size(type, &a);
6964 gen_vla_alloc(type, a);
6965 gen_vla_sp_save(addr);
6966 vla_sp_loc = addr;
6967 vlas_in_scope++;
6969 } else if (has_init) {
6970 size_t oldreloc_offset = 0;
6971 if (sec && sec->reloc)
6972 oldreloc_offset = sec->reloc->data_offset;
6973 decl_initializer(type, sec, addr, 1, 0);
6974 if (sec && sec->reloc)
6975 squeeze_multi_relocs(sec, oldreloc_offset);
6976 /* patch flexible array member size back to -1, */
6977 /* for possible subsequent similar declarations */
6978 if (flexible_array)
6979 flexible_array->type.ref->c = -1;
6982 no_alloc:
6983 /* restore parse state if needed */
6984 if (init_str) {
6985 end_macro();
6986 next();
6989 nocode_wanted = saved_nocode_wanted;
6992 /* parse a function defined by symbol 'sym' and generate its code in
6993 'cur_text_section' */
6994 static void gen_function(Sym *sym)
6996 nocode_wanted = 0;
6997 ind = cur_text_section->data_offset;
6998 /* NOTE: we patch the symbol size later */
6999 put_extern_sym(sym, cur_text_section, ind, 0);
7000 funcname = get_tok_str(sym->v, NULL);
7001 func_ind = ind;
7002 /* Initialize VLA state */
7003 vla_sp_loc = -1;
7004 vla_sp_root_loc = -1;
7005 /* put debug symbol */
7006 tcc_debug_funcstart(tcc_state, sym);
7007 /* push a dummy symbol to enable local sym storage */
7008 sym_push2(&local_stack, SYM_FIELD, 0, 0);
7009 local_scope = 1; /* for function parameters */
7010 gfunc_prolog(&sym->type);
7011 local_scope = 0;
7012 rsym = 0;
7013 block(NULL, NULL, 0);
7014 nocode_wanted = 0;
7015 gsym(rsym);
7016 gfunc_epilog();
7017 cur_text_section->data_offset = ind;
7018 label_pop(&global_label_stack, NULL, 0);
7019 /* reset local stack */
7020 local_scope = 0;
7021 sym_pop(&local_stack, NULL, 0);
7022 /* end of function */
7023 /* patch symbol size */
7024 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
7025 ind - func_ind;
7026 tcc_debug_funcend(tcc_state, ind - func_ind);
7027 /* It's better to crash than to generate wrong code */
7028 cur_text_section = NULL;
7029 funcname = ""; /* for safety */
7030 func_vt.t = VT_VOID; /* for safety */
7031 func_var = 0; /* for safety */
7032 ind = 0; /* for safety */
7033 nocode_wanted = 0x80000000;
7034 check_vstack();
7037 static void gen_inline_functions(TCCState *s)
7039 Sym *sym;
7040 int inline_generated, i, ln;
7041 struct InlineFunc *fn;
7043 ln = file->line_num;
7044 /* iterate while inline function are referenced */
7045 do {
7046 inline_generated = 0;
7047 for (i = 0; i < s->nb_inline_fns; ++i) {
7048 fn = s->inline_fns[i];
7049 sym = fn->sym;
7050 if (sym && sym->c) {
7051 /* the function was used: generate its code and
7052 convert it to a normal function */
7053 fn->sym = NULL;
7054 if (file)
7055 pstrcpy(file->filename, sizeof file->filename, fn->filename);
7056 sym->type.t &= ~VT_INLINE;
7058 begin_macro(fn->func_str, 1);
7059 next();
7060 cur_text_section = text_section;
7061 gen_function(sym);
7062 end_macro();
7064 inline_generated = 1;
7067 } while (inline_generated);
7068 file->line_num = ln;
7071 ST_FUNC void free_inline_functions(TCCState *s)
7073 int i;
7074 /* free tokens of unused inline functions */
7075 for (i = 0; i < s->nb_inline_fns; ++i) {
7076 struct InlineFunc *fn = s->inline_fns[i];
7077 if (fn->sym)
7078 tok_str_free(fn->func_str);
7080 dynarray_reset(&s->inline_fns, &s->nb_inline_fns);
7083 /* 'l' is VT_LOCAL or VT_CONST to define default storage type, or VT_CMP
7084 if parsing old style parameter decl list (and FUNC_SYM is set then) */
7085 static int decl0(int l, int is_for_loop_init, Sym *func_sym)
7087 int v, has_init, r;
7088 CType type, btype;
7089 Sym *sym;
7090 AttributeDef ad;
7092 while (1) {
7093 if (!parse_btype(&btype, &ad)) {
7094 if (is_for_loop_init)
7095 return 0;
7096 /* skip redundant ';' if not in old parameter decl scope */
7097 if (tok == ';' && l != VT_CMP) {
7098 next();
7099 continue;
7101 if (l == VT_CONST &&
7102 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
7103 /* global asm block */
7104 asm_global_instr();
7105 continue;
7107 /* special test for old K&R protos without explicit int
7108 type. Only accepted when defining global data */
7109 if (l != VT_CONST || tok < TOK_UIDENT)
7110 break;
7111 btype.t = VT_INT;
7113 if (tok == ';') {
7114 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
7115 int v = btype.ref->v;
7116 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
7117 tcc_warning("unnamed struct/union that defines no instances");
7118 next();
7119 continue;
7121 if (IS_ENUM(btype.t)) {
7122 next();
7123 continue;
7126 while (1) { /* iterate thru each declaration */
7127 type = btype;
7128 /* If the base type itself was an array type of unspecified
7129 size (like in 'typedef int arr[]; arr x = {1};') then
7130 we will overwrite the unknown size by the real one for
7131 this decl. We need to unshare the ref symbol holding
7132 that size. */
7133 if ((type.t & VT_ARRAY) && type.ref->c < 0) {
7134 type.ref = sym_push(SYM_FIELD, &type.ref->type, 0, type.ref->c);
7136 type_decl(&type, &ad, &v, TYPE_DIRECT);
7137 #if 0
7139 char buf[500];
7140 type_to_str(buf, sizeof(buf), &type, get_tok_str(v, NULL));
7141 printf("type = '%s'\n", buf);
7143 #endif
7144 if ((type.t & VT_BTYPE) == VT_FUNC) {
7145 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
7146 tcc_error("function without file scope cannot be static");
7148 /* if old style function prototype, we accept a
7149 declaration list */
7150 sym = type.ref;
7151 if (sym->f.func_type == FUNC_OLD && l == VT_CONST)
7152 decl0(VT_CMP, 0, sym);
7155 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
7156 ad.asm_label = asm_label_instr();
7157 /* parse one last attribute list, after asm label */
7158 parse_attribute(&ad);
7159 if (tok == '{')
7160 expect(";");
7163 #ifdef TCC_TARGET_PE
7164 if (ad.a.dllimport || ad.a.dllexport) {
7165 if (type.t & (VT_STATIC|VT_TYPEDEF))
7166 tcc_error("cannot have dll linkage with static or typedef");
7167 if (ad.a.dllimport) {
7168 if ((type.t & VT_BTYPE) == VT_FUNC)
7169 ad.a.dllimport = 0;
7170 else
7171 type.t |= VT_EXTERN;
7174 #endif
7175 if (tok == '{') {
7176 if (l != VT_CONST)
7177 tcc_error("cannot use local functions");
7178 if ((type.t & VT_BTYPE) != VT_FUNC)
7179 expect("function definition");
7181 /* reject abstract declarators in function definition
7182 make old style params without decl have int type */
7183 sym = type.ref;
7184 while ((sym = sym->next) != NULL) {
7185 if (!(sym->v & ~SYM_FIELD))
7186 expect("identifier");
7187 if (sym->type.t == VT_VOID)
7188 sym->type = int_type;
7191 /* XXX: cannot do better now: convert extern line to static inline */
7192 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
7193 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
7195 sym = sym_find(v);
7196 if (sym) {
7197 Sym *ref;
7198 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
7199 goto func_error1;
7201 ref = sym->type.ref;
7203 /* use func_call from prototype if not defined */
7204 if (ref->f.func_call != FUNC_CDECL
7205 && type.ref->f.func_call == FUNC_CDECL)
7206 type.ref->f.func_call = ref->f.func_call;
7208 /* use static from prototype */
7209 if (sym->type.t & VT_STATIC)
7210 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
7212 /* If the definition has no visibility use the
7213 one from prototype. */
7214 if (!type.ref->a.visibility)
7215 type.ref->a.visibility = ref->a.visibility;
7216 /* apply other storage attributes from prototype */
7217 type.ref->a.dllexport |= ref->a.dllexport;
7218 type.ref->a.weak |= ref->a.weak;
7220 if (!is_compatible_types(&sym->type, &type)) {
7221 func_error1:
7222 tcc_error("incompatible types for redefinition of '%s'",
7223 get_tok_str(v, NULL));
7225 if (ref->f.func_body)
7226 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
7227 /* if symbol is already defined, then put complete type */
7228 sym->type = type;
7230 } else {
7231 /* put function symbol */
7232 sym = global_identifier_push(v, type.t, 0);
7233 sym->type.ref = type.ref;
7236 sym->type.ref->f.func_body = 1;
7237 sym->r = VT_SYM | VT_CONST;
7238 patch_storage(sym, &ad, NULL);
7240 /* static inline functions are just recorded as a kind
7241 of macro. Their code will be emitted at the end of
7242 the compilation unit only if they are used */
7243 if ((type.t & (VT_INLINE | VT_STATIC)) ==
7244 (VT_INLINE | VT_STATIC)) {
7245 struct InlineFunc *fn;
7246 const char *filename;
7248 filename = file ? file->filename : "";
7249 fn = tcc_malloc(sizeof *fn + strlen(filename));
7250 strcpy(fn->filename, filename);
7251 fn->sym = sym;
7252 skip_or_save_block(&fn->func_str);
7253 dynarray_add(&tcc_state->inline_fns,
7254 &tcc_state->nb_inline_fns, fn);
7255 } else {
7256 /* compute text section */
7257 cur_text_section = ad.section;
7258 if (!cur_text_section)
7259 cur_text_section = text_section;
7260 gen_function(sym);
7262 break;
7263 } else {
7264 if (l == VT_CMP) {
7265 /* find parameter in function parameter list */
7266 for (sym = func_sym->next; sym; sym = sym->next)
7267 if ((sym->v & ~SYM_FIELD) == v)
7268 goto found;
7269 tcc_error("declaration for parameter '%s' but no such parameter",
7270 get_tok_str(v, NULL));
7271 found:
7272 if (type.t & VT_STORAGE) /* 'register' is okay */
7273 tcc_error("storage class specified for '%s'",
7274 get_tok_str(v, NULL));
7275 if (sym->type.t != VT_VOID)
7276 tcc_error("redefinition of parameter '%s'",
7277 get_tok_str(v, NULL));
7278 convert_parameter_type(&type);
7279 sym->type = type;
7280 } else if (type.t & VT_TYPEDEF) {
7281 /* save typedefed type */
7282 /* XXX: test storage specifiers ? */
7283 sym = sym_find(v);
7284 if (sym && sym->sym_scope == local_scope) {
7285 if (!is_compatible_types(&sym->type, &type)
7286 || !(sym->type.t & VT_TYPEDEF))
7287 tcc_error("incompatible redefinition of '%s'",
7288 get_tok_str(v, NULL));
7289 sym->type = type;
7290 } else {
7291 sym = sym_push(v, &type, 0, 0);
7293 sym->a = ad.a;
7294 sym->f = ad.f;
7295 } else {
7296 r = 0;
7297 if ((type.t & VT_BTYPE) == VT_FUNC) {
7298 /* external function definition */
7299 /* specific case for func_call attribute */
7300 type.ref->f = ad.f;
7301 } else if (!(type.t & VT_ARRAY)) {
7302 /* not lvalue if array */
7303 r |= lvalue_type(type.t);
7305 has_init = (tok == '=');
7306 if (has_init && (type.t & VT_VLA))
7307 tcc_error("variable length array cannot be initialized");
7308 if (((type.t & VT_EXTERN) && (!has_init || l != VT_CONST)) ||
7309 ((type.t & VT_BTYPE) == VT_FUNC) ||
7310 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
7311 !has_init && l == VT_CONST && type.ref->c < 0)) {
7312 /* external variable or function */
7313 /* NOTE: as GCC, uninitialized global static
7314 arrays of null size are considered as
7315 extern */
7316 sym = external_sym(v, &type, r, &ad);
7317 if (ad.alias_target) {
7318 Section tsec;
7319 ElfW(Sym) *esym;
7320 Sym *alias_target;
7321 alias_target = sym_find(ad.alias_target);
7322 if (!alias_target || !alias_target->c)
7323 tcc_error("unsupported forward __alias__ attribute");
7324 esym = &((ElfW(Sym) *)symtab_section->data)[alias_target->c];
7325 tsec.sh_num = esym->st_shndx;
7326 /* Local statics have a scope until now (for
7327 warnings), remove it here. */
7328 sym->sym_scope = 0;
7329 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
7331 } else {
7332 if (type.t & VT_STATIC)
7333 r |= VT_CONST;
7334 else
7335 r |= l;
7336 if (has_init)
7337 next();
7338 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
7341 if (tok != ',') {
7342 if (is_for_loop_init)
7343 return 1;
7344 skip(';');
7345 break;
7347 next();
7349 ad.a.aligned = 0;
7352 return 0;
7355 static void decl(int l)
7357 decl0(l, 0, NULL);
7360 /* ------------------------------------------------------------------------- */