ncc: don't cast the return value for void functions
[neatcc.git] / ncc.c
bloba7486745bfc55c5feebcc70e738fd2bce0bdc172
1 /*
2 * neatcc - a small and simple C compiler
4 * Copyright (C) 2010-2011 Ali Gholami Rudi
6 * This file is released under GNU GPL version 2.
7 */
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <stdio.h>
13 #include <sys/stat.h>
14 #include <sys/types.h>
15 #include "gen.h"
16 #include "tok.h"
17 #include "out.h"
19 #define MAXLOCALS (1 << 10)
20 #define MAXGLOBALS (1 << 10)
21 #define MAXARGS (1 << 5)
23 #define TYPE_BT(t) ((t)->ptr ? LONGSZ : (t)->bt)
24 #define TYPE_SZ(t) ((t)->ptr ? LONGSZ : (t)->bt & BT_SZMASK)
26 #define T_ARRAY 0x01
27 #define T_STRUCT 0x02
28 #define T_FUNC 0x04
30 #define F_INIT 0x01
31 #define F_STATIC 0x02
32 #define F_EXTERN 0x04
34 struct type {
35 unsigned bt;
36 unsigned flags;
37 int ptr;
38 int id; /* for structs, functions and arrays */
39 int addr; /* the address is passed to gen.c; deref for value */
42 /* type stack */
43 static struct type ts[MAXTMP];
44 static int nts;
46 static void ts_push_bt(unsigned bt)
48 ts[nts].ptr = 0;
49 ts[nts].flags = 0;
50 ts[nts].addr = 0;
51 ts[nts++].bt = bt;
54 static void ts_push(struct type *t)
56 struct type *d = &ts[nts++];
57 memcpy(d, t, sizeof(*t));
60 static void ts_push_addr(struct type *t)
62 ts_push(t);
63 ts[nts - 1].addr = 1;
66 static void ts_pop(struct type *type)
68 nts--;
69 if (type)
70 *type = ts[nts];
73 void err(char *msg)
75 char err[1 << 7];
76 int len = cpp_loc(err, tok_addr());
77 strcpy(err + len, msg);
78 die(err);
81 struct name {
82 char name[NAMELEN];
83 char elfname[NAMELEN]; /* local elf name for static variables in function */
84 struct type type;
85 long addr; /* local stack offset, global data addr, struct offset */
88 static struct name locals[MAXLOCALS];
89 static int nlocals;
90 static struct name globals[MAXGLOBALS];
91 static int nglobals;
93 static void local_add(struct name *name)
95 if (nlocals >= MAXLOCALS)
96 err("nomem: MAXLOCALS reached!\n");
97 memcpy(&locals[nlocals++], name, sizeof(*name));
100 static int global_find(char *name)
102 int i;
103 for (i = 0; i < nglobals; i++)
104 if (!strcmp(name, globals[i].name))
105 return i;
106 return -1;
109 static void global_add(struct name *name)
111 int found = global_find(name->name);
112 int i = found == -1 ? nglobals++ : found;
113 if (nglobals >= MAXGLOBALS)
114 err("nomem: MAXGLOBALS reached!\n");
115 memcpy(&globals[i], name, sizeof(*name));
118 #define MAXENUMS (1 << 10)
120 static struct enumval {
121 char name[NAMELEN];
122 int n;
123 } enums[MAXENUMS];
124 static int nenums;
126 static void enum_add(char *name, int val)
128 struct enumval *ev = &enums[nenums++];
129 if (nenums >= MAXENUMS)
130 err("nomem: MAXENUMS reached!\n");
131 strcpy(ev->name, name);
132 ev->n = val;
135 static int enum_find(int *val, char *name)
137 int i;
138 for (i = nenums - 1; i >= 0; --i)
139 if (!strcmp(name, enums[i].name)) {
140 *val = enums[i].n;
141 return 0;
143 return 1;
146 #define MAXTYPEDEFS (1 << 10)
148 static struct typdefinfo {
149 char name[NAMELEN];
150 struct type type;
151 } typedefs[MAXTYPEDEFS];
152 static int ntypedefs;
154 static void typedef_add(char *name, struct type *type)
156 struct typdefinfo *ti = &typedefs[ntypedefs++];
157 if (ntypedefs >= MAXTYPEDEFS)
158 err("nomem: MAXTYPEDEFS reached!\n");
159 strcpy(ti->name, name);
160 memcpy(&ti->type, type, sizeof(*type));
163 static int typedef_find(char *name)
165 int i;
166 for (i = ntypedefs - 1; i >= 0; --i)
167 if (!strcmp(name, typedefs[i].name))
168 return i;
169 return -1;
172 #define MAXARRAYS (1 << 10)
174 static struct array {
175 struct type type;
176 int n;
177 } arrays[MAXARRAYS];
178 static int narrays;
180 static int array_add(struct type *type, int n)
182 struct array *a = &arrays[narrays++];
183 if (narrays >= MAXARRAYS)
184 err("nomem: MAXARRAYS reached!\n");
185 memcpy(&a->type, type, sizeof(*type));
186 a->n = n;
187 return a - arrays;
190 static void array2ptr(struct type *t)
192 if (t->flags & T_ARRAY && !t->ptr) {
193 memcpy(t, &arrays[t->id].type, sizeof(*t));
194 t->ptr++;
198 #define MAXSTRUCTS (1 << 10)
199 #define MAXFIELDS (1 << 7)
201 static struct structinfo {
202 char name[NAMELEN];
203 struct name fields[MAXFIELDS];
204 int nfields;
205 int isunion;
206 int size;
207 } structs[MAXSTRUCTS];
208 static int nstructs;
210 static int struct_find(char *name, int isunion)
212 int i;
213 for (i = nstructs - 1; i >= 0; --i)
214 if (*structs[i].name && !strcmp(name, structs[i].name) &&
215 structs[i].isunion == isunion)
216 return i;
217 i = nstructs++;
218 if (nstructs >= MAXSTRUCTS)
219 err("nomem: MAXTYPES reached!\n");
220 memset(&structs[i], 0, sizeof(structs[i]));
221 strcpy(structs[i].name, name);
222 structs[i].isunion = isunion;
223 return i;
226 static struct name *struct_field(int id, char *name)
228 struct structinfo *si = &structs[id];
229 int i;
230 for (i = 0; i < si->nfields; i++)
231 if (!strcmp(name, si->fields[i].name))
232 return &si->fields[i];
233 err("field not found\n");
236 #define MAXBREAK (1 << 7)
238 static long breaks[MAXBREAK];
239 static int nbreaks;
240 static long continues[MAXBREAK];
241 static int ncontinues;
243 static void break_fill(long addr, int till)
245 int i;
246 for (i = till; i < nbreaks; i++)
247 o_filljmp2(breaks[i], addr);
248 nbreaks = till;
251 static void continue_fill(long addr, int till)
253 int i;
254 for (i = till; i < ncontinues; i++)
255 o_filljmp2(continues[i], addr);
256 ncontinues = till;
259 static int type_totsz(struct type *t)
261 if (t->ptr)
262 return LONGSZ;
263 if (t->flags & T_ARRAY)
264 return arrays[t->id].n * type_totsz(&arrays[t->id].type);
265 return t->flags & T_STRUCT ? structs[t->id].size : BT_SZ(t->bt);
268 static unsigned type_szde(struct type *t)
270 struct type de = *t;
271 array2ptr(&de);
272 de.ptr--;
273 return type_totsz(&de);
276 static void ts_de(int deref)
278 struct type *t = &ts[nts - 1];
279 if (deref && t->addr && (!(t->flags & T_ARRAY) || (t->ptr)))
280 o_deref(TYPE_BT(t));
281 t->addr = 0;
284 static void ts_pop_de(struct type *t)
286 struct type de;
287 if (!t)
288 t = &de;
289 ts_pop(t);
290 array2ptr(t);
291 if (t->addr && !(t->flags & T_FUNC))
292 o_deref(TYPE_BT(t));
293 t->addr = 0;
296 static void ts_pop_de2(struct type *t1, struct type *t2)
298 ts_pop_de(t1);
299 o_tmpswap();
300 ts_pop_de(t2);
301 o_tmpswap();
304 static int tok_jmp(int tok)
306 if (tok_see() != tok)
307 return 1;
308 tok_get();
309 return 0;
312 static void tok_expect(int tok)
314 if (tok_get() != tok)
315 err("syntax error\n");
318 static unsigned bt_op(unsigned bt1, unsigned bt2)
320 unsigned s1 = BT_SZ(bt1);
321 unsigned s2 = BT_SZ(bt2);
322 return (bt1 | bt2) & BT_SIGNED | (s1 > s2 ? s1 : s2);
325 static void ts_binop(int op)
327 struct type t1, t2;
328 ts_pop_de2(&t1, &t2);
329 o_bop(op);
330 ts_push_bt(bt_op(TYPE_BT(&t1), TYPE_BT(&t2)));
333 static void ts_addop(int op)
335 struct type t1, t2;
336 ts_pop_de2(&t1, &t2);
337 if (!t1.ptr && !t2.ptr) {
338 o_bop(op);
339 ts_push_bt(bt_op(TYPE_BT(&t1), TYPE_BT(&t2)));
340 return;
342 if (t1.ptr && !t2.ptr)
343 o_tmpswap();
344 if (!t1.ptr && t2.ptr)
345 if (type_szde(&t2) > 1) {
346 o_num(type_szde(&t2));
347 o_bop(O_MUL);
349 if (t1.ptr && !t2.ptr)
350 o_tmpswap();
351 o_bop(op);
352 if (t1.ptr && t2.ptr) {
353 int sz = type_szde(&t1);
354 if (sz > 1) {
355 o_num(sz);
356 o_bop(O_DIV);
358 ts_push_bt(4 | BT_SIGNED);
359 } else {
360 ts_push(t1.ptr ? &t1 : &t2);
364 #define ALIGN(x, a) (((x) + (a) - 1) & ~((a) - 1))
365 #define MIN(a, b) ((a) < (b) ? (a) : (b))
367 static int type_alignment(struct type *t)
369 if (t->flags & T_ARRAY && !t->ptr)
370 return type_alignment(&arrays[t->id].type);
371 if (t->flags & T_STRUCT && !t->ptr)
372 return type_alignment(&structs[t->id].fields[0].type);
373 return MIN(LONGSZ, type_totsz(t));
376 static void structdef(void *data, struct name *name, unsigned flags)
378 struct structinfo *si = data;
379 if (si->isunion) {
380 name->addr = 0;
381 if (si->size < type_totsz(&name->type))
382 si->size = type_totsz(&name->type);
383 } else {
384 struct type *t = &name->type;
385 int alignment = type_alignment(t);
386 if (t->flags & T_ARRAY && !t->ptr)
387 alignment = MIN(LONGSZ, type_totsz(&arrays[t->id].type));
388 si->size = ALIGN(si->size, alignment);
389 name->addr = si->size;
390 si->size += type_totsz(&name->type);
392 memcpy(&si->fields[si->nfields++], name, sizeof(*name));
395 static int readdefs(void (*def)(void *, struct name *, unsigned f), void *data);
397 static int struct_create(char *name, int isunion)
399 int id = struct_find(name, isunion);
400 struct structinfo *si = &structs[id];
401 tok_expect('{');
402 while (tok_jmp('}')) {
403 readdefs(structdef, si);
404 tok_expect(';');
406 return id;
409 static void readexpr(void);
411 static void enum_create(void)
413 long n = 0;
414 tok_expect('{');
415 while (tok_jmp('}')) {
416 char name[NAMELEN];
417 tok_expect(TOK_NAME);
418 strcpy(name, tok_id());
419 if (tok_see() == '=') {
420 tok_get();
421 readexpr();
422 ts_pop(NULL);
423 if (o_popnum(&n))
424 err("const expr expected!\n");
426 enum_add(name, n++);
427 tok_jmp(',');
431 static int basetype(struct type *type, unsigned *flags)
433 int sign = 1;
434 int size = 4;
435 int done = 0;
436 int i = 0;
437 int isunion;
438 char name[NAMELEN] = "";
439 *flags = 0;
440 type->flags = 0;
441 type->ptr = 0;
442 type->addr = 0;
443 while (!done) {
444 switch (tok_see()) {
445 case TOK_STATIC:
446 *flags |= F_STATIC;
447 break;
448 case TOK_EXTERN:
449 *flags |= F_EXTERN;
450 break;
451 case TOK_VOID:
452 sign = 0;
453 size = 0;
454 done = 1;
455 break;
456 case TOK_INT:
457 done = 1;
458 break;
459 case TOK_CHAR:
460 size = 1;
461 done = 1;
462 break;
463 case TOK_SHORT:
464 size = 2;
465 break;
466 case TOK_LONG:
467 size = LONGSZ;
468 break;
469 case TOK_SIGNED:
470 break;
471 case TOK_UNSIGNED:
472 sign = 0;
473 break;
474 case TOK_UNION:
475 case TOK_STRUCT:
476 isunion = tok_get() == TOK_UNION;
477 if (!tok_jmp(TOK_NAME))
478 strcpy(name, tok_id());
479 if (tok_see() == '{')
480 type->id = struct_create(name, isunion);
481 else
482 type->id = struct_find(name, isunion);
483 type->flags |= T_STRUCT;
484 type->bt = LONGSZ;
485 return 0;
486 case TOK_ENUM:
487 tok_get();
488 tok_jmp(TOK_NAME);
489 if (tok_see() == '{')
490 enum_create();
491 type->bt = 4 | BT_SIGNED;
492 return 0;
493 default:
494 if (tok_see() == TOK_NAME) {
495 int id = typedef_find(tok_id());
496 if (id != -1) {
497 tok_get();
498 memcpy(type, &typedefs[id].type,
499 sizeof(*type));
500 return 0;
503 if (!i)
504 return 1;
505 done = 1;
506 continue;
508 i++;
509 tok_get();
511 type->bt = size | (sign ? BT_SIGNED : 0);
512 return 0;
515 static int readname(struct type *main, char *name,
516 struct type *base, unsigned flags);
518 static int readtype(struct type *type)
520 return readname(type, NULL, NULL, 0);
523 static void readptrs(struct type *type)
525 while (!tok_jmp('*')) {
526 type->ptr++;
527 if (!type->bt)
528 type->bt = 1;
532 /* used to differenciate labels from case and cond exprs */
533 static int ncexpr;
534 static int caseexpr;
536 static void readpre(void);
538 static char *tmp_str(char *buf, int len)
540 static char name[NAMELEN];
541 static int id;
542 void *dat;
543 sprintf(name, "__neatcc.s%d", id++);
544 dat = dat_dat(name, len, 0);
545 memcpy(dat, buf, len);
546 return name;
549 static void readprimary(void)
551 int i;
552 if (!tok_jmp(TOK_NUM)) {
553 long n;
554 int bt = tok_num(&n);
555 ts_push_bt(bt);
556 o_num(n);
557 return;
559 if (!tok_jmp(TOK_STR)) {
560 struct type t;
561 char buf[BUFSIZE];
562 int len;
563 t.bt = 1 | BT_SIGNED;
564 t.ptr = 1;
565 t.addr = 0;
566 t.flags = 0;
567 ts_push(&t);
568 len = tok_str(buf);
569 o_sym(tmp_str(buf, len));
570 return;
572 if (!tok_jmp(TOK_NAME)) {
573 struct name unkn = {""};
574 char *name = unkn.name;
575 int n;
576 strcpy(name, tok_id());
577 /* don't search for labels here */
578 if (!ncexpr && !caseexpr && tok_see() == ':')
579 return;
580 for (i = nlocals - 1; i >= 0; --i) {
581 struct type *t = &locals[i].type;
582 if (!strcmp(locals[i].name, name)) {
583 o_local(locals[i].addr);
584 ts_push_addr(t);
585 return;
588 if ((n = global_find(name)) != -1) {
589 struct name *g = &globals[n];
590 struct type *t = &g->type;
591 char *elfname = *g->elfname ? g->elfname : g->name;
592 o_sym(elfname);
593 ts_push_addr(t);
594 return;
596 if (!enum_find(&n, name)) {
597 ts_push_bt(4 | BT_SIGNED);
598 o_num(n);
599 return;
601 if (tok_see() != '(')
602 err("unknown symbol\n");
603 global_add(&unkn);
604 ts_push_bt(LONGSZ);
605 o_sym(unkn.name);
606 return;
608 if (!tok_jmp('(')) {
609 struct type t;
610 if (!readtype(&t)) {
611 struct type o;
612 tok_expect(')');
613 readpre();
614 ts_pop_de(&o);
615 ts_push(&t);
616 if (!t.ptr || !o.ptr)
617 o_cast(TYPE_BT(&t));
618 } else {
619 readexpr();
620 tok_expect(')');
622 return;
626 static void arrayderef(void)
628 struct type t;
629 int sz;
630 ts_pop_de(NULL);
631 ts_pop(&t);
632 if (!(t.flags & T_ARRAY) && t.addr) {
633 o_tmpswap();
634 o_deref(TYPE_BT(&t));
635 o_tmpswap();
637 array2ptr(&t);
638 t.ptr--;
639 sz = type_totsz(&t);
640 t.addr = 1;
641 if (sz > 1) {
642 o_num(sz);
643 o_bop(O_MUL);
645 o_bop(O_ADD);
646 ts_push(&t);
649 static void inc_post(int op)
651 struct type t = ts[nts - 1];
652 /* pushing the value before inc */
653 o_tmpcopy();
654 ts_de(1);
655 o_load();
656 o_tmpswap();
658 /* increment by 1 or pointer size */
659 o_tmpcopy();
660 ts_push(&t);
661 ts_pop_de(&t);
662 o_num(t.ptr > 0 ? type_szde(&t) : 1);
663 o_bop(op);
665 /* assign back */
666 o_assign(TYPE_BT(&t));
667 o_tmpdrop(1);
670 static void readfield(void)
672 struct name *field;
673 struct type t;
674 tok_expect(TOK_NAME);
675 ts_pop(&t);
676 array2ptr(&t);
677 field = struct_field(t.id, tok_id());
678 if (field->addr) {
679 o_num(field->addr);
680 o_bop(O_ADD);
682 ts_push_addr(&field->type);
685 #define MAXFUNCS (1 << 10)
687 static struct funcinfo {
688 struct type args[MAXFIELDS];
689 struct type ret;
690 int nargs;
691 } funcs[MAXFUNCS];
692 static int nfuncs;
694 static int func_create(struct type *ret, struct name *args, int nargs)
696 struct funcinfo *fi = &funcs[nfuncs++];
697 int i;
698 if (nfuncs >= MAXFUNCS)
699 err("nomem: MAXFUNCS reached!\n");
700 memcpy(&fi->ret, ret, sizeof(*ret));
701 for (i = 0; i < nargs; i++)
702 memcpy(&fi->args[i], &args[i].type, sizeof(*ret));
703 fi->nargs = nargs;
704 return fi - funcs;
707 static void readcall(void)
709 struct type t;
710 struct funcinfo *fi;
711 int argc = 0;
712 ts_pop(&t);
713 if (t.flags & T_FUNC && t.ptr > 0)
714 o_deref(LONGSZ);
715 fi = t.flags & T_FUNC ? &funcs[t.id] : NULL;
716 if (tok_see() != ')') {
717 do {
718 readexpr();
719 ts_pop_de(NULL);
720 argc++;
721 } while (!tok_jmp(','));
723 tok_expect(')');
724 o_call(argc, fi ? TYPE_BT(&fi->ret) : 4 | BT_SIGNED);
725 if (fi) {
726 if (TYPE_BT(&fi->ret))
727 o_cast(TYPE_BT(&fi->ret));
728 ts_push(&fi->ret);
729 } else {
730 ts_push_bt(4 | BT_SIGNED);
734 static void readpost(void)
736 readprimary();
737 while (1) {
738 if (!tok_jmp('[')) {
739 readexpr();
740 tok_expect(']');
741 arrayderef();
742 continue;
744 if (!tok_jmp('(')) {
745 readcall();
746 continue;
748 if (!tok_jmp(TOK2("++"))) {
749 inc_post(O_ADD);
750 continue;
752 if (!tok_jmp(TOK2("--"))) {
753 inc_post(O_SUB);
754 continue;
756 if (!tok_jmp('.')) {
757 readfield();
758 continue;
760 if (!tok_jmp(TOK2("->"))) {
761 ts_de(1);
762 readfield();
763 continue;
765 break;
769 static void inc_pre(int op)
771 struct type t;
772 readpre();
773 /* copy the destination */
774 o_tmpcopy();
775 ts_push(&ts[nts - 1]);
776 /* increment by 1 or pointer size */
777 ts_pop_de(&t);
778 o_num(t.ptr > 0 ? type_szde(&t) : 1);
779 o_bop(op);
780 /* assign the result */
781 o_assign(TYPE_BT(&t));
782 ts_de(0);
785 static void readpre(void)
787 if (!tok_jmp('&')) {
788 struct type type;
789 readpre();
790 ts_pop(&type);
791 if (!type.addr)
792 die("cannot use the address\n");
793 type.ptr++;
794 type.addr = 0;
795 ts_push(&type);
796 return;
798 if (!tok_jmp('*')) {
799 struct type t;
800 readpre();
801 ts_pop(&t);
802 array2ptr(&t);
803 if (!t.ptr)
804 err("dereferencing non-pointer\n");
805 if (t.addr)
806 o_deref(TYPE_BT(&t));
807 t.ptr--;
808 t.addr = 1;
809 ts_push(&t);
810 return;
812 if (!tok_jmp('!')) {
813 readpre();
814 ts_pop_de(NULL);
815 o_uop(O_LNOT);
816 ts_push_bt(4 | BT_SIGNED);
817 return;
819 if (!tok_jmp('-')) {
820 readpre();
821 ts_de(1);
822 o_uop(O_NEG);
823 return;
825 if (!tok_jmp('~')) {
826 readpre();
827 ts_de(1);
828 o_uop(O_NOT);
829 return;
831 if (!tok_jmp(TOK2("++"))) {
832 inc_pre(O_ADD);
833 return;
835 if (!tok_jmp(TOK2("--"))) {
836 inc_pre(O_SUB);
837 return;
839 if (!tok_jmp(TOK_SIZEOF)) {
840 struct type t;
841 int op = !tok_jmp('(');
842 if (readtype(&t)) {
843 int nogen = !o_nogen();
844 readexpr();
845 if (nogen)
846 o_dogen();
847 ts_pop(&t);
848 o_tmpdrop(1);
850 ts_push_bt(4);
851 o_num(type_totsz(&t));
852 if (op)
853 tok_expect(')');
854 return;
856 readpost();
859 static void readmul(void)
861 readpre();
862 while (1) {
863 if (!tok_jmp('*')) {
864 readpre();
865 ts_binop(O_MUL);
866 continue;
868 if (!tok_jmp('/')) {
869 readpre();
870 ts_binop(O_DIV);
871 continue;
873 if (!tok_jmp('%')) {
874 readpre();
875 ts_binop(O_MOD);
876 continue;
878 break;
882 static void readadd(void)
884 readmul();
885 while (1) {
886 if (!tok_jmp('+')) {
887 readmul();
888 ts_addop(O_ADD);
889 continue;
891 if (!tok_jmp('-')) {
892 readmul();
893 ts_addop(O_SUB);
894 continue;
896 break;
900 static void shift(int uop, int sop)
902 struct type t;
903 readadd();
904 ts_pop_de2(NULL, &t);
905 o_bop(BT_SIGNED & TYPE_BT(&t) ? sop : uop);
906 ts_push_bt(TYPE_BT(&t));
909 static void readshift(void)
911 readadd();
912 while (1) {
913 if (!tok_jmp(TOK2("<<"))) {
914 shift(O_SHL, O_SHL);
915 continue;
917 if (!tok_jmp(TOK2(">>"))) {
918 shift(O_SHR, O_ASR);
919 continue;
921 break;
925 static void cmp(int op)
927 readshift();
928 ts_pop_de2(NULL, NULL);
929 o_bop(op);
930 ts_push_bt(4 | BT_SIGNED);
933 static void readcmp(void)
935 readshift();
936 while (1) {
937 if (!tok_jmp('<')) {
938 cmp(O_LT);
939 continue;
941 if (!tok_jmp('>')) {
942 cmp(O_GT);
943 continue;
945 if (!tok_jmp(TOK2("<="))) {
946 cmp(O_LE);
947 continue;
949 if (!tok_jmp(TOK2(">="))) {
950 cmp(O_GE);
951 continue;
953 break;
957 static void eq(int op)
959 readcmp();
960 ts_pop_de2(NULL, NULL);
961 o_bop(op);
962 ts_push_bt(4 | BT_SIGNED);
965 static void readeq(void)
967 readcmp();
968 while (1) {
969 if (!tok_jmp(TOK2("=="))) {
970 eq(O_EQ);
971 continue;
973 if (!tok_jmp(TOK2("!="))) {
974 eq(O_NEQ);
975 continue;
977 break;
981 static void readbitand(void)
983 readeq();
984 while (!tok_jmp('&')) {
985 readeq();
986 ts_binop(O_AND);
990 static void readxor(void)
992 readbitand();
993 while (!tok_jmp('^')) {
994 readbitand();
995 ts_binop(O_XOR);
999 static void readbitor(void)
1001 readxor();
1002 while (!tok_jmp('|')) {
1003 readxor();
1004 ts_binop(O_OR);
1008 #define MAXCOND (1 << 7)
1010 static void readand(void)
1012 long conds[MAXCOND];
1013 int nconds = 0;
1014 long passed;
1015 int i;
1016 readbitor();
1017 if (tok_see() != TOK2("&&"))
1018 return;
1019 o_fork();
1020 ts_pop_de(NULL);
1021 conds[nconds++] = o_jz(0);
1022 while (!tok_jmp(TOK2("&&"))) {
1023 readbitor();
1024 ts_pop_de(NULL);
1025 conds[nconds++] = o_jz(0);
1027 o_num(1);
1028 o_forkpush();
1029 passed = o_jmp(0);
1030 for (i = 0; i < nconds; i++)
1031 o_filljmp(conds[i]);
1032 o_num(0);
1033 o_forkpush();
1034 o_forkjoin();
1035 o_filljmp(passed);
1036 ts_push_bt(4 | BT_SIGNED);
1039 static void reador(void)
1041 long conds[MAXCOND];
1042 int nconds = 0;
1043 long failed;
1044 int i;
1045 readand();
1046 if (tok_see() != TOK2("||"))
1047 return;
1048 o_fork();
1049 ts_pop_de(NULL);
1050 conds[nconds++] = o_jnz(0);
1051 while (!tok_jmp(TOK2("||"))) {
1052 readand();
1053 ts_pop_de(NULL);
1054 conds[nconds++] = o_jnz(0);
1056 o_num(0);
1057 o_forkpush();
1058 failed = o_jmp(0);
1059 for (i = 0; i < nconds; i++)
1060 o_filljmp(conds[i]);
1061 o_num(1);
1062 o_forkpush();
1063 o_forkjoin();
1064 o_filljmp(failed);
1065 ts_push_bt(4 | BT_SIGNED);
1068 static int readcexpr_const(void)
1070 long c;
1071 int nogen;
1072 if (o_popnum(&c))
1073 return -1;
1074 if (!c)
1075 nogen = !o_nogen();
1076 reador();
1077 ts_pop(NULL);
1078 tok_expect(':');
1079 if (c) {
1080 nogen = !o_nogen();
1081 } else {
1082 if (nogen)
1083 o_dogen();
1084 o_tmpdrop(1);
1086 reador();
1087 if (c) {
1088 if (nogen)
1089 o_dogen();
1090 o_tmpdrop(1);
1092 return 0;
1095 static void readcexpr(void)
1097 long l1, l2;
1098 reador();
1099 if (tok_jmp('?'))
1100 return;
1101 ncexpr++;
1102 ts_pop_de(NULL);
1103 o_fork();
1104 if (readcexpr_const()) {
1105 l1 = o_jz(0);
1106 reador();
1107 o_forkpush();
1108 l2 = o_jmp(0);
1109 ts_pop(NULL);
1111 tok_expect(':');
1112 o_filljmp(l1);
1113 reador();
1114 o_forkpush();
1115 o_forkjoin();
1116 o_filljmp(l2);
1118 ncexpr--;
1121 static void opassign(int op, int ptrop)
1123 struct type t = ts[nts - 1];
1124 o_tmpcopy();
1125 ts_push(&t);
1126 readexpr();
1127 ts_addop(op);
1128 o_assign(TYPE_BT(&ts[nts - 1]));
1129 ts_pop(NULL);
1130 ts_de(0);
1133 static void doassign(void)
1135 struct type t = ts[nts - 1];
1136 if (!t.ptr && t.flags & T_STRUCT) {
1137 ts_pop(NULL);
1138 o_num(type_totsz(&t));
1139 o_memcpy();
1140 } else {
1141 ts_pop_de(NULL);
1142 o_assign(TYPE_BT(&ts[nts - 1]));
1143 ts_de(0);
1147 static void readexpr(void)
1149 readcexpr();
1150 if (!tok_jmp('=')) {
1151 readexpr();
1152 doassign();
1153 return;
1155 if (!tok_jmp(TOK2("+="))) {
1156 opassign(O_ADD, 1);
1157 return;
1159 if (!tok_jmp(TOK2("-="))) {
1160 opassign(O_SUB, 1);
1161 return;
1163 if (!tok_jmp(TOK2("*="))) {
1164 opassign(O_MUL, 0);
1165 return;
1167 if (!tok_jmp(TOK2("/="))) {
1168 opassign(O_DIV, 0);
1169 return;
1171 if (!tok_jmp(TOK2("%="))) {
1172 opassign(O_MOD, 0);
1173 return;
1175 if (!tok_jmp(TOK3("<<="))) {
1176 opassign(O_SHL, 0);
1177 return;
1179 if (!tok_jmp(TOK3(">>="))) {
1180 opassign(O_SHR, 0);
1181 return;
1183 if (!tok_jmp(TOK3("&="))) {
1184 opassign(O_AND, 0);
1185 return;
1187 if (!tok_jmp(TOK3("|="))) {
1188 opassign(O_OR, 0);
1189 return;
1191 if (!tok_jmp(TOK3("^="))) {
1192 opassign(O_XOR, 0);
1193 return;
1197 static void readestmt(void)
1199 do {
1200 o_tmpdrop(-1);
1201 nts = 0;
1202 readexpr();
1203 } while (!tok_jmp(','));
1206 static void o_localoff(long addr, int off)
1208 o_local(addr);
1209 if (off) {
1210 o_num(off);
1211 o_bop(O_ADD);
1215 static struct type *innertype(struct type *t)
1217 if (t->flags & T_ARRAY && !t->ptr)
1218 return innertype(&arrays[t->id].type);
1219 return t;
1222 static void initexpr(struct type *t, int off, void *obj,
1223 void (*set)(void *obj, int off, struct type *t))
1225 if (tok_jmp('{')) {
1226 set(obj, off, t);
1227 return;
1229 if (!t->ptr && t->flags & T_STRUCT) {
1230 struct structinfo *si = &structs[t->id];
1231 int i;
1232 for (i = 0; i < si->nfields; i++) {
1233 struct name *field = &si->fields[i];
1234 if (!tok_jmp('.')) {
1235 tok_expect(TOK_NAME);
1236 field = struct_field(t->id, tok_id());
1237 tok_expect('=');
1239 initexpr(&field->type, off + field->addr, obj, set);
1240 if (tok_jmp(',') || tok_see() == '}')
1241 break;
1243 } else if (t->flags & T_ARRAY) {
1244 struct type *t_de = &arrays[t->id].type;
1245 int i;
1246 for (i = 0; ; i++) {
1247 long idx = i;
1248 struct type *it = t_de;
1249 if (!tok_jmp('[')) {
1250 readexpr();
1251 o_popnum(&idx);
1252 ts_pop(NULL);
1253 tok_expect(']');
1254 tok_expect('=');
1256 if (tok_see() != '{')
1257 it = innertype(t_de);
1258 initexpr(it, off + type_totsz(it) * idx, obj, set);
1259 if (tok_jmp(',') || tok_see() == '}')
1260 break;
1263 tok_expect('}');
1266 static void jumpbrace(void)
1268 int depth = 0;
1269 while (tok_see() != '}' || depth--)
1270 if (tok_get() == '{')
1271 depth++;
1272 tok_expect('}');
1275 static int initsize(void)
1277 long addr = tok_addr();
1278 int n = 0;
1279 if (!tok_jmp(TOK_STR)) {
1280 n = tok_str(NULL);
1281 tok_jump(addr);
1282 return n;
1284 o_nogen();
1285 tok_expect('{');
1286 while (tok_jmp('}')) {
1287 long idx = n;
1288 if (!tok_jmp('[')) {
1289 readexpr();
1290 o_popnum(&idx);
1291 ts_pop(NULL);
1292 tok_expect(']');
1293 tok_expect('=');
1295 if (n < idx + 1)
1296 n = idx + 1;
1297 while (tok_see() != '}' && tok_see() != ',')
1298 if (tok_get() == '{')
1299 jumpbrace();
1300 tok_jmp(',');
1302 o_dogen();
1303 tok_jump(addr);
1304 return n;
1307 #define F_GLOBAL(flags) (!((flags) & F_STATIC))
1309 static void globalinit(void *obj, int off, struct type *t)
1311 struct name *name = obj;
1312 char *elfname = *name->elfname ? name->elfname : name->name;
1313 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1314 struct type *t_de = &arrays[t->id].type;
1315 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1316 char buf[BUFSIZE];
1317 int len;
1318 tok_expect(TOK_STR);
1319 len = tok_str(buf);
1320 memcpy((void *) name->addr + off, buf, len);
1321 return;
1324 readexpr();
1325 o_datset(elfname, off, TYPE_BT(t));
1326 ts_pop(NULL);
1329 static void globaldef(void *data, struct name *name, unsigned flags)
1331 struct type *t = &name->type;
1332 char *elfname = *name->elfname ? name->elfname : name->name;
1333 int sz;
1334 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1335 if (~flags & F_EXTERN)
1336 arrays[t->id].n = initsize();
1337 sz = type_totsz(t);
1338 if (!(flags & F_EXTERN) && (!(t->flags & T_FUNC) || t->ptr)) {
1339 if (flags & F_INIT)
1340 name->addr = (long) dat_dat(elfname, sz, F_GLOBAL(flags));
1341 else
1342 dat_bss(elfname, sz, F_GLOBAL(flags));
1344 global_add(name);
1345 if (flags & F_INIT)
1346 initexpr(t, 0, name, globalinit);
1349 static void localinit(void *obj, int off, struct type *t)
1351 long addr = *(long *) obj;
1352 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1353 struct type *t_de = &arrays[t->id].type;
1354 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1355 char buf[BUFSIZE];
1356 int len;
1357 tok_expect(TOK_STR);
1358 len = tok_str(buf);
1359 o_localoff(addr, off);
1360 o_sym(tmp_str(buf, len));
1361 o_num(len);
1362 o_memcpy();
1363 o_tmpdrop(1);
1364 return;
1367 o_localoff(addr, off);
1368 ts_push(t);
1369 readexpr();
1370 doassign();
1371 ts_pop(NULL);
1372 o_tmpdrop(1);
1375 /* current function name */
1376 static char func_name[NAMELEN];
1378 static void localdef(void *data, struct name *name, unsigned flags)
1380 struct type *t = &name->type;
1381 if (flags & (F_STATIC | F_EXTERN)) {
1382 sprintf(name->elfname, "__neatcc.%s.%s", func_name, name->name);
1383 globaldef(data, name, flags);
1384 return;
1386 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1387 arrays[t->id].n = initsize();
1388 name->addr = o_mklocal(type_totsz(&name->type));
1389 local_add(name);
1390 if (flags & F_INIT) {
1391 if (t->flags & (T_ARRAY | T_STRUCT) && !t->ptr) {
1392 o_local(name->addr);
1393 o_num(0);
1394 o_num(type_totsz(t));
1395 o_memset();
1396 o_tmpdrop(1);
1398 initexpr(t, 0, &name->addr, localinit);
1402 static void funcdef(char *name, struct type *type, struct name *args,
1403 int nargs, unsigned flags)
1405 struct name global = {""};
1406 int i;
1407 strcpy(global.name, name);
1408 strcpy(func_name, name);
1409 memcpy(&global.type, type, sizeof(*type));
1410 o_func_beg(name, F_GLOBAL(flags));
1411 global_add(&global);
1412 for (i = 0; i < nargs; i++) {
1413 args[i].addr = o_arg(i);
1414 local_add(&args[i]);
1418 static int readargs(struct name *args)
1420 int nargs = 0;
1421 tok_expect('(');
1422 while (tok_see() != ')') {
1423 if (!tok_jmp(TOK3("...")))
1424 break;
1425 readname(&args[nargs].type, args[nargs].name, NULL, 0);
1426 array2ptr(&args[nargs].type);
1427 nargs++;
1428 if (tok_jmp(','))
1429 break;
1431 tok_expect(')');
1432 if (nargs == 1 && !TYPE_BT(&args[0].type))
1433 return 0;
1434 return nargs;
1437 static int readname(struct type *main, char *name,
1438 struct type *base, unsigned flags)
1440 struct type tpool[3];
1441 int npool = 0;
1442 struct type *type = &tpool[npool++];
1443 struct type *func = NULL;
1444 struct type *ret = NULL;
1445 int arsz[10];
1446 int nar = 0;
1447 int i;
1448 memset(tpool, 0, sizeof(tpool));
1449 if (name)
1450 *name = '\0';
1451 if (!base) {
1452 if (basetype(type, &flags))
1453 return 1;
1454 } else {
1455 memcpy(type, base, sizeof(*base));
1457 readptrs(type);
1458 if (!tok_jmp('(')) {
1459 ret = type;
1460 type = &tpool[npool++];
1461 func = type;
1462 readptrs(type);
1464 if (!tok_jmp(TOK_NAME) && name)
1465 strcpy(name, tok_id());
1466 while (!tok_jmp('[')) {
1467 long n = 0;
1468 if (tok_jmp(']')) {
1469 readexpr();
1470 ts_pop(NULL);
1471 if (o_popnum(&n))
1472 err("const expr expected\n");
1473 tok_expect(']');
1475 arsz[nar++] = n;
1477 for (i = nar - 1; i >= 0; i--) {
1478 type->id = array_add(type, arsz[i]);
1479 if (func && i == nar - 1)
1480 func = &arrays[type->id].type;
1481 type->flags = T_ARRAY;
1482 type->bt = LONGSZ;
1483 type->ptr = 0;
1485 if (func)
1486 tok_expect(')');
1487 if (tok_see() == '(') {
1488 struct name args[MAXARGS] = {{""}};
1489 int nargs = readargs(args);
1490 int fdef = !func;
1491 if (!func) {
1492 ret = type;
1493 type = &tpool[npool++];
1494 func = type;
1496 func->flags = T_FUNC;
1497 func->bt = LONGSZ;
1498 func->id = func_create(ret, args, nargs);
1499 if (fdef && tok_see() == '{') {
1500 funcdef(name, func, args, nargs, flags);
1501 return 1;
1504 memcpy(main, type, sizeof(*type));
1505 return 0;
1508 static int readdefs(void (*def)(void *data, struct name *name, unsigned flags),
1509 void *data)
1511 struct type base;
1512 unsigned base_flags;
1513 if (basetype(&base, &base_flags))
1514 return 1;
1515 while (tok_see() != ';' && tok_see() != '{') {
1516 struct name name = {{""}};
1517 unsigned flags = base_flags;
1518 if (readname(&name.type, name.name, &base, flags))
1519 break;
1520 if (!tok_jmp('='))
1521 flags |= F_INIT;
1522 def(data, &name, flags);
1523 tok_jmp(',');
1525 return 0;
1528 static void typedefdef(void *data, struct name *name, unsigned flags)
1530 typedef_add(name->name, &name->type);
1533 static void readstmt(void);
1535 #define MAXCASES (1 << 7)
1537 static void readswitch(void)
1539 int break_beg = nbreaks;
1540 long val_addr = o_mklocal(LONGSZ);
1541 long matched[MAXCASES];
1542 int nmatched = 0;
1543 struct type t;
1544 long next;
1545 int ref = 1;
1546 int i;
1547 tok_expect('(');
1548 readexpr();
1549 ts_pop_de(&t);
1550 o_local(val_addr);
1551 o_tmpswap();
1552 o_assign(TYPE_BT(&t));
1553 ts_de(0);
1554 o_tmpdrop(1);
1555 tok_expect(')');
1556 tok_expect('{');
1557 while (tok_jmp('}')) {
1558 int n = 0;
1559 while (tok_see() == TOK_CASE || tok_see() == TOK_DEFAULT) {
1560 if (n++ > 0)
1561 matched[nmatched++] = o_jmp(0);
1562 if (!ref++)
1563 o_filljmp(next);
1564 if (!tok_jmp(TOK_CASE)) {
1565 caseexpr = 1;
1566 readexpr();
1567 ts_pop_de(NULL);
1568 caseexpr = 0;
1569 o_local(val_addr);
1570 o_deref(TYPE_BT(&t));
1571 o_bop(O_EQ);
1572 next = o_jz(0);
1573 ref = 0;
1574 tok_expect(':');
1575 o_tmpdrop(1);
1576 continue;
1578 if (!tok_jmp(TOK_DEFAULT)) {
1579 tok_expect(':');
1580 continue;
1583 for (i = 0; i < nmatched; i++)
1584 o_filljmp(matched[i]);
1585 nmatched = 0;
1586 readstmt();
1588 o_rmlocal(val_addr, LONGSZ);
1589 if (!ref++)
1590 o_filljmp(next);
1591 break_fill(o_mklabel(), break_beg);
1594 #define MAXGOTO (1 << 10)
1596 static struct gotoinfo {
1597 char name[NAMELEN];
1598 long addr;
1599 } gotos[MAXGOTO];
1600 static int ngotos;
1602 static struct labelinfo {
1603 char name[NAMELEN];
1604 long addr;
1605 } labels[MAXGOTO];
1606 static int nlabels;
1608 static void goto_add(char *name)
1610 strcpy(gotos[ngotos].name, name);
1611 gotos[ngotos++].addr = o_jmp(0);
1614 static void label_add(char *name)
1616 strcpy(labels[nlabels].name, name);
1617 labels[nlabels++].addr = o_mklabel();
1620 static void goto_fill(void)
1622 int i, j;
1623 for (i = 0; i < ngotos; i++)
1624 for (j = 0; j < nlabels; j++)
1625 if (!strcmp(gotos[i].name, labels[j].name)) {
1626 o_filljmp2(gotos[i].addr, labels[j].addr);
1627 break;
1631 static void readstmt(void)
1633 o_tmpdrop(-1);
1634 nts = 0;
1635 if (!tok_jmp('{')) {
1636 int _nlocals = nlocals;
1637 int _nglobals = nglobals;
1638 int _nenums = nenums;
1639 int _ntypedefs = ntypedefs;
1640 int _nstructs = nstructs;
1641 int _nfuncs = nfuncs;
1642 int _narrays = narrays;
1643 while (tok_jmp('}'))
1644 readstmt();
1645 nlocals = _nlocals;
1646 nenums = _nenums;
1647 ntypedefs = _ntypedefs;
1648 nstructs = _nstructs;
1649 nfuncs = _nfuncs;
1650 narrays = _narrays;
1651 nglobals = _nglobals;
1652 return;
1654 if (!readdefs(localdef, NULL)) {
1655 tok_expect(';');
1656 return;
1658 if (!tok_jmp(TOK_TYPEDEF)) {
1659 readdefs(typedefdef, NULL);
1660 tok_expect(';');
1661 return;
1663 if (!tok_jmp(TOK_IF)) {
1664 long l1, l2;
1665 tok_expect('(');
1666 readexpr();
1667 tok_expect(')');
1668 ts_pop_de(NULL);
1669 l1 = o_jz(0);
1670 readstmt();
1671 if (!tok_jmp(TOK_ELSE)) {
1672 l2 = o_jmp(0);
1673 o_filljmp(l1);
1674 readstmt();
1675 o_filljmp(l2);
1676 } else {
1677 o_filljmp(l1);
1679 return;
1681 if (!tok_jmp(TOK_WHILE)) {
1682 long l1, l2;
1683 int break_beg = nbreaks;
1684 int continue_beg = ncontinues;
1685 l1 = o_mklabel();
1686 tok_expect('(');
1687 readexpr();
1688 tok_expect(')');
1689 ts_pop_de(NULL);
1690 l2 = o_jz(0);
1691 readstmt();
1692 o_jmp(l1);
1693 o_filljmp(l2);
1694 break_fill(o_mklabel(), break_beg);
1695 continue_fill(l1, continue_beg);
1696 return;
1698 if (!tok_jmp(TOK_DO)) {
1699 long l1, l2;
1700 int break_beg = nbreaks;
1701 int continue_beg = ncontinues;
1702 l1 = o_mklabel();
1703 readstmt();
1704 tok_expect(TOK_WHILE);
1705 tok_expect('(');
1706 l2 = o_mklabel();
1707 readexpr();
1708 ts_pop_de(NULL);
1709 o_jnz(l1);
1710 tok_expect(')');
1711 break_fill(o_mklabel(), break_beg);
1712 continue_fill(l2, continue_beg);
1713 return;
1715 if (!tok_jmp(TOK_FOR)) {
1716 long l_check, l_jump, j_fail, j_pass;
1717 int break_beg = nbreaks;
1718 int continue_beg = ncontinues;
1719 int has_cond = 0;
1720 tok_expect('(');
1721 if (tok_see() != ';')
1722 readestmt();
1723 tok_expect(';');
1724 l_check = o_mklabel();
1725 if (tok_see() != ';') {
1726 readestmt();
1727 ts_pop_de(NULL);
1728 j_fail = o_jz(0);
1729 has_cond = 1;
1731 tok_expect(';');
1732 j_pass = o_jmp(0);
1733 l_jump = o_mklabel();
1734 if (tok_see() != ')')
1735 readestmt();
1736 tok_expect(')');
1737 o_jmp(l_check);
1738 o_filljmp(j_pass);
1739 readstmt();
1740 o_jmp(l_jump);
1741 if (has_cond)
1742 o_filljmp(j_fail);
1743 break_fill(o_mklabel(), break_beg);
1744 continue_fill(l_jump, continue_beg);
1745 return;
1747 if (!tok_jmp(TOK_SWITCH)) {
1748 readswitch();
1749 return;
1751 if (!tok_jmp(TOK_RETURN)) {
1752 int ret = tok_see() != ';';
1753 if (ret) {
1754 readexpr();
1755 ts_pop_de(NULL);
1757 tok_expect(';');
1758 o_ret(ret);
1759 return;
1761 if (!tok_jmp(TOK_BREAK)) {
1762 tok_expect(';');
1763 breaks[nbreaks++] = o_jmp(0);
1764 return;
1766 if (!tok_jmp(TOK_CONTINUE)) {
1767 tok_expect(';');
1768 continues[ncontinues++] = o_jmp(0);
1769 return;
1771 if (!tok_jmp(TOK_GOTO)) {
1772 tok_expect(TOK_NAME);
1773 goto_add(tok_id());
1774 tok_expect(';');
1775 return;
1777 readestmt();
1778 /* labels */
1779 if (!tok_jmp(':')) {
1780 label_add(tok_id());
1781 return;
1783 tok_expect(';');
1786 static void readdecl(void)
1788 if (!tok_jmp(TOK_TYPEDEF)) {
1789 readdefs(typedefdef, NULL);
1790 tok_expect(';');
1791 return;
1793 readdefs(globaldef, NULL);
1794 if (tok_see() == '{') {
1795 readstmt();
1796 goto_fill();
1797 o_func_end();
1798 func_name[0] = '\0';
1799 nlocals = 0;
1800 ngotos = 0;
1801 nlabels = 0;
1802 return;
1804 tok_expect(';');
1807 static void parse(void)
1809 while (tok_see() != TOK_EOF)
1810 readdecl();
1813 int main(int argc, char *argv[])
1815 char obj[128];
1816 int ofd;
1817 int i = 1;
1818 while (i < argc && argv[i][0] == '-') {
1819 if (argv[i][1] == 'I')
1820 cpp_addpath(argv[i][2] ? argv[i] + 2 : argv[++i]);
1821 if (argv[i][1] == 'D') {
1822 char *name = argv[i] + 2;
1823 char *def = "";
1824 char *eq = strchr(name, '=');
1825 if (eq) {
1826 *eq = '\0';
1827 def = eq + 1;
1829 cpp_define(name, def);
1831 i++;
1833 if (i == argc)
1834 die("neatcc: no file given\n");
1835 if (cpp_init(argv[i]))
1836 die("neatcc: cannot open input file\n");
1837 parse();
1838 strcpy(obj, argv[i]);
1839 obj[strlen(obj) - 1] = 'o';
1840 ofd = open(obj, O_WRONLY | O_TRUNC | O_CREAT, 0600);
1841 o_write(ofd);
1842 close(ofd);
1843 return 0;