2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
36 /* no eXecute on Win32 */
41 #define O_RDWR _O_RDWR
42 #define O_CREAT _O_CREAT
43 #define O_EXCL _O_EXCL
44 #define O_BINARY _O_BINARY
46 /* remap some names, we are not in the POSIX world */
47 #define access(fname, mode) _access(fname, mode)
48 #define mktemp(tmpl) _mktemp(tmpl)
49 #define open(fname, oflag, mode) _open(fname, oflag, mode)
50 #define fdopen(fd, mode) _fdopen(fd, mode)
51 #define popen(cmd, mode) _popen(cmd, mode)
52 #define pclose(file) _pclose(file)
63 #include <libfirm/firm.h>
64 #include <libfirm/be.h>
69 #include "type_hash.h"
72 #include "diagnostic.h"
73 #include "lang_features.h"
74 #include "driver/firm_opt.h"
75 #include "driver/firm_cmdline.h"
76 #include "adt/error.h"
77 #include "write_fluffy.h"
78 #include "write_caml.h"
83 #define PREPROCESSOR "cpp -std=c99 -U__WCHAR_TYPE__ -D__WCHAR_TYPE__=int -U__SIZE_TYPE__ -D__SIZE_TYPE__=__SIZE_TYPE__ -m32"
87 #define LINKER "gcc -m32"
91 #define ASSEMBLER "as --32"
94 /** The current c mode/dialect. */
95 unsigned int c_mode = _C89|_C99|_GNUC;
97 /** The 'machine size', 16, 32 or 64 bit, 32bit is the default. */
98 unsigned int machine_size = 32;
100 /** true if the char type is signed. */
101 bool char_is_signed = true;
103 /** true for strict language checking. */
104 bool strict_mode = false;
106 /** use builtins for some libc functions */
107 bool use_builtins = false;
109 /* to switch on printing of implicit casts */
110 extern bool print_implicit_casts;
112 /* to switch on printing of parenthesis to indicate operator precedence */
113 extern bool print_parenthesis;
116 static struct obstack cppflags_obst, ldflags_obst;
118 typedef struct file_list_entry_t file_list_entry_t;
120 struct file_list_entry_t {
121 const char *filename;
122 file_list_entry_t *next;
125 #if defined(_DEBUG) || defined(FIRM_DEBUG)
127 * Debug printf implementation.
129 * @param fmt printf style format parameter
131 void dbg_printf(const char *fmt, ...)
135 if (firm_dump.debug_print) {
141 #endif /* defined(_DEBUG) || defined(FIRM_DEBUG) */
143 static void initialize_firm(void)
147 dump_consts_local(1);
148 dump_keepalive_edges(1);
151 static void get_output_name(char *buf, size_t buflen, const char *inputname,
154 size_t last_dot = 0xffffffff;
157 if(inputname == NULL) {
158 snprintf(buf, buflen, "a%s", newext);
162 for(const char *c = inputname; *c != 0; ++c) {
167 if(last_dot == 0xffffffff)
170 if(last_dot >= buflen)
171 panic("filename too long");
172 memcpy(buf, inputname, last_dot);
174 size_t extlen = strlen(newext) + 1;
175 if(extlen + last_dot >= buflen)
176 panic("filename too long");
177 memcpy(buf+last_dot, newext, extlen);
180 #include "builtins.h"
182 static translation_unit_t *do_parsing(FILE *const in, const char *const input_name)
187 lexer_open_buffer(builtins, sizeof(builtins)-1, "<builtin>");
191 lexer_open_stream(in, input_name);
194 translation_unit_t *unit = finish_parsing();
198 static void lextest(FILE *in, const char *fname)
200 lexer_open_stream(in, fname);
203 lexer_next_preprocessing_token();
204 print_token(stdout, &lexer_token);
206 } while(lexer_token.type != T_EOF);
209 static FILE *preprocess(FILE *in, const char *fname, bool to_stdout)
212 obstack_1grow(&cppflags_obst, '\0');
213 const char *flags = obstack_finish(&cppflags_obst);
216 snprintf(buf, sizeof(buf), PREPROCESSOR " %s %s", flags, fname);
218 /* read from stdin */
219 snprintf(buf, sizeof(buf), PREPROCESSOR " %s -", flags);
226 int res = system(buf);
229 FILE *f = popen(buf, "r");
231 fprintf(stderr, "invoking preprocessor failed\n");
238 static void do_link(const char *out, const char *in)
241 obstack_1grow(&ldflags_obst, '\0');
242 const char *flags = obstack_finish(&ldflags_obst);
244 snprintf(buf, sizeof(buf), LINKER " %s -o %s %s", flags, out, in);
248 int err = system(buf);
250 fprintf(stderr, "linker reported an error\n");
255 static void assemble(const char *out, const char *in)
259 snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
264 int err = system(buf);
266 fprintf(stderr, "assembler reported an error\n");
271 static const char *try_dir(const char *dir)
275 if(access(dir, R_OK | W_OK | X_OK) == 0)
280 static const char *get_tempdir(void)
282 static const char *tmpdir = NULL;
288 tmpdir = try_dir(getenv("TMPDIR"));
290 tmpdir = try_dir(getenv("TMP"));
292 tmpdir = try_dir(getenv("TEMP"));
296 tmpdir = try_dir(P_tmpdir);
300 tmpdir = try_dir("/var/tmp");
302 tmpdir = try_dir("/usr/tmp");
304 tmpdir = try_dir("/tmp");
313 /* cheap and nasty mkstemp replacement */
314 static int mkstemp(char *templ)
317 return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
322 * an own version of tmpnam, which: writes in a buffer, appends a user specified
323 * suffix, emits no warnings during linking (like glibc/gnu ld do for tmpnam)...
325 static FILE *make_temp_file(char *buffer, size_t buflen,
326 const char *prefix, const char *suffix)
328 const char *tempdir = get_tempdir();
330 /* oh well... mkstemp doesn't accept a suffix after XXXXXX... */
334 snprintf(buffer, buflen, "%s/%sXXXXXX%s", tempdir, prefix, suffix);
336 int fd = mkstemp(buffer);
338 fprintf(stderr, "couldn't create temporary file: %s\n",
342 FILE *out = fdopen(fd, "w");
344 fprintf(stderr, "couldn't create temporary file FILE*\n");
352 * Do the necessary lowering for compound parameters.
354 void lower_compound_params(void)
356 lower_params_t params;
358 params.def_ptr_alignment = 4;
359 params.flags = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
360 params.hidden_params = ADD_HIDDEN_ALWAYS_IN_FRONT;
361 params.find_pointer_type = NULL;
362 params.ret_compound_in_regs = NULL;
363 lower_calls_with_compounds(¶ms);
366 typedef enum compile_mode_t {
381 static void usage(const char *argv0)
383 fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
386 static void print_cparser_version(void) {
388 firm_get_version(&ver);
390 printf("cparser (%s) using libFirm (%u.%u",
391 cparser_REVISION, ver.major, ver.minor);
392 if(ver.revision[0] != 0) {
394 fputs(ver.revision, stdout);
396 if(ver.build[0] != 0) {
398 fputs(ver.build, stdout);
403 static void set_be_option(const char *arg)
405 int res = firm_be_option(arg);
410 static void set_option(const char *arg)
412 int res = firm_option(arg);
417 int main(int argc, char **argv)
421 const char *input = NULL;
422 const char *outname = NULL;
423 const char *dumpfunction = NULL;
424 compile_mode_t mode = CompileAssembleLink;
426 int result = EXIT_SUCCESS;
427 char cpu_arch[16] = "ia32";
428 file_list_entry_t *c_files = NULL;
429 file_list_entry_t *s_files = NULL;
430 file_list_entry_t *o_files = NULL;
431 struct obstack file_obst;
433 obstack_init(&cppflags_obst);
434 obstack_init(&ldflags_obst);
435 obstack_init(&file_obst);
437 #define GET_ARG_AFTER(def, args) \
438 def = &arg[sizeof(args)-1]; \
439 if(def[0] == '\0') { \
442 fprintf(stderr, "error: expected argument after '" args "'\n"); \
443 argument_errors = true; \
447 if(def[0] == '-' && def[1] != '\0') { \
448 fprintf(stderr, "error: expected argument after '" args "'\n"); \
449 argument_errors = true; \
454 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
456 /* early options parsing (find out optimisation level) */
457 for(int i = 1; i < argc; ++i) {
458 const char *arg = argv[i];
462 const char *option = &arg[1];
463 if(option[0] == 'O') {
464 sscanf(&option[1], "%d", &opt_level);
468 /* apply optimisation level */
471 set_option("no-opt");
474 set_option("no-inline");
478 set_option("strict-aliasing");
481 set_option("cond-eval");
482 set_option("if-conv");
486 set_option("inline");
487 set_option("deconv");
488 set_be_option("omitfp");
492 /* parse rest of options */
493 bool help_displayed = false;
494 bool argument_errors = false;
495 for(int i = 1; i < argc; ++i) {
496 const char *arg = argv[i];
497 if(arg[0] == '-' && arg[1] != 0) {
499 const char *option = &arg[1];
500 if(option[0] == 'o') {
501 GET_ARG_AFTER(outname, "-o");
502 } else if(option[0] == 'g') {
503 set_be_option("debuginfo=stabs");
504 set_be_option("omitfp=no");
505 set_be_option("ia32-nooptcc=yes");
506 } else if(SINGLE_OPTION('c')) {
507 mode = CompileAssemble;
508 } else if(SINGLE_OPTION('E')) {
509 mode = PreprocessOnly;
510 } else if(SINGLE_OPTION('S')) {
512 } else if(option[0] == 'O') {
514 } else if(option[0] == 'I') {
516 GET_ARG_AFTER(opt, "-I");
517 obstack_printf(&cppflags_obst, " -I%s", opt);
518 } else if(option[0] == 'D') {
520 GET_ARG_AFTER(opt, "-D");
521 obstack_printf(&cppflags_obst, " -D%s", opt);
522 } else if(option[0] == 'U') {
524 GET_ARG_AFTER(opt, "-U");
525 obstack_printf(&cppflags_obst, " -U%s", opt);
526 } else if(option[0] == 'l') {
528 GET_ARG_AFTER(opt, "-l");
529 obstack_printf(&ldflags_obst, " -l%s", opt);
530 } else if(option[0] == 'L') {
532 GET_ARG_AFTER(opt, "-L");
533 obstack_printf(&ldflags_obst, " -L%s", opt);
534 } else if(SINGLE_OPTION('v')) {
536 } else if(SINGLE_OPTION('w')) {
537 inhibit_all_warnings = true;
538 } else if(option[0] == 'f') {
540 GET_ARG_AFTER(opt, "-f");
542 if(strcmp(opt, "syntax-only") == 0) {
544 } else if(strcmp(opt, "omit-frame-pointer") == 0) {
545 set_be_option("omitfp");
546 } else if(strcmp(opt, "no-omit-frame-pointer") == 0) {
547 set_be_option("omitfp=no");
548 } else if(strcmp(opt, "fast-math") == 0
549 || strcmp(opt, "unroll-loops") == 0
550 || strcmp(opt, "expensive-optimizations") == 0
551 || strcmp(opt, "no-common") == 0) {
552 fprintf(stderr, "ignoring gcc option '-f %s'\n", opt);
554 int res = firm_option(opt);
556 fprintf(stderr, "error: unknown Firm option '-f %s'\n",
558 argument_errors = true;
560 } else if (res == -1) {
561 help_displayed = true;
564 } else if(option[0] == 'b') {
566 GET_ARG_AFTER(opt, "-b");
567 int res = firm_be_option(opt);
569 fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
571 argument_errors = true;
572 } else if (res == -1) {
573 help_displayed = true;
575 if (strncmp(opt, "isa=", 4) == 0)
576 strncpy(cpu_arch, opt, sizeof(cpu_arch));
578 } else if(option[0] == 'W') {
579 set_warning_opt(&option[1]);
580 } else if(option[0] == 'm') {
585 GET_ARG_AFTER(opt, "-m");
586 if(strncmp(opt, "arch=", 5) == 0) {
587 GET_ARG_AFTER(opt, "-march=");
588 snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
589 int res = firm_be_option(arch_opt);
591 argument_errors = true;
593 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
594 int res = firm_be_option(arch_opt);
596 argument_errors = true;
598 } else if(strncmp(opt, "tune=", 5) == 0) {
599 GET_ARG_AFTER(opt, "-mtune=");
600 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
601 int res = firm_be_option(arch_opt);
603 argument_errors = true;
604 } else if(strncmp(opt, "cpu=", 4) == 0) {
605 GET_ARG_AFTER(opt, "-mcpu=");
606 snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
607 int res = firm_be_option(arch_opt);
609 argument_errors = true;
610 } else if(strncmp(opt, "fpmath=", 7) == 0) {
611 GET_ARG_AFTER(opt, "-mfpmath=");
612 if(strcmp(opt, "387") == 0)
614 else if(strcmp(opt, "sse") == 0)
617 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
618 argument_errors = true;
620 if(!argument_errors) {
621 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
622 int res = firm_be_option(arch_opt);
624 argument_errors = true;
626 } else if(strncmp(opt, "preferred-stack-boundary=", 25) == 0) {
627 GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
628 snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
629 int res = firm_be_option(arch_opt);
631 argument_errors = true;
632 } else if(strcmp(opt, "omit-leaf-frame-pointer") == 0) {
633 set_be_option("omitleaffp=1");
634 } else if(strcmp(opt, "no-omit-leaf-frame-pointer") == 0) {
635 set_be_option("omitleaffp=0");
638 long int value = strtol(opt, &endptr, 10);
639 if (*endptr != '\0') {
640 fprintf(stderr, "error: wrong option '-m %s'\n", opt);
641 argument_errors = true;
643 if (value != 16 && value != 32 && value != 64) {
644 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
645 argument_errors = true;
647 machine_size = (unsigned int)value;
650 } else if (option[0] == '\0') {
652 fprintf(stderr, "error: multiple input files specified\n");
653 argument_errors = true;
657 } else if(strcmp(option, "pg") == 0) {
658 set_be_option("gprof");
659 obstack_printf(&ldflags_obst, " -pg");
660 } else if(strcmp(option, "pedantic") == 0) {
661 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
662 } else if(strncmp(option, "std=", 4) == 0) {
663 if(strcmp(&option[4], "c99") == 0) {
665 } else if(strcmp(&option[4], "c89") == 0) {
667 } else if(strcmp(&option[4], "gnu99") == 0) {
668 c_mode = _C89|_C99|_GNUC;
669 } else if(strcmp(&option[4], "microsoft") == 0) {
670 c_mode = _C89|_C99|_MS;
672 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
673 } else if(strcmp(option, "version") == 0) {
674 print_cparser_version();
675 } else if (option[0] == '-') {
676 /* double dash option */
678 if(strcmp(option, "gcc") == 0) {
680 } else if(strcmp(option, "no-gcc") == 0) {
682 } else if(strcmp(option, "ms") == 0) {
684 } else if(strcmp(option, "no-ms") == 0) {
686 } else if(strcmp(option, "signed-chars") == 0) {
687 char_is_signed = true;
688 } else if(strcmp(option, "unsigned-chars") == 0) {
689 char_is_signed = false;
690 } else if(strcmp(option, "strict") == 0) {
692 } else if(strcmp(option, "lextest") == 0) {
694 } else if(strcmp(option, "benchmark") == 0) {
695 mode = BenchmarkParser;
696 } else if(strcmp(option, "print-ast") == 0) {
698 } else if(strcmp(option, "print-implicit-cast") == 0) {
699 print_implicit_casts = true;
700 } else if(strcmp(option, "print-parenthesis") == 0) {
701 print_parenthesis = true;
702 } else if(strcmp(option, "print-fluffy") == 0) {
704 } else if(strcmp(option, "print-caml") == 0) {
706 } else if(strcmp(option, "version") == 0) {
707 print_cparser_version();
709 } else if(strcmp(option, "dump-function") == 0) {
712 fprintf(stderr, "error: "
713 "expected argument after '--dump-function'\n");
714 argument_errors = true;
717 dumpfunction = argv[i];
720 fprintf(stderr, "error: unknown argument '%s'\n", arg);
721 argument_errors = true;
724 fprintf(stderr, "error: unknown argument '%s'\n", arg);
725 argument_errors = true;
729 file_list_entry_t *entry
730 = obstack_alloc(&file_obst, sizeof(entry[0]));
731 entry->filename = arg;
733 size_t len = strlen(arg);
736 /* exception: '-' as name reads C from stdin */
737 entry->next = c_files;
741 fprintf(stderr, "'%s': file format not recognized\n", input);
745 if (strcmp(arg+len-2, ".c") == 0
746 || strcmp(arg+len-2, ".h") == 0) {
747 entry->next = c_files;
749 } else if (strcmp(arg+len-2, ".s") == 0) {
750 entry->next = s_files;
752 } else if (strcmp(arg+len-2, ".o") == 0) {
753 entry->next = o_files;
756 fprintf(stderr, "'%s': file format not recognized\n", input);
761 if (c_files == NULL && s_files == NULL && o_files != NULL) {
763 } else if (c_files != NULL && c_files->next == NULL) {
764 input = c_files->filename;
766 if (c_files == NULL) {
767 fprintf(stderr, "error: no input files specified\n");
769 fprintf(stderr, "error: multiple input files specified\n");
771 argument_errors = true;
774 /* we do the lowering in ast2firm */
775 firm_opt.lower_bitfields = FALSE;
777 if (help_displayed) {
778 return !argument_errors;
780 if (argument_errors) {
797 char outnamebuf[4096];
798 if(outname == NULL) {
800 case BenchmarkParser:
813 get_output_name(outnamebuf, sizeof(outnamebuf), input, ".s");
814 outname = outnamebuf;
816 case CompileAssemble:
817 get_output_name(outnamebuf, sizeof(outnamebuf), input, ".o");
818 outname = outnamebuf;
821 get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
823 outname = outnamebuf;
826 case CompileAssembleLink:
828 /* Windows compiler typically derive the output name from
829 the first source file */
830 get_output_name(outnamebuf, sizeof(outnamebuf), input, ".exe");
831 outname = outnamebuf;
840 obstack_1grow(&ldflags_obst, '\0');
841 const char *flags = obstack_finish(&ldflags_obst);
843 obstack_printf(&file_obst, "%s", LINKER);
845 for (file_list_entry_t *entry = o_files; entry != NULL;
846 entry = entry->next) {
847 obstack_printf(&file_obst, " %s", entry->filename);
850 obstack_printf(&file_obst, " -o %s %s", outname, flags);
852 char *buf = obstack_finish(&file_obst);
857 int err = system(buf);
859 fprintf(stderr, "linker reported an error\n");
865 if(outname != NULL) {
866 if(strcmp(outname, "-") == 0) {
869 out = fopen(outname, "w");
871 fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
880 fprintf(stderr, "%s: no input files\n", argv[0]);
882 } else if(strcmp(input, "-") == 0) {
886 in = fopen(input, "r");
888 fprintf(stderr, "Couldn't open '%s': %s\n", input, strerror(errno));
893 if(mode == LexTest) {
899 FILE *preprocessed_in = preprocess(in, input, mode == PreprocessOnly);
900 translation_unit_t *const unit = do_parsing(preprocessed_in, input);
901 int res = pclose(preprocessed_in);
906 if(error_count > 0) {
907 /* parsing failed because of errors */
908 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count, warning_count);
909 result = EXIT_FAILURE;
910 } else if(warning_count > 0) {
911 fprintf(stderr, "%u warning(s)\n", warning_count);
914 if(mode == BenchmarkParser) {
918 /* prints the AST even if errors occurred */
919 if(mode == PrintAst) {
920 type_set_output(out);
926 /* cannot handle other modes with errors */
927 if(result != EXIT_SUCCESS)
930 if(mode == PrintFluffy) {
931 write_fluffy_decls(out, unit);
933 if (mode == PrintCaml) {
934 write_caml_decls(out, unit);
937 translation_unit_to_firm(unit);
939 if(mode == ParseOnly) {
944 char asm_tempfile[1024];
945 if(mode == CompileDump) {
947 firm_be_opt.selection = BE_NONE;
948 } else if(mode == Compile) {
952 = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "cc", ".s");
954 gen_firm_finish(asm_out, input, /*c_mode=*/1, /*firm_const_exists=*/0);
956 if(mode == CompileDump) {
958 ident *id = new_id_from_str(dumpfunction);
959 ir_graph *irg = NULL;
960 int n_irgs = get_irp_n_irgs();
961 for(int i = 0; i < n_irgs; ++i) {
962 ir_graph *tirg = get_irp_irg(i);
963 ident *irg_id = get_entity_ident(get_irg_entity(tirg));
971 fprintf(stderr, "No graph for function '%s' found\n", dumpfunction);
975 dump_ir_block_graph_file(irg, out);
982 /* assemble assembler and create object file */
983 char obj_tfile[1024];
984 if(mode == CompileAssemble || mode == CompileAssembleLink) {
985 const char *obj_outfile;
986 if(mode == CompileAssemble) {
988 obj_outfile = outname;
991 = make_temp_file(obj_tfile, sizeof(obj_tfile), "cc", ".o");
993 obj_outfile = obj_tfile;
996 assemble(obj_outfile, asm_tempfile);
999 /* link object file */
1000 if(mode == CompileAssembleLink) {
1001 do_link(outname, obj_tfile);
1004 obstack_free(&cppflags_obst, NULL);
1005 obstack_free(&ldflags_obst, NULL);
1006 obstack_free(&file_obst, NULL);
1015 exit_symbol_table();