Accept -Wno-all, -Wno-extra and -Wno-unused like GCC.
[cparser] / main.c
1 #include <config.h>
2
3 #define _GNU_SOURCE
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdbool.h>
8 #include <errno.h>
9 #include <string.h>
10 #include <assert.h>
11
12 #ifdef _WIN32
13
14 #include <fcntl.h>
15 #include <io.h>
16
17 /* no eXecute on Win32 */
18 #define X_OK 0
19 #define W_OK 2
20 #define R_OK 4
21
22 #define O_RDWR          _O_RDWR
23 #define O_CREAT         _O_CREAT
24 #define O_EXCL          _O_EXCL
25 #define O_BINARY        _O_BINARY
26
27 /* remap some names, we are not in the POSIX world */
28 #define access(fname, mode)      _access(fname, mode)
29 #define mktemp(tmpl)             _mktemp(tmpl)
30 #define open(fname, oflag, mode) _open(fname, oflag, mode)
31 #define fdopen(fd, mode)         _fdopen(fd, mode)
32 #define popen(cmd, mode)         _popen(cmd, mode)
33 #define pclose(file)             _pclose(file)
34
35 #else
36 #include <unistd.h>
37 #define HAVE_MKSTEMP
38 #endif
39
40 #ifndef WITH_LIBCORE
41 #define WITH_LIBCORE
42 #endif
43
44 #include <libfirm/firm.h>
45 #include <libfirm/be.h>
46
47 #include "lexer.h"
48 #include "token_t.h"
49 #include "types.h"
50 #include "type_hash.h"
51 #include "parser.h"
52 #include "ast2firm.h"
53 #include "diagnostic.h"
54 #include "lang_features.h"
55 #include "driver/firm_opt.h"
56 #include "driver/firm_cmdline.h"
57 #include "adt/error.h"
58 #include "write_fluffy.h"
59 #include "revision.h"
60 #include "warning.h"
61
62 #ifndef PREPROCESSOR
63 #define PREPROCESSOR "cpp -std=c99 -U__WCHAR_TYPE__ -D__WCHAR_TYPE__=int"
64 #endif
65
66 #ifndef LINKER
67 #define LINKER    "gcc -m32"
68 #endif
69
70 #ifndef ASSEMBLER
71 #define ASSEMBLER "as --32"
72 #endif
73
74 /** The current c mode/dialect. */
75 unsigned int c_mode = _C89|_C99|_GNUC;
76
77 /** The 'machine size', 16, 32 or 64 bit, 32bit is the default. */
78 unsigned int machine_size = 32;
79
80 /** true if the char type is signed. */
81 bool char_is_signed = true;
82
83 /** true for strict language checking. */
84 bool strict_mode = false;
85
86 static int            verbose;
87 static struct obstack cppflags_obst, ldflags_obst;
88
89 #if defined(_DEBUG) || defined(FIRM_DEBUG)
90 /**
91  * Debug printf implementation.
92  *
93  * @param fmt  printf style format parameter
94  */
95 void dbg_printf(const char *fmt, ...)
96 {
97         va_list list;
98
99         if (firm_dump.debug_print) {
100                 va_start(list, fmt);
101                 vprintf(fmt, list);
102                 va_end(list);
103         }  /* if */
104 }
105 #endif /* defined(_DEBUG) || defined(FIRM_DEBUG) */
106
107 static void initialize_firm(void)
108 {
109         firm_early_init();
110
111         dump_consts_local(1);
112         dump_keepalive_edges(1);
113 }
114
115 static void get_output_name(char *buf, size_t buflen, const char *inputname,
116                             const char *newext)
117 {
118         size_t last_dot = 0xffffffff;
119         size_t i = 0;
120
121         if(inputname == NULL) {
122                 snprintf(buf, buflen, "a%s", newext);
123                 return;
124         }
125
126         for(const char *c = inputname; *c != 0; ++c) {
127                 if(*c == '.')
128                         last_dot = i;
129                 ++i;
130         }
131         if(last_dot == 0xffffffff)
132                 last_dot = i;
133
134         if(last_dot >= buflen)
135                 panic("filename too long");
136         memcpy(buf, inputname, last_dot);
137
138         size_t extlen = strlen(newext) + 1;
139         if(extlen + last_dot >= buflen)
140                 panic("filename too long");
141         memcpy(buf+last_dot, newext, extlen);
142 }
143
144 static translation_unit_t *do_parsing(FILE *const in, const char *const input)
145 {
146         lexer_open_stream(in, input);
147         translation_unit_t *unit = parse();
148         return unit;
149 }
150
151 static void lextest(FILE *in, const char *fname)
152 {
153         lexer_open_stream(in, fname);
154
155         do {
156                 lexer_next_preprocessing_token();
157                 print_token(stdout, &lexer_token);
158                 puts("");
159         } while(lexer_token.type != T_EOF);
160 }
161
162 static FILE* preprocess(FILE* in, const char *fname)
163 {
164         char buf[4096];
165         const char *flags = obstack_finish(&cppflags_obst);
166
167         if(in != stdin) {
168                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s %s", flags, fname);
169         } else {
170                 /* read from stdin */
171                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s -", flags);
172         }
173
174         if(verbose) {
175                 puts(buf);
176         }
177         FILE* f = popen(buf, "r");
178         if (f == NULL) {
179                 fprintf(stderr, "invoking preprocessor failed\n");
180                 exit(1);
181         }
182         return f;
183 }
184
185 static void do_link(const char *out, const char *in)
186 {
187         char buf[4096];
188         const char *flags = obstack_finish(&ldflags_obst);
189
190         snprintf(buf, sizeof(buf), LINKER " %s -o %s %s", flags, out, in);
191         if(verbose) {
192                 puts(buf);
193         }
194         int err = system(buf);
195         if(err != 0) {
196                 fprintf(stderr, "linker reported an error\n");
197                 exit(1);
198         }
199 }
200
201 static void assemble(const char *out, const char *in)
202 {
203         char buf[4096];
204
205         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
206         if(verbose) {
207                 puts(buf);
208         }
209
210         int err = system(buf);
211         if(err != 0) {
212                 fprintf(stderr, "assembler reported an error\n");
213                 exit(1);
214         }
215 }
216
217 static const char *try_dir(const char *dir)
218 {
219         if(dir == NULL)
220                 return dir;
221         if(access(dir, R_OK | W_OK | X_OK) == 0)
222                 return dir;
223         return NULL;
224 }
225
226 static const char *get_tempdir(void)
227 {
228         static const char *tmpdir = NULL;
229
230         if(tmpdir != NULL)
231                 return tmpdir;
232
233         if(tmpdir == NULL)
234                 tmpdir = try_dir(getenv("TMPDIR"));
235         if(tmpdir == NULL)
236                 tmpdir = try_dir(getenv("TMP"));
237         if(tmpdir == NULL)
238                 tmpdir = try_dir(getenv("TEMP"));
239
240 #ifdef P_tmpdir
241         if(tmpdir == NULL)
242                 tmpdir = try_dir(P_tmpdir);
243 #endif
244
245         if(tmpdir == NULL)
246                 tmpdir = try_dir("/var/tmp");
247         if(tmpdir == NULL)
248                 tmpdir = try_dir("/usr/tmp");
249         if(tmpdir == NULL)
250                 tmpdir = try_dir("/tmp");
251
252         if(tmpdir == NULL)
253                 tmpdir = ".";
254
255         return tmpdir;
256 }
257
258 #ifndef HAVE_MKSTEMP
259 /* cheap and nasty mkstemp replacement */
260 static int mkstemp(char *templ)
261 {
262         mktemp(templ);
263         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
264 }
265 #endif
266
267 /**
268  * an own version of tmpnam, which: writes in a buffer, appends a user specified
269  * suffix, emits no warnings during linking (like glibc/gnu ld do for tmpnam)...
270  */
271 static FILE *make_temp_file(char *buffer, size_t buflen,
272                             const char *prefix, const char *suffix)
273 {
274         const char *tempdir = get_tempdir();
275
276         /* oh well... mkstemp doesn't accept a suffix after XXXXXX... */
277         (void) suffix;
278         suffix = "";
279
280         snprintf(buffer, buflen, "%s/%sXXXXXX%s", tempdir, prefix, suffix);
281
282         int fd = mkstemp(buffer);
283         if(fd == -1) {
284                 fprintf(stderr, "couldn't create temporary file: %s\n",
285                         strerror(errno));
286                 exit(1);
287         }
288         FILE *out = fdopen(fd, "w");
289         if(out == NULL) {
290                 fprintf(stderr, "couldn't create temporary file FILE*\n");
291                 exit(1);
292         }
293
294         return out;
295 }
296
297 /**
298  * Do the necessary lowering for compound parameters.
299  */
300 void lower_compound_params(void)
301 {
302         lower_params_t params;
303
304         params.def_ptr_alignment    = 4;
305         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
306         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
307         params.find_pointer_type    = NULL;
308         params.ret_compound_in_regs = NULL;
309         lower_calls_with_compounds(&params);
310 }
311
312 typedef enum compile_mode_t {
313         ParseOnly,
314         Compile,
315         CompileDump,
316         CompileAssemble,
317         CompileAssembleLink,
318         LexTest,
319         PrintAst,
320         PrintFluffy
321 } compile_mode_t;
322
323 static void usage(const char *argv0)
324 {
325         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
326 }
327
328 int main(int argc, char **argv)
329 {
330         initialize_firm();
331
332         const char     *input        = NULL;
333         const char     *outname      = NULL;
334         const char     *dumpfunction = NULL;
335         compile_mode_t  mode         = CompileAssembleLink;
336
337         obstack_init(&cppflags_obst);
338         obstack_init(&ldflags_obst);
339
340 #define GET_ARG_AFTER(def, args)                                             \
341         def = &arg[sizeof(args)-1];                                              \
342         if(def[0] == '\0') {                                                     \
343                 ++i;                                                                 \
344                 if(i >= argc) {                                                      \
345                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
346                         argument_errors = true;                                          \
347                         break;                                                           \
348                 }                                                                    \
349                 def = argv[i];                                                       \
350                 if(def[0] == '-' && def[1] != '\0') {                                \
351                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
352                         argument_errors = true;                                          \
353                         continue;                                                        \
354                 }                                                                    \
355         }
356
357 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
358
359         bool help_displayed  = false;
360         bool argument_errors = false;
361         for(int i = 1; i < argc; ++i) {
362                 const char *arg = argv[i];
363                 if(arg[0] == '-') {
364                         /* an option */
365                         const char *option = &arg[1];
366                         if(option[0] == 'o') {
367                                 GET_ARG_AFTER(outname, "-o");
368                         } else if(SINGLE_OPTION('c')) {
369                                 mode = CompileAssemble;
370                         } else if(SINGLE_OPTION('S')) {
371                                 mode = Compile;
372                         } else if(option[0] == 'I') {
373                                 const char *opt;
374                                 GET_ARG_AFTER(opt, "-I");
375                                 obstack_printf(&cppflags_obst, " -I%s", opt);
376                         } else if(option[0] == 'D') {
377                                 const char *opt;
378                                 GET_ARG_AFTER(opt, "-D");
379                                 obstack_printf(&cppflags_obst, " -D%s", opt);
380                         } else if(option[0] == 'U') {
381                                 const char *opt;
382                                 GET_ARG_AFTER(opt, "-U");
383                                 obstack_printf(&cppflags_obst, " -U%s", opt);
384                         } else if(option[0] == 'l') {
385                                 const char *opt;
386                                 GET_ARG_AFTER(opt, "-l");
387                                 obstack_printf(&ldflags_obst, " -l%s", opt);
388                         } else if(option[0] == 'L') {
389                                 const char *opt;
390                                 GET_ARG_AFTER(opt, "-L");
391                                 obstack_printf(&ldflags_obst, " -L%s", opt);
392                         } else if(SINGLE_OPTION('v')) {
393                                 verbose = 1;
394                         } else if(SINGLE_OPTION('w')) {
395                                 inhibit_all_warnings = true;
396                         } else if(option[0] == 'f') {
397                                 const char *opt;
398                                 GET_ARG_AFTER(opt, "-f");
399
400                                 if(strcmp(opt, "syntax-only") == 0) {
401                                         mode = ParseOnly;
402                                 } else if(strcmp(opt, "omit-frame-pointer") == 0) {
403                                         firm_be_option("omitfp");
404                                 } else if(strcmp(opt, "no-omit-frame-pointer") == 0) {
405                                         firm_be_option("omitfp=no");
406                                 } else {
407                                         int res = firm_option(opt);
408                                         if (res == 0) {
409                                                 fprintf(stderr, "error: unknown Firm option '-f %s'\n",
410                                                         opt);
411                                                 argument_errors = true;
412                                                 continue;
413                                         } else if (res == -1) {
414                                                 help_displayed = true;
415                                         }
416                                 }
417                         } else if(option[0] == 'b') {
418                                 const char *opt;
419                                 GET_ARG_AFTER(opt, "-b");
420                                 int res = firm_be_option(opt);
421                                 if (res == 0) {
422                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
423                                                 opt);
424                                         argument_errors = true;
425                                 } else if (res == -1) {
426                                         help_displayed = true;
427                                 }
428                         } else if(option[0] == 'W') {
429                                 set_warning_opt(&option[1]);
430                         } else if(option[0] == 'm') {
431                                 const char *opt;
432                                 GET_ARG_AFTER(opt, "-m");
433                                 char *endptr;
434                                 long int value = strtol(opt, &endptr, 10);
435                                 if (*endptr != '\0') {
436                                         fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
437                                         argument_errors = true;
438                                 }
439                                 if (value != 16 && value != 32 && value != 64) {
440                                         fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
441                                         argument_errors = true;
442                                 } else {
443                                         machine_size = (unsigned int)value;
444                                 }
445                         } else if (option[0] == '\0') {
446                                 if(input != NULL) {
447                                         fprintf(stderr, "error: multiple input files specified\n");
448                                         argument_errors = true;
449                                 } else {
450                                         input = arg;
451                                 }
452                         } else if(strcmp(option, "pedantic") == 0) {
453                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
454                         } else if(option[0] == 'O' ||
455                                   option[0] == 'g' ||
456                                   strncmp(option, "std=", 4) == 0) {
457                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
458                         } else if (option[0] == '-') {
459                                 /* double dash option */
460                                 ++option;
461                                 if(strcmp(option, "gcc") == 0) {
462                                         c_mode |= _GNUC;
463                                 } else if(strcmp(option, "no-gcc") == 0) {
464                                         c_mode &= ~_GNUC;
465                                 } else if(strcmp(option, "ms") == 0) {
466                                         c_mode |= _MS;
467                                 } else if(strcmp(option, "no-ms") == 0) {
468                                         c_mode &= ~_MS;
469                                 } else if(strcmp(option, "signed-chars") == 0) {
470                                         char_is_signed = true;
471                                 } else if(strcmp(option, "unsigned-chars") == 0) {
472                                         char_is_signed = false;
473                                 } else if(strcmp(option, "strict") == 0) {
474                                         strict_mode = true;
475                                 } else if(strcmp(option, "lextest") == 0) {
476                                         mode = LexTest;
477                                 } else if(strcmp(option, "print-ast") == 0) {
478                                         mode = PrintAst;
479                                 } else if(strcmp(option, "print-fluffy") == 0) {
480                                         mode = PrintFluffy;
481                                 } else if(strcmp(option, "version") == 0) {
482                                         firm_version_t ver;
483                                         firm_get_version(&ver);
484                                         printf("cparser (%d.%d %s) using libFirm (%u.%u", 0, 1, cparser_REVISION, ver.major, ver.minor);
485                                         if(ver.revision[0] != 0) {
486                                                 putchar(' ');
487                                                 fputs(ver.revision, stdout);
488                                         }
489                                         if(ver.build[0] != 0) {
490                                                 putchar(' ');
491                                                 fputs(ver.build, stdout);
492                                         }
493                                         puts(")\n");
494                                         exit(EXIT_SUCCESS);
495                                 } else if(strcmp(option, "dump-function") == 0) {
496                                         ++i;
497                                         if(i >= argc) {
498                                                 fprintf(stderr, "error: "
499                                                         "expected argument after '--dump-function'\n");
500                                                 argument_errors = true;
501                                                 break;
502                                         }
503                                         dumpfunction = argv[i];
504                                         mode         = CompileDump;
505                                 } else {
506                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
507                                         argument_errors = true;
508                                 }
509                         } else {
510                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
511                                 argument_errors = true;
512                         }
513                 } else {
514                         if(input != NULL) {
515                                 fprintf(stderr, "error: multiple input files specified\n");
516                                 argument_errors = true;
517                         } else {
518                                 input = arg;
519                         }
520                 }
521         }
522
523         /* we do the lowering in ast2firm */
524         firm_opt.lower_bitfields = FALSE;
525
526         if(help_displayed) {
527                 return !argument_errors;
528         }
529         if(argument_errors) {
530                 usage(argv[0]);
531                 return 1;
532         }
533
534         gen_firm_init();
535         init_symbol_table();
536         init_tokens();
537         init_types();
538         init_typehash();
539         init_basic_types();
540         init_lexer();
541         init_ast();
542         init_parser();
543         init_ast2firm();
544
545         FILE *out = NULL;
546         char  outnamebuf[4096];
547         if(outname == NULL) {
548                 switch(mode) {
549                 case PrintAst:
550                 case PrintFluffy:
551                 case LexTest:
552                         if(outname == NULL)
553                                 outname = "-";
554                         break;
555                 case ParseOnly:
556                         break;
557                 case Compile:
558                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".s");
559                         outname = outnamebuf;
560                         break;
561                 case CompileAssemble:
562                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".o");
563                         outname = outnamebuf;
564                         break;
565                 case CompileDump:
566                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
567                                         ".vcg");
568                         outname = outnamebuf;
569                         break;
570                 case CompileAssembleLink:
571                         outname = "a.out";
572                         break;
573                 }
574         }
575
576         if(outname != NULL) {
577                 if(strcmp(outname, "-") == 0) {
578                         out = stdout;
579                 } else {
580                         out = fopen(outname, "w");
581                         if(out == NULL) {
582                                 fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
583                                         strerror(errno));
584                                 return 1;
585                         }
586                 }
587         }
588
589         FILE *in;
590         if(input == NULL) {
591                 fprintf(stderr, "%s: no input files\n", argv[0]);
592                 return 1;
593         } else if(strcmp(input, "-") == 0) {
594                 in    = stdin;
595                 input = "<stdin>";
596         } else {
597                 in = fopen(input, "r");
598                 if(in == NULL) {
599                         fprintf(stderr, "Couldn't open '%s': %s\n", input, strerror(errno));
600                         return 1;
601                 }
602         }
603
604         if(mode == LexTest) {
605                 lextest(in, input);
606                 fclose(in);
607                 return 0;
608         }
609
610         FILE *preprocessed_in = preprocess(in, input);
611         translation_unit_t *const unit = do_parsing(preprocessed_in, input);
612         int result = pclose(preprocessed_in);
613         if(result != 0) {
614                 return result;
615         }
616         if(unit == NULL) {
617                 /* parsing failed because of errors */
618                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count, warning_count);
619                 return EXIT_FAILURE;
620         }
621         if (warning_count > 0) {
622                 fprintf(stderr, "%u warning(s)\n", warning_count);
623         }
624
625         if(mode == PrintAst) {
626                 type_set_output(out);
627                 ast_set_output(out);
628                 print_ast(unit);
629                 return 0;
630         }
631         if(mode == PrintFluffy) {
632                 type_set_output(out);
633                 ast_set_output(out);
634                 write_fluffy_decls(out, unit);
635         }
636
637         translation_unit_to_firm(unit);
638
639         if(mode == ParseOnly) {
640                 return 0;
641         }
642
643         FILE *asm_out;
644         char  asm_tempfile[1024];
645         if(mode == CompileDump) {
646                 asm_out = NULL;
647                 firm_be_opt.selection = BE_NONE;
648         } else if(mode == Compile) {
649                 asm_out = out;
650         } else {
651                 asm_out
652                         = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "cc", ".s");
653         }
654         gen_firm_finish(asm_out, input, /*c_mode=*/1, /*firm_const_exists=*/0);
655
656         if(mode == CompileDump) {
657                 /* find irg */
658                 ident    *id     = new_id_from_str(dumpfunction);
659                 ir_graph *irg    = NULL;
660                 int       n_irgs = get_irp_n_irgs();
661                 for(int i = 0; i < n_irgs; ++i) {
662                         ir_graph *tirg   = get_irp_irg(i);
663                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
664                         if(irg_id == id) {
665                                 irg = tirg;
666                                 break;
667                         }
668                 }
669
670                 if(irg == NULL) {
671                         fprintf(stderr, "No graph for function '%s' found\n", dumpfunction);
672                         return 1;
673                 }
674
675                 dump_ir_block_graph_file(irg, out);
676                 fclose(out);
677                 return 0;
678         }
679
680         fclose(asm_out);
681
682         /* assemble assembler and create object file */
683         char obj_tfile[1024];
684         if(mode == CompileAssemble || mode == CompileAssembleLink) {
685                 const char *obj_outfile;
686                 if(mode == CompileAssemble) {
687                         fclose(out);
688                         obj_outfile = outname;
689                 } else {
690                         FILE *tempf
691                                 = make_temp_file(obj_tfile, sizeof(obj_tfile), "cc", ".o");
692                         fclose(tempf);
693                         obj_outfile = obj_tfile;
694                 }
695
696                 assemble(obj_outfile, asm_tempfile);
697         }
698
699         /* link object file */
700         if(mode == CompileAssembleLink) {
701                 do_link(outname, obj_tfile);
702         }
703
704         obstack_free(&cppflags_obst, NULL);
705         obstack_free(&ldflags_obst, NULL);
706
707         exit_ast2firm();
708         exit_parser();
709         exit_ast();
710         exit_lexer();
711         exit_typehash();
712         exit_types();
713         exit_tokens();
714         exit_symbol_table();
715         return 0;
716 }