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