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