5e66ff12ea00fa312f8af898898f4bac1c7d5db8
[cparser] / main.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
4  *
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.
9  *
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.
14  *
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
18  * 02111-1307, USA.
19  */
20 #include <config.h>
21
22 #define _GNU_SOURCE
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <stdbool.h>
27 #include <errno.h>
28 #include <string.h>
29 #include <assert.h>
30
31 #ifdef _WIN32
32
33 #include <fcntl.h>
34 #include <io.h>
35
36 /* no eXecute on Win32 */
37 #define X_OK 0
38 #define W_OK 2
39 #define R_OK 4
40
41 #define O_RDWR          _O_RDWR
42 #define O_CREAT         _O_CREAT
43 #define O_EXCL          _O_EXCL
44 #define O_BINARY        _O_BINARY
45
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)
53
54 #else
55 #include <unistd.h>
56 #define HAVE_MKSTEMP
57 #endif
58
59 #ifndef WITH_LIBCORE
60 #define WITH_LIBCORE
61 #endif
62
63 #include <libfirm/firm.h>
64 #include <libfirm/be.h>
65
66 #include "lexer.h"
67 #include "token_t.h"
68 #include "types.h"
69 #include "type_hash.h"
70 #include "parser.h"
71 #include "ast2firm.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 "revision.h"
79 #include "warning.h"
80
81 #ifndef PREPROCESSOR
82 #define PREPROCESSOR "cpp -std=c99 -U__WCHAR_TYPE__ -D__WCHAR_TYPE__=int -m32"
83 #endif
84
85 #ifndef LINKER
86 #define LINKER    "gcc -m32"
87 #endif
88
89 #ifndef ASSEMBLER
90 #define ASSEMBLER "as --32"
91 #endif
92
93 /** The current c mode/dialect. */
94 unsigned int c_mode = _C89|_C99|_GNUC;
95
96 /** The 'machine size', 16, 32 or 64 bit, 32bit is the default. */
97 unsigned int machine_size = 32;
98
99 /** true if the char type is signed. */
100 bool char_is_signed = true;
101
102 /** true for strict language checking. */
103 bool strict_mode = false;
104
105 /* to switch on printing of implicit casts */
106 extern bool print_implicit_casts;
107
108 /* to switch on printing of parenthesis to indicate operator precedence */
109 extern bool print_parenthesis;
110
111 static int            verbose;
112 static struct obstack cppflags_obst, ldflags_obst;
113
114 typedef struct file_list_entry_t file_list_entry_t;
115
116 struct file_list_entry_t {
117         const char        *filename;
118         file_list_entry_t *next;
119 };
120
121 #if defined(_DEBUG) || defined(FIRM_DEBUG)
122 /**
123  * Debug printf implementation.
124  *
125  * @param fmt  printf style format parameter
126  */
127 void dbg_printf(const char *fmt, ...)
128 {
129         va_list list;
130
131         if (firm_dump.debug_print) {
132                 va_start(list, fmt);
133                 vprintf(fmt, list);
134                 va_end(list);
135         }  /* if */
136 }
137 #endif /* defined(_DEBUG) || defined(FIRM_DEBUG) */
138
139 static void initialize_firm(void)
140 {
141         firm_early_init();
142
143         dump_consts_local(1);
144         dump_keepalive_edges(1);
145 }
146
147 static void get_output_name(char *buf, size_t buflen, const char *inputname,
148                             const char *newext)
149 {
150         size_t last_dot = 0xffffffff;
151         size_t i = 0;
152
153         if(inputname == NULL) {
154                 snprintf(buf, buflen, "a%s", newext);
155                 return;
156         }
157
158         for(const char *c = inputname; *c != 0; ++c) {
159                 if(*c == '.')
160                         last_dot = i;
161                 ++i;
162         }
163         if(last_dot == 0xffffffff)
164                 last_dot = i;
165
166         if(last_dot >= buflen)
167                 panic("filename too long");
168         memcpy(buf, inputname, last_dot);
169
170         size_t extlen = strlen(newext) + 1;
171         if(extlen + last_dot >= buflen)
172                 panic("filename too long");
173         memcpy(buf+last_dot, newext, extlen);
174 }
175
176 static translation_unit_t *do_parsing(FILE *const in, const char *const input_name)
177 {
178         lexer_open_stream(in, input_name);
179         translation_unit_t *unit = parse();
180         return unit;
181 }
182
183 static void lextest(FILE *in, const char *fname)
184 {
185         lexer_open_stream(in, fname);
186
187         do {
188                 lexer_next_preprocessing_token();
189                 print_token(stdout, &lexer_token);
190                 puts("");
191         } while(lexer_token.type != T_EOF);
192 }
193
194 static FILE *preprocess(FILE *in, const char *fname, bool to_stdout)
195 {
196         char buf[4096];
197         obstack_1grow(&cppflags_obst, '\0');
198         const char *flags = obstack_finish(&cppflags_obst);
199
200         if(in != stdin) {
201                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s %s", flags, fname);
202         } else {
203                 /* read from stdin */
204                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s -", flags);
205         }
206
207         if(verbose) {
208                 puts(buf);
209         }
210         if(to_stdout) {
211                 int res = system(buf);
212                 exit(res);
213         } else {
214                 FILE *f = popen(buf, "r");
215                 if(f == NULL) {
216                         fprintf(stderr, "invoking preprocessor failed\n");
217                         exit(1);
218                 }
219                 return f;
220         }
221 }
222
223 static void do_link(const char *out, const char *in)
224 {
225         char buf[4096];
226         obstack_1grow(&ldflags_obst, '\0');
227         const char *flags = obstack_finish(&ldflags_obst);
228
229         snprintf(buf, sizeof(buf), LINKER " %s -o %s %s", flags, out, in);
230         if(verbose) {
231                 puts(buf);
232         }
233         int err = system(buf);
234         if(err != 0) {
235                 fprintf(stderr, "linker reported an error\n");
236                 exit(1);
237         }
238 }
239
240 static void assemble(const char *out, const char *in)
241 {
242         char buf[4096];
243
244         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
245         if(verbose) {
246                 puts(buf);
247         }
248
249         int err = system(buf);
250         if(err != 0) {
251                 fprintf(stderr, "assembler reported an error\n");
252                 exit(1);
253         }
254 }
255
256 static const char *try_dir(const char *dir)
257 {
258         if(dir == NULL)
259                 return dir;
260         if(access(dir, R_OK | W_OK | X_OK) == 0)
261                 return dir;
262         return NULL;
263 }
264
265 static const char *get_tempdir(void)
266 {
267         static const char *tmpdir = NULL;
268
269         if(tmpdir != NULL)
270                 return tmpdir;
271
272         if(tmpdir == NULL)
273                 tmpdir = try_dir(getenv("TMPDIR"));
274         if(tmpdir == NULL)
275                 tmpdir = try_dir(getenv("TMP"));
276         if(tmpdir == NULL)
277                 tmpdir = try_dir(getenv("TEMP"));
278
279 #ifdef P_tmpdir
280         if(tmpdir == NULL)
281                 tmpdir = try_dir(P_tmpdir);
282 #endif
283
284         if(tmpdir == NULL)
285                 tmpdir = try_dir("/var/tmp");
286         if(tmpdir == NULL)
287                 tmpdir = try_dir("/usr/tmp");
288         if(tmpdir == NULL)
289                 tmpdir = try_dir("/tmp");
290
291         if(tmpdir == NULL)
292                 tmpdir = ".";
293
294         return tmpdir;
295 }
296
297 #ifndef HAVE_MKSTEMP
298 /* cheap and nasty mkstemp replacement */
299 static int mkstemp(char *templ)
300 {
301         mktemp(templ);
302         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
303 }
304 #endif
305
306 /**
307  * an own version of tmpnam, which: writes in a buffer, appends a user specified
308  * suffix, emits no warnings during linking (like glibc/gnu ld do for tmpnam)...
309  */
310 static FILE *make_temp_file(char *buffer, size_t buflen,
311                             const char *prefix, const char *suffix)
312 {
313         const char *tempdir = get_tempdir();
314
315         /* oh well... mkstemp doesn't accept a suffix after XXXXXX... */
316         (void) suffix;
317         suffix = "";
318
319         snprintf(buffer, buflen, "%s/%sXXXXXX%s", tempdir, prefix, suffix);
320
321         int fd = mkstemp(buffer);
322         if(fd == -1) {
323                 fprintf(stderr, "couldn't create temporary file: %s\n",
324                         strerror(errno));
325                 exit(1);
326         }
327         FILE *out = fdopen(fd, "w");
328         if(out == NULL) {
329                 fprintf(stderr, "couldn't create temporary file FILE*\n");
330                 exit(1);
331         }
332
333         return out;
334 }
335
336 /**
337  * Do the necessary lowering for compound parameters.
338  */
339 void lower_compound_params(void)
340 {
341         lower_params_t params;
342
343         params.def_ptr_alignment    = 4;
344         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
345         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
346         params.find_pointer_type    = NULL;
347         params.ret_compound_in_regs = NULL;
348         lower_calls_with_compounds(&params);
349 }
350
351 typedef enum compile_mode_t {
352         BenchmarkParser,
353         PreprocessOnly,
354         ParseOnly,
355         Compile,
356         CompileDump,
357         CompileAssemble,
358         CompileAssembleLink,
359         LexTest,
360         PrintAst,
361         PrintFluffy,
362         Link
363 } compile_mode_t;
364
365 static void usage(const char *argv0)
366 {
367         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
368 }
369
370 static void print_cparser_version(void) {
371         firm_version_t ver;
372         firm_get_version(&ver);
373
374         printf("cparser (%s) using libFirm (%u.%u",
375                 cparser_REVISION, ver.major, ver.minor);
376         if(ver.revision[0] != 0) {
377                 putchar(' ');
378                 fputs(ver.revision, stdout);
379         }
380         if(ver.build[0] != 0) {
381                 putchar(' ');
382                 fputs(ver.build, stdout);
383         }
384         puts(")\n");
385 }
386
387 int main(int argc, char **argv)
388 {
389         initialize_firm();
390
391         const char        *input        = NULL;
392         const char        *outname      = NULL;
393         const char        *dumpfunction = NULL;
394         compile_mode_t     mode         = CompileAssembleLink;
395         int                opt_level    = 1;
396         int                result       = EXIT_SUCCESS;
397         char               cpu_arch[16] = "ia32";
398         file_list_entry_t *c_files      = NULL;
399         file_list_entry_t *s_files      = NULL;
400         file_list_entry_t *o_files      = NULL;
401         struct obstack     file_obst;
402
403         obstack_init(&cppflags_obst);
404         obstack_init(&ldflags_obst);
405         obstack_init(&file_obst);
406
407 #define GET_ARG_AFTER(def, args)                                             \
408         def = &arg[sizeof(args)-1];                                              \
409         if(def[0] == '\0') {                                                     \
410                 ++i;                                                                 \
411                 if(i >= argc) {                                                      \
412                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
413                         argument_errors = true;                                          \
414                         break;                                                           \
415                 }                                                                    \
416                 def = argv[i];                                                       \
417                 if(def[0] == '-' && def[1] != '\0') {                                \
418                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
419                         argument_errors = true;                                          \
420                         continue;                                                        \
421                 }                                                                    \
422         }
423
424 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
425
426         /* early options parsing (find out optimisation level) */
427         for(int i = 1; i < argc; ++i) {
428                 const char *arg = argv[i];
429                 if(arg[0] != '-')
430                         continue;
431
432                 const char *option = &arg[1];
433                 if(option[0] == 'O') {
434                         sscanf(&option[1], "%d", &opt_level);
435                 }
436         }
437
438         /* apply optimisation level */
439         switch(opt_level) {
440         case 0:
441                 firm_option("no-opt");
442                 break;
443         case 1:
444                 firm_option("no-inline");
445                 break;
446         default:
447         case 4:
448                 firm_option("strict-aliasing");
449                 /* fallthrough */
450         case 3:
451                 firm_option("cond-eval");
452                 firm_option("if-conv");
453                 /* fallthrough */
454         case 2:
455                 firm_option("inline");
456                 firm_option("deconv");
457                 firm_be_option("omitfp");
458                 break;
459         }
460
461         /* parse rest of options */
462         bool help_displayed  = false;
463         bool argument_errors = false;
464         for(int i = 1; i < argc; ++i) {
465                 const char *arg = argv[i];
466                 if(arg[0] == '-' && arg[1] != 0) {
467                         /* an option */
468                         const char *option = &arg[1];
469                         if(option[0] == 'o') {
470                                 GET_ARG_AFTER(outname, "-o");
471                         } else if(option[0] == 'g') {
472                                 firm_be_option("stabs=yes");
473                                 firm_be_option("omitfp=no");
474                                 firm_be_option("ia32-nooptcc=yes");
475                         } else if(SINGLE_OPTION('c')) {
476                                 mode = CompileAssemble;
477                         } else if(SINGLE_OPTION('E')) {
478                                 mode = PreprocessOnly;
479                         } else if(SINGLE_OPTION('S')) {
480                                 mode = Compile;
481                         } else if(option[0] == 'O') {
482                                 continue;
483                         } else if(option[0] == 'I') {
484                                 const char *opt;
485                                 GET_ARG_AFTER(opt, "-I");
486                                 obstack_printf(&cppflags_obst, " -I%s", opt);
487                         } else if(option[0] == 'D') {
488                                 const char *opt;
489                                 GET_ARG_AFTER(opt, "-D");
490                                 obstack_printf(&cppflags_obst, " -D%s", opt);
491                         } else if(option[0] == 'U') {
492                                 const char *opt;
493                                 GET_ARG_AFTER(opt, "-U");
494                                 obstack_printf(&cppflags_obst, " -U%s", opt);
495                         } else if(option[0] == 'l') {
496                                 const char *opt;
497                                 GET_ARG_AFTER(opt, "-l");
498                                 obstack_printf(&ldflags_obst, " -l%s", opt);
499                         } else if(option[0] == 'L') {
500                                 const char *opt;
501                                 GET_ARG_AFTER(opt, "-L");
502                                 obstack_printf(&ldflags_obst, " -L%s", opt);
503                         } else if(SINGLE_OPTION('v')) {
504                                 verbose = 1;
505                         } else if(SINGLE_OPTION('w')) {
506                                 inhibit_all_warnings = true;
507                         } else if(option[0] == 'f') {
508                                 const char *opt;
509                                 GET_ARG_AFTER(opt, "-f");
510
511                                 if(strcmp(opt, "syntax-only") == 0) {
512                                         mode = ParseOnly;
513                                 } else if(strcmp(opt, "omit-frame-pointer") == 0) {
514                                         firm_be_option("omitfp");
515                                 } else if(strcmp(opt, "no-omit-frame-pointer") == 0) {
516                                         firm_be_option("omitfp=no");
517                                 } else {
518                                         int res = firm_option(opt);
519                                         if (res == 0) {
520                                                 fprintf(stderr, "error: unknown Firm option '-f %s'\n",
521                                                         opt);
522                                                 argument_errors = true;
523                                                 continue;
524                                         } else if (res == -1) {
525                                                 help_displayed = true;
526                                         }
527                                 }
528                         } else if(option[0] == 'b') {
529                                 const char *opt;
530                                 GET_ARG_AFTER(opt, "-b");
531                                 int res = firm_be_option(opt);
532                                 if (res == 0) {
533                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
534                                                 opt);
535                                         argument_errors = true;
536                                 } else if (res == -1) {
537                                         help_displayed = true;
538                                 } else {
539                                         if (strncmp(opt, "isa=", 4) == 0)
540                                                 strncpy(cpu_arch, opt, sizeof(cpu_arch));
541                                 }
542                         } else if(option[0] == 'W') {
543                                 set_warning_opt(&option[1]);
544                         } else if(option[0] == 'm') {
545                                 /* -m options */
546                                 const char *opt;
547                                 char arch_opt[64];
548
549                                 GET_ARG_AFTER(opt, "-m");
550                                 if(strncmp(opt, "arch=", 5) == 0) {
551                                         GET_ARG_AFTER(opt, "-march=");
552                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
553                                         int res = firm_be_option(arch_opt);
554                                         if (res == 0)
555                                                 argument_errors = true;
556                                         else {
557                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
558                                                 int res = firm_be_option(arch_opt);
559                                                 if (res == 0)
560                                                         argument_errors = true;
561                                         }
562                                 } else if(strncmp(opt, "tune=", 5) == 0) {
563                                         GET_ARG_AFTER(opt, "-mtune=");
564                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
565                                         int res = firm_be_option(arch_opt);
566                                         if (res == 0)
567                                                 argument_errors = true;
568                                 } else if(strncmp(opt, "cpu=", 4) == 0) {
569                                         GET_ARG_AFTER(opt, "-mcpu=");
570                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
571                                         int res = firm_be_option(arch_opt);
572                                         if (res == 0)
573                                                 argument_errors = true;
574                                 } else if(strncmp(opt, "fpmath=", 7) == 0) {
575                                         GET_ARG_AFTER(opt, "-mfpmath=");
576                                         if(strcmp(opt, "387") == 0)
577                                                 opt = "x87";
578                                         else if(strcmp(opt, "sse") == 0)
579                                                 opt = "sse2";
580                                         else {
581                                                 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
582                                                 argument_errors = true;
583                                         }
584                                         if(!argument_errors) {
585                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
586                                                 int res = firm_be_option(arch_opt);
587                                                 if (res == 0)
588                                                         argument_errors = true;
589                                         }
590                                 } else if(strncmp(opt, "preferred-stack-boundary=", 25) == 0) {
591                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
592                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
593                                         int res = firm_be_option(arch_opt);
594                                         if (res == 0)
595                                                 argument_errors = true;
596                                 } else if(strcmp(opt, "omit-leaf-frame-pointer") == 0) {
597                                         int res = firm_be_option("omitleaffp=1");
598                                         if (res == 0)
599                                                 argument_errors = true;
600                                 } else if(strcmp(opt, "no-omit-leaf-frame-pointer") == 0) {
601                                         int res = firm_be_option("omitleaffp=0");
602                                         if (res == 0)
603                                                 argument_errors = true;
604                                 } else {
605                                         char *endptr;
606                                         long int value = strtol(opt, &endptr, 10);
607                                         if (*endptr != '\0') {
608                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
609                                                 argument_errors = true;
610                                         }
611                                         if (value != 16 && value != 32 && value != 64) {
612                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
613                                                 argument_errors = true;
614                                         } else {
615                                                 machine_size = (unsigned int)value;
616                                         }
617                                 }
618                         } else if (option[0] == '\0') {
619                                 if(input != NULL) {
620                                         fprintf(stderr, "error: multiple input files specified\n");
621                                         argument_errors = true;
622                                 } else {
623                                         input = arg;
624                                 }
625                         } else if(strcmp(option, "pg") == 0) {
626                                 firm_be_option("-b gprof");
627                                 obstack_printf(&ldflags_obst, " -pg");
628                         } else if(strcmp(option, "pedantic") == 0) {
629                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
630                         } else if(strncmp(option, "std=", 4) == 0) {
631                                 if(strcmp(&option[4], "c99") == 0) {
632                                         c_mode = _C89|_C99;
633                                 } else if(strcmp(&option[4], "c89") == 0) {
634                                         c_mode = _C89;
635                                 } else if(strcmp(&option[4], "gnu99") == 0) {
636                                         c_mode = _C89|_C99|_GNUC;
637                                 } else if(strcmp(&option[4], "microsoft") == 0) {
638                                         c_mode = _C89|_C99|_MS;
639                                 } else
640                                         fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
641                         } else if(strcmp(option, "version") == 0) {
642                                 print_cparser_version();
643                         } else if (option[0] == '-') {
644                                 /* double dash option */
645                                 ++option;
646                                 if(strcmp(option, "gcc") == 0) {
647                                         c_mode |= _GNUC;
648                                 } else if(strcmp(option, "no-gcc") == 0) {
649                                         c_mode &= ~_GNUC;
650                                 } else if(strcmp(option, "ms") == 0) {
651                                         c_mode |= _MS;
652                                 } else if(strcmp(option, "no-ms") == 0) {
653                                         c_mode &= ~_MS;
654                                 } else if(strcmp(option, "signed-chars") == 0) {
655                                         char_is_signed = true;
656                                 } else if(strcmp(option, "unsigned-chars") == 0) {
657                                         char_is_signed = false;
658                                 } else if(strcmp(option, "strict") == 0) {
659                                         strict_mode = true;
660                                 } else if(strcmp(option, "lextest") == 0) {
661                                         mode = LexTest;
662                                 } else if(strcmp(option, "benchmark") == 0) {
663                                         mode = BenchmarkParser;
664                                 } else if(strcmp(option, "print-ast") == 0) {
665                                         mode = PrintAst;
666                                 } else if(strcmp(option, "print-implicit-cast") == 0) {
667                                         print_implicit_casts = true;
668                                 } else if(strcmp(option, "print-parenthesis") == 0) {
669                                         print_parenthesis = true;
670                                 } else if(strcmp(option, "print-fluffy") == 0) {
671                                         mode = PrintFluffy;
672                                 } else if(strcmp(option, "version") == 0) {
673                                         print_cparser_version();
674                                         exit(EXIT_SUCCESS);
675                                 } else if(strcmp(option, "dump-function") == 0) {
676                                         ++i;
677                                         if(i >= argc) {
678                                                 fprintf(stderr, "error: "
679                                                         "expected argument after '--dump-function'\n");
680                                                 argument_errors = true;
681                                                 break;
682                                         }
683                                         dumpfunction = argv[i];
684                                         mode         = CompileDump;
685                                 } else {
686                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
687                                         argument_errors = true;
688                                 }
689                         } else {
690                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
691                                 argument_errors = true;
692                         }
693                 } else {
694
695                         file_list_entry_t *entry
696                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
697                         entry->filename = arg;
698
699                         size_t len = strlen(arg);
700                         if (len < 2) {
701                                 if (arg[0] == '-') {
702                                         /* exception: '-' as name reads C from stdin */
703                                         entry->next = c_files;
704                                         c_files     = entry;
705                                         continue;
706                                 }
707                                 fprintf(stderr, "'%s': file format not recognized\n", input);
708                                 continue;
709                         }
710
711                         if (strcmp(arg+len-2, ".c") == 0) {
712                                 entry->next = c_files;
713                                 c_files     = entry;
714                         } else if (strcmp(arg+len-2, ".s") == 0) {
715                                 entry->next = s_files;
716                                 s_files     = entry;
717                         } else if (strcmp(arg+len-2, ".o") == 0) {
718                                 entry->next = o_files;
719                                 o_files     = entry;
720                         } else {
721                                 fprintf(stderr, "'%s': file format not recognized\n", input);
722                         }
723                 }
724         }
725
726         if (c_files == NULL && s_files == NULL && o_files != NULL) {
727                 mode = Link;
728         } else if (c_files != NULL && c_files->next == NULL) {
729                 input = c_files->filename;
730         } else {
731                 if (c_files == NULL) {
732                         fprintf(stderr, "error: no input files specified\n");
733                 } else {
734                         fprintf(stderr, "error: multiple input files specified\n");
735                 }
736                 argument_errors = true;
737         }
738
739         /* we do the lowering in ast2firm */
740         firm_opt.lower_bitfields = FALSE;
741
742         if (help_displayed) {
743                 return !argument_errors;
744         }
745         if (argument_errors) {
746                 usage(argv[0]);
747                 return 1;
748         }
749
750         gen_firm_init();
751         init_symbol_table();
752         init_tokens();
753         init_types();
754         init_typehash();
755         init_basic_types();
756         init_lexer();
757         init_ast();
758         init_parser();
759         init_ast2firm();
760
761         FILE *out = NULL;
762         char  outnamebuf[4096];
763         if(outname == NULL) {
764                 switch(mode) {
765                 case BenchmarkParser:
766                 case PrintAst:
767                 case PrintFluffy:
768                 case LexTest:
769                         if(outname == NULL)
770                                 outname = "-";
771                         break;
772                 case PreprocessOnly:
773                         break;
774                 case ParseOnly:
775                         break;
776                 case Compile:
777                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".s");
778                         outname = outnamebuf;
779                         break;
780                 case CompileAssemble:
781                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".o");
782                         outname = outnamebuf;
783                         break;
784                 case CompileDump:
785                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
786                                         ".vcg");
787                         outname = outnamebuf;
788                         break;
789                 case Link:
790                 case CompileAssembleLink:
791 #ifdef _WIN32
792                         /* Windows compiler typically derive the output name from
793                            the first source file */
794                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".exe");
795                         outname = outnamebuf;
796 #else
797                         outname = "a.out";
798 #endif
799                         break;
800                 }
801         }
802
803         if (mode == Link) {
804                 obstack_1grow(&ldflags_obst, '\0');
805                 const char *flags = obstack_finish(&ldflags_obst);
806
807                 obstack_printf(&file_obst, "%s", LINKER);
808
809                 for (file_list_entry_t *entry = o_files; entry != NULL;
810                                 entry = entry->next) {
811                         obstack_printf(&file_obst, " %s", entry->filename);
812                 }
813
814                 obstack_printf(&file_obst, " -o %s %s", outname, flags);
815
816                 char *buf = obstack_finish(&file_obst);
817
818                 if(verbose) {
819                         puts(buf);
820                 }
821                 int err = system(buf);
822                 if(err != 0) {
823                         fprintf(stderr, "linker reported an error\n");
824                         exit(1);
825                 }
826                 return 0;
827         }
828
829         if(outname != NULL) {
830                 if(strcmp(outname, "-") == 0) {
831                         out = stdout;
832                 } else {
833                         out = fopen(outname, "w");
834                         if(out == NULL) {
835                                 fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
836                                         strerror(errno));
837                                 return 1;
838                         }
839                 }
840         }
841
842         FILE *in;
843         if(input == NULL) {
844                 fprintf(stderr, "%s: no input files\n", argv[0]);
845                 return 1;
846         } else if(strcmp(input, "-") == 0) {
847                 in    = stdin;
848                 input = "<stdin>";
849         } else {
850                 in = fopen(input, "r");
851                 if(in == NULL) {
852                         fprintf(stderr, "Couldn't open '%s': %s\n", input, strerror(errno));
853                         return 1;
854                 }
855         }
856
857         if(mode == LexTest) {
858                 lextest(in, input);
859                 fclose(in);
860                 return 0;
861         }
862
863         FILE *preprocessed_in = preprocess(in, input, mode == PreprocessOnly);
864         translation_unit_t *const unit = do_parsing(preprocessed_in, input);
865         int res = pclose(preprocessed_in);
866         if(res != 0) {
867                 return res;
868         }
869
870         if(error_count > 0) {
871                 /* parsing failed because of errors */
872                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count, warning_count);
873                 result = EXIT_FAILURE;
874         } else if(warning_count > 0) {
875                 fprintf(stderr, "%u warning(s)\n", warning_count);
876         }
877
878         if(mode == BenchmarkParser) {
879                 return result;
880         }
881
882         /* prints the AST even if errors occurred */
883         if(mode == PrintAst) {
884                 type_set_output(out);
885                 ast_set_output(out);
886                 print_ast(unit);
887                 return result;
888         }
889
890         /* cannot handle other modes with errors */
891         if(result != EXIT_SUCCESS)
892                 return result;
893
894         if(mode == PrintFluffy) {
895                 type_set_output(out);
896                 ast_set_output(out);
897                 write_fluffy_decls(out, unit);
898         }
899
900         translation_unit_to_firm(unit);
901
902         if(mode == ParseOnly) {
903                 return 0;
904         }
905
906         FILE *asm_out;
907         char  asm_tempfile[1024];
908         if(mode == CompileDump) {
909                 asm_out = NULL;
910                 firm_be_opt.selection = BE_NONE;
911         } else if(mode == Compile) {
912                 asm_out = out;
913         } else {
914                 asm_out
915                         = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "cc", ".s");
916         }
917         gen_firm_finish(asm_out, input, /*c_mode=*/1, /*firm_const_exists=*/0);
918
919         if(mode == CompileDump) {
920                 /* find irg */
921                 ident    *id     = new_id_from_str(dumpfunction);
922                 ir_graph *irg    = NULL;
923                 int       n_irgs = get_irp_n_irgs();
924                 for(int i = 0; i < n_irgs; ++i) {
925                         ir_graph *tirg   = get_irp_irg(i);
926                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
927                         if(irg_id == id) {
928                                 irg = tirg;
929                                 break;
930                         }
931                 }
932
933                 if(irg == NULL) {
934                         fprintf(stderr, "No graph for function '%s' found\n", dumpfunction);
935                         return 1;
936                 }
937
938                 dump_ir_block_graph_file(irg, out);
939                 fclose(out);
940                 return 0;
941         }
942
943         fclose(asm_out);
944
945         /* assemble assembler and create object file */
946         char obj_tfile[1024];
947         if(mode == CompileAssemble || mode == CompileAssembleLink) {
948                 const char *obj_outfile;
949                 if(mode == CompileAssemble) {
950                         fclose(out);
951                         obj_outfile = outname;
952                 } else {
953                         FILE *tempf
954                                 = make_temp_file(obj_tfile, sizeof(obj_tfile), "cc", ".o");
955                         fclose(tempf);
956                         obj_outfile = obj_tfile;
957                 }
958
959                 assemble(obj_outfile, asm_tempfile);
960         }
961
962         /* link object file */
963         if(mode == CompileAssembleLink) {
964                 do_link(outname, obj_tfile);
965         }
966
967         obstack_free(&cppflags_obst, NULL);
968         obstack_free(&ldflags_obst, NULL);
969         obstack_free(&file_obst, NULL);
970
971         exit_ast2firm();
972         exit_parser();
973         exit_ast();
974         exit_lexer();
975         exit_typehash();
976         exit_types();
977         exit_tokens();
978         exit_symbol_table();
979         return 0;
980 }