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