- add FE support for MS _AddressOfReturnAddress()
[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 #define unlink(filename)         _unlink(filename)
54
55 #else
56 #include <unistd.h>
57 #define HAVE_MKSTEMP
58 #endif
59
60 #include <libfirm/firm.h>
61 #include <libfirm/be.h>
62
63 #include "lexer.h"
64 #include "token_t.h"
65 #include "types.h"
66 #include "type_hash.h"
67 #include "parser.h"
68 #include "type_t.h"
69 #include "ast2firm.h"
70 #include "diagnostic.h"
71 #include "lang_features.h"
72 #include "driver/firm_opt.h"
73 #include "driver/firm_cmdline.h"
74 #include "adt/error.h"
75 #include "wrappergen/write_fluffy.h"
76 #include "wrappergen/write_caml.h"
77 #include "wrappergen/write_jna.h"
78 #include "revision.h"
79 #include "warning.h"
80 #include "mangle.h"
81
82 #ifndef PREPROCESSOR
83 #ifndef __WIN32__
84 #define PREPROCESSOR "gcc -E -std=c99 -m32 -U__STRICT_ANSI__"
85 #else
86 #define PREPROCESSOR "cpp -std=c99 -m32 -U__STRICT_ANSI__"
87 #endif
88 #endif
89
90 #ifndef LINKER
91 #define LINKER    "gcc -m32"
92 #endif
93
94 #ifndef ASSEMBLER
95 #ifdef __APPLE__
96 #define ASSEMBLER "gcc -c -xassembler"
97 #else
98 #define ASSEMBLER "as --32"
99 #endif
100 #endif
101
102 /** The current c mode/dialect. */
103 unsigned int c_mode = _C89 | _ANSI | _C99 | _GNUC;
104
105 /** The 'machine size', 16, 32 or 64 bit, 32bit is the default. */
106 unsigned int machine_size = 32;
107
108 /** true if the char type is signed. */
109 bool char_is_signed = true;
110
111 /** true for strict language checking. */
112 bool strict_mode = false;
113
114 /** use builtins for some libc functions */
115 bool use_builtins = false;
116
117 /** we have extern function with const attribute. */
118 bool have_const_functions = false;
119
120 atomic_type_kind_t wchar_atomic_kind = ATOMIC_TYPE_INT;
121
122 /* to switch on printing of implicit casts */
123 extern bool print_implicit_casts;
124
125 /* to switch on printing of parenthesis to indicate operator precedence */
126 extern bool print_parenthesis;
127
128 static int             verbose;
129 static struct obstack  cppflags_obst, ldflags_obst;
130 static char            dep_target[1024];
131 static const char     *outname;
132
133 typedef struct file_list_entry_t file_list_entry_t;
134
135 typedef enum filetype_t {
136         FILETYPE_AUTODETECT,
137         FILETYPE_C,
138         FILETYPE_PREPROCESSED_C,
139         FILETYPE_CXX,
140         FILETYPE_PREPROCESSED_CXX,
141         FILETYPE_ASSEMBLER,
142         FILETYPE_PREPROCESSED_ASSEMBLER,
143         FILETYPE_OBJECT,
144         FILETYPE_UNKNOWN
145 } filetype_t;
146
147 struct file_list_entry_t {
148         const char  *name; /**< filename or NULL for stdin */
149         filetype_t   type;
150         file_list_entry_t *next;
151 };
152
153 static file_list_entry_t *temp_files;
154
155 #if defined(_DEBUG) || defined(FIRM_DEBUG)
156 /**
157  * Debug printf implementation.
158  *
159  * @param fmt  printf style format parameter
160  */
161 void dbg_printf(const char *fmt, ...)
162 {
163         va_list list;
164
165         if (firm_dump.debug_print) {
166                 va_start(list, fmt);
167                 vprintf(fmt, list);
168                 va_end(list);
169         }  /* if */
170 }
171 #endif /* defined(_DEBUG) || defined(FIRM_DEBUG) */
172
173 static void initialize_firm(void)
174 {
175         firm_early_init();
176
177         dump_consts_local(1);
178         dump_keepalive_edges(1);
179 }
180
181 static void get_output_name(char *buf, size_t buflen, const char *inputname,
182                             const char *newext)
183 {
184         if (inputname == NULL)
185                 inputname = "a";
186
187         char const *const last_slash = strrchr(inputname, '/');
188         char const *const filename   =
189                 last_slash != NULL ? last_slash + 1 : inputname;
190         char const *const last_dot   = strrchr(filename, '.');
191         char const *const name_end   =
192                 last_dot != NULL ? last_dot : strchr(filename, '\0');
193
194         int const len = snprintf(buf, buflen, "%.*s%s",
195                         (int)(name_end - filename), filename, newext);
196 #ifdef _WIN32
197         if (len < 0 || buflen <= (size_t)len)
198 #else
199         if (buflen <= (size_t)len)
200 #endif
201                 panic("filename too long");
202 }
203
204 #include "builtins.h"
205
206 static translation_unit_t *do_parsing(FILE *const in, const char *const input_name)
207 {
208         start_parsing();
209
210         if (use_builtins) {
211                 lexer_open_buffer(builtins, sizeof(builtins)-1, "<builtin>");
212                 parse();
213         }
214
215         lexer_open_stream(in, input_name);
216         parse();
217
218         translation_unit_t *unit = finish_parsing();
219         return unit;
220 }
221
222 static void lextest(FILE *in, const char *fname)
223 {
224         lexer_open_stream(in, fname);
225
226         do {
227                 lexer_next_preprocessing_token();
228                 print_token(stdout, &lexer_token);
229                 putchar('\n');
230         } while (lexer_token.type != T_EOF);
231 }
232
233 static void add_flag(struct obstack *obst, const char *format, ...)
234 {
235         char buf[4096];
236         va_list ap;
237
238         va_start(ap, format);
239 #ifdef _WIN32
240         int len =
241 #endif
242                 vsnprintf(buf, sizeof(buf), format, ap);
243         va_end(ap);
244
245         obstack_1grow(obst, ' ');
246 #ifdef _WIN32
247         obstack_1grow(obst, '"');
248         obstack_grow(obst, buf, len);
249         obstack_1grow(obst, '"');
250 #else
251         /* escape stuff... */
252         for (char *c = buf; *c != '\0'; ++c) {
253                 switch(*c) {
254                 case ' ':
255                 case '"':
256                 case '$':
257                 case '&':
258                 case '(':
259                 case ')':
260                 case ';':
261                 case '<':
262                 case '>':
263                 case '\'':
264                 case '\\':
265                 case '\n':
266                 case '\r':
267                 case '\t':
268                 case '`':
269                 case '|':
270                         obstack_1grow(obst, '\\');
271                         /* FALLTHROUGH */
272                 default:
273                         obstack_1grow(obst, *c);
274                         break;
275                 }
276         }
277 #endif
278 }
279
280 static const char *type_to_string(type_t *type)
281 {
282         assert(type->kind == TYPE_ATOMIC);
283         return get_atomic_kind_name(type->atomic.akind);
284 }
285
286 static FILE *preprocess(const char *fname)
287 {
288         obstack_1grow(&cppflags_obst, '\0');
289         const char *flags = obstack_finish(&cppflags_obst);
290
291         obstack_printf(&cppflags_obst, "%s", PREPROCESSOR);
292
293         /* setup default defines */
294         add_flag(&cppflags_obst, "-U__WCHAR_TYPE__");
295         add_flag(&cppflags_obst, "-D__WCHAR_TYPE__=%s", type_to_string(type_wchar_t));
296         add_flag(&cppflags_obst, "-U__SIZE_TYPE__");
297         add_flag(&cppflags_obst, "-D__SIZE_TYPE__=%s", type_to_string(type_size_t));
298
299         /* TODO hack... */
300         add_flag(&cppflags_obst, "-D__builtin_abort=abort");
301         add_flag(&cppflags_obst, "-D__builtin_abs=abs");
302         add_flag(&cppflags_obst, "-D__builtin_exit=exit");
303         add_flag(&cppflags_obst, "-D__builtin_malloc=malloc");
304         add_flag(&cppflags_obst, "-D__builtin_memcmp=memcmp");
305         add_flag(&cppflags_obst, "-D__builtin_memcpy=memcpy");
306         add_flag(&cppflags_obst, "-D__builtin_memset=memset");
307         add_flag(&cppflags_obst, "-D__builtin_strlen=strlen");
308         add_flag(&cppflags_obst, "-D__builtin_strcmp=strcmp");
309         add_flag(&cppflags_obst, "-D__builtin_strcpy=strcpy");
310
311         /* handle dependency generation */
312         if (dep_target[0] != '\0') {
313                 add_flag(&cppflags_obst, "-MF");
314                 add_flag(&cppflags_obst, dep_target);
315                 if (outname != NULL) {
316                                 add_flag(&cppflags_obst, "-MQ");
317                                 add_flag(&cppflags_obst, outname);
318                 }
319         }
320         if (flags[0] != '\0') {
321                 obstack_printf(&cppflags_obst, " %s", flags);
322         }
323         add_flag(&cppflags_obst, fname);
324
325         obstack_1grow(&cppflags_obst, '\0');
326         const char *buf = obstack_finish(&cppflags_obst);
327         if (verbose) {
328                 puts(buf);
329         }
330
331         FILE *f = popen(buf, "r");
332         if (f == NULL) {
333                 fprintf(stderr, "invoking preprocessor failed\n");
334                 exit(1);
335         }
336
337         return f;
338 }
339
340 static void assemble(const char *out, const char *in)
341 {
342         char buf[4096];
343
344         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
345         if (verbose) {
346                 puts(buf);
347         }
348
349         int err = system(buf);
350         if (err != 0) {
351                 fprintf(stderr, "assembler reported an error\n");
352                 exit(1);
353         }
354 }
355
356 static void print_file_name(const char *file)
357 {
358         add_flag(&ldflags_obst, "-print-file-name=%s", file);
359
360         obstack_1grow(&ldflags_obst, '\0');
361         const char *flags = obstack_finish(&ldflags_obst);
362
363         /* construct commandline */
364         obstack_printf(&ldflags_obst, "%s ", LINKER);
365         obstack_printf(&ldflags_obst, "%s", flags);
366         obstack_1grow(&ldflags_obst, '\0');
367
368         char *commandline = obstack_finish(&ldflags_obst);
369
370         if (verbose) {
371                 puts(commandline);
372         }
373         int err = system(commandline);
374         if (err != EXIT_SUCCESS) {
375                 fprintf(stderr, "linker reported an error\n");
376                 exit(1);
377         }
378 }
379
380 static const char *try_dir(const char *dir)
381 {
382         if (dir == NULL)
383                 return dir;
384         if (access(dir, R_OK | W_OK | X_OK) == 0)
385                 return dir;
386         return NULL;
387 }
388
389 static const char *get_tempdir(void)
390 {
391         static const char *tmpdir = NULL;
392
393         if (tmpdir != NULL)
394                 return tmpdir;
395
396         if (tmpdir == NULL)
397                 tmpdir = try_dir(getenv("TMPDIR"));
398         if (tmpdir == NULL)
399                 tmpdir = try_dir(getenv("TMP"));
400         if (tmpdir == NULL)
401                 tmpdir = try_dir(getenv("TEMP"));
402
403 #ifdef P_tmpdir
404         if (tmpdir == NULL)
405                 tmpdir = try_dir(P_tmpdir);
406 #endif
407
408         if (tmpdir == NULL)
409                 tmpdir = try_dir("/var/tmp");
410         if (tmpdir == NULL)
411                 tmpdir = try_dir("/usr/tmp");
412         if (tmpdir == NULL)
413                 tmpdir = try_dir("/tmp");
414
415         if (tmpdir == NULL)
416                 tmpdir = ".";
417
418         return tmpdir;
419 }
420
421 #ifndef HAVE_MKSTEMP
422 /* cheap and nasty mkstemp replacement */
423 static int mkstemp(char *templ)
424 {
425         mktemp(templ);
426         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
427 }
428 #endif
429
430 /**
431  * an own version of tmpnam, which: writes in a buffer, emits no warnings
432  * during linking (like glibc/gnu ld do for tmpnam)...
433  */
434 static FILE *make_temp_file(char *buffer, size_t buflen, const char *prefix)
435 {
436         const char *tempdir = get_tempdir();
437
438         snprintf(buffer, buflen, "%s/%sXXXXXX", tempdir, prefix);
439
440         int fd = mkstemp(buffer);
441         if (fd == -1) {
442                 fprintf(stderr, "couldn't create temporary file: %s\n",
443                         strerror(errno));
444                 exit(1);
445         }
446         FILE *out = fdopen(fd, "w");
447         if (out == NULL) {
448                 fprintf(stderr, "couldn't create temporary file FILE*\n");
449                 exit(1);
450         }
451
452         file_list_entry_t *entry = xmalloc(sizeof(*entry));
453         memset(entry, 0, sizeof(*entry));
454
455         size_t  name_len = strlen(buffer) + 1;
456         char   *name     = malloc(name_len);
457         memcpy(name, buffer, name_len);
458         entry->name      = name;
459
460         entry->next = temp_files;
461         temp_files  = entry;
462
463         return out;
464 }
465
466 static void free_temp_files(void)
467 {
468         file_list_entry_t *entry = temp_files;
469         file_list_entry_t *next;
470         for ( ; entry != NULL; entry = next) {
471                 next = entry->next;
472
473                 unlink(entry->name);
474                 free((char*) entry->name);
475                 free(entry);
476         }
477         temp_files = NULL;
478 }
479
480 /**
481  * Do the necessary lowering for compound parameters.
482  */
483 void lower_compound_params(void)
484 {
485         lower_params_t params;
486
487         params.def_ptr_alignment    = 4;
488         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
489         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
490         params.find_pointer_type    = NULL;
491         params.ret_compound_in_regs = NULL;
492         lower_calls_with_compounds(&params);
493 }
494
495 typedef enum compile_mode_t {
496         BenchmarkParser,
497         PreprocessOnly,
498         ParseOnly,
499         Compile,
500         CompileDump,
501         CompileAssemble,
502         CompileAssembleLink,
503         LexTest,
504         PrintAst,
505         PrintFluffy,
506         PrintCaml,
507         PrintJna
508 } compile_mode_t;
509
510 static void usage(const char *argv0)
511 {
512         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
513 }
514
515 static void print_cparser_version(void)
516 {
517         printf("cparser (%s) using libFirm (%u.%u",
518                cparser_REVISION, ir_get_version_major(),
519                ir_get_version_minor());
520
521         const char *revision = ir_get_version_revision();
522         if (revision[0] != 0) {
523                 putchar(' ');
524                 fputs(revision, stdout);
525         }
526
527         const char *build = ir_get_version_build();
528         if (build[0] != 0) {
529                 putchar(' ');
530                 fputs(build, stdout);
531         }
532         puts(")\n");
533 }
534
535 static void set_be_option(const char *arg)
536 {
537         int res = firm_be_option(arg);
538         (void) res;
539         assert(res);
540 }
541
542 static void set_option(const char *arg)
543 {
544         int res = firm_option(arg);
545         (void) res;
546         assert(res);
547 }
548
549 static void copy_file(FILE *dest, FILE *input)
550 {
551         char buf[16384];
552
553         while (!feof(input) && !ferror(dest)) {
554                 size_t read = fread(buf, 1, sizeof(buf), input);
555                 if (fwrite(buf, 1, read, dest) != read) {
556                         perror("couldn't write output");
557                 }
558         }
559 }
560
561 static inline bool streq(char const* a, char const* b)
562 {
563         return strcmp(a, b) == 0;
564 }
565
566 static inline bool strstart(char const* str, char const* start)
567 {
568         do {
569                 if (*start == '\0')
570                         return true;
571         } while (*str++ == *start++);
572         return false;
573 }
574
575 static FILE *open_file(const char *filename)
576 {
577         if (streq(filename, "-")) {
578                 return stdin;
579         }
580
581         FILE *in = fopen(filename, "r");
582         if (in == NULL) {
583                 fprintf(stderr, "Couldn't open '%s': %s\n", filename,
584                                 strerror(errno));
585                 exit(1);
586         }
587
588         return in;
589 }
590
591 static filetype_t get_filetype_from_string(const char *string)
592 {
593         if (streq(string, "c") || streq(string, "c-header"))
594                 return FILETYPE_C;
595         if (streq(string, "c++") || streq(string, "c++-header"))
596                 return FILETYPE_CXX;
597         if (streq(string, "assembler"))
598                 return FILETYPE_PREPROCESSED_ASSEMBLER;
599         if (streq(string, "assembler-with-cpp"))
600                 return FILETYPE_ASSEMBLER;
601         if (streq(string, "none"))
602                 return FILETYPE_AUTODETECT;
603
604         return FILETYPE_UNKNOWN;
605 }
606
607 static void init_os_support(void)
608 {
609         /* OS option must be set to the backend */
610         switch (firm_opt.os_support) {
611         case OS_SUPPORT_MINGW:
612                 set_be_option("ia32-gasmode=mingw");
613                 wchar_atomic_kind = ATOMIC_TYPE_USHORT;
614                 break;
615         case OS_SUPPORT_LINUX:
616                 set_be_option("ia32-gasmode=elf");
617                 break;
618         case OS_SUPPORT_MACHO:
619                 set_be_option("ia32-gasmode=macho");
620                 set_be_option("ia32-stackalign=4");
621                 set_be_option("pic");
622                 break;
623         }
624 }
625
626 typedef enum lang_standard_t {
627         STANDARD_DEFAULT, /* gnu99 (for C, GCC does gnu89) or gnu++98 (for C++) */
628         STANDARD_ANSI,    /* c89 (for C) or c++98 (for C++) */
629         STANDARD_C89,     /* ISO C90 (sic) */
630         STANDARD_C90,     /* ISO C90 as modified in amendment 1 */
631         STANDARD_C99,     /* ISO C99 */
632         STANDARD_GNU89,   /* ISO C90 plus GNU extensions (including some C99) */
633         STANDARD_GNU99,   /* ISO C99 plus GNU extensions */
634         STANDARD_CXX98,   /* ISO C++ 1998 plus amendments */
635         STANDARD_GNUXX98  /* ISO C++ 1998 plus amendments and GNU extensions */
636 } lang_standard_t;
637
638 int main(int argc, char **argv)
639 {
640         initialize_firm();
641
642         const char        *dumpfunction         = NULL;
643         const char        *print_file_name_file = NULL;
644         compile_mode_t     mode                 = CompileAssembleLink;
645         int                opt_level            = 1;
646         int                result               = EXIT_SUCCESS;
647         char               cpu_arch[16]         = "ia32";
648         file_list_entry_t *files                = NULL;
649         file_list_entry_t *last_file            = NULL;
650         bool               construct_dep_target = false;
651         struct obstack     file_obst;
652
653         atexit(free_temp_files);
654
655         /* hack for now... */
656         if (strstr(argv[0], "pptest") != NULL) {
657                 extern int pptest_main(int argc, char **argv);
658                 return pptest_main(argc, argv);
659         }
660
661         obstack_init(&cppflags_obst);
662         obstack_init(&ldflags_obst);
663         obstack_init(&file_obst);
664
665 #define GET_ARG_AFTER(def, args)                                             \
666         def = &arg[sizeof(args)-1];                                              \
667         if (def[0] == '\0') {                                                     \
668                 ++i;                                                                 \
669                 if (i >= argc) {                                                      \
670                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
671                         argument_errors = true;                                          \
672                         break;                                                           \
673                 }                                                                    \
674                 def = argv[i];                                                       \
675                 if (def[0] == '-' && def[1] != '\0') {                                \
676                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
677                         argument_errors = true;                                          \
678                         continue;                                                        \
679                 }                                                                    \
680         }
681
682 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
683
684         /* early options parsing (find out optimisation level and OS) */
685         for (int i = 1; i < argc; ++i) {
686                 const char *arg = argv[i];
687                 if (arg[0] != '-')
688                         continue;
689
690                 const char *option = &arg[1];
691                 if (option[0] == 'O') {
692                         sscanf(&option[1], "%d", &opt_level);
693                 }
694                 if (strcmp(arg, "-fwin32") == 0) {
695                         firm_opt.os_support = OS_SUPPORT_MINGW;
696                 } else if (strcmp(arg, "-fmac") == 0) {
697                         firm_opt.os_support = OS_SUPPORT_MACHO;
698                 } else if (strcmp(arg, "-flinux") == 0) {
699                         firm_opt.os_support = OS_SUPPORT_LINUX;
700                 }
701         }
702
703         /* set target/os specific stuff */
704         init_os_support();
705
706         /* apply optimisation level */
707         switch(opt_level) {
708         case 0:
709                 set_option("no-opt");
710                 break;
711         case 1:
712                 set_option("no-inline");
713                 break;
714         default:
715         case 4:
716                 set_option("strict-aliasing");
717                 /* use_builtins = true; */
718                 /* fallthrough */
719         case 3:
720                 set_option("cond-eval");
721                 set_option("if-conv");
722                 /* fallthrough */
723         case 2:
724                 set_option("inline");
725                 set_option("deconv");
726                 set_be_option("omitfp");
727                 break;
728         }
729
730         /* parse rest of options */
731         lang_standard_t standard        = STANDARD_DEFAULT;
732         unsigned        features_on     = 0;
733         unsigned        features_off    = 0;
734         filetype_t      forced_filetype = FILETYPE_AUTODETECT;
735         bool            help_displayed  = false;
736         bool            argument_errors = false;
737         for (int i = 1; i < argc; ++i) {
738                 const char *arg = argv[i];
739                 if (arg[0] == '-' && arg[1] != '\0') {
740                         /* an option */
741                         const char *option = &arg[1];
742                         if (option[0] == 'o') {
743                                 GET_ARG_AFTER(outname, "-o");
744                         } else if (option[0] == 'g') {
745                                 set_be_option("debuginfo=stabs");
746                                 set_be_option("omitfp=no");
747                                 set_be_option("ia32-nooptcc=yes");
748                         } else if (SINGLE_OPTION('c')) {
749                                 mode = CompileAssemble;
750                         } else if (SINGLE_OPTION('E')) {
751                                 mode = PreprocessOnly;
752                         } else if (SINGLE_OPTION('S')) {
753                                 mode = Compile;
754                         } else if (option[0] == 'O') {
755                                 continue;
756                         } else if (option[0] == 'I') {
757                                 const char *opt;
758                                 GET_ARG_AFTER(opt, "-I");
759                                 add_flag(&cppflags_obst, "-I%s", opt);
760                         } else if (option[0] == 'D') {
761                                 const char *opt;
762                                 GET_ARG_AFTER(opt, "-D");
763                                 add_flag(&cppflags_obst, "-D%s", opt);
764                         } else if (option[0] == 'U') {
765                                 const char *opt;
766                                 GET_ARG_AFTER(opt, "-U");
767                                 add_flag(&cppflags_obst, "-U%s", opt);
768                         } else if (option[0] == 'l') {
769                                 const char *opt;
770                                 GET_ARG_AFTER(opt, "-l");
771                                 add_flag(&ldflags_obst, "-l%s", opt);
772                         } else if (option[0] == 'L') {
773                                 const char *opt;
774                                 GET_ARG_AFTER(opt, "-L");
775                                 add_flag(&ldflags_obst, "-L%s", opt);
776                         } else if (SINGLE_OPTION('v')) {
777                                 verbose = 1;
778                         } else if (SINGLE_OPTION('w')) {
779                                 memset(&warning, 0, sizeof(warning));
780                         } else if (option[0] == 'x') {
781                                 const char *opt;
782                                 GET_ARG_AFTER(opt, "-x");
783                                 forced_filetype = get_filetype_from_string(opt);
784                                 if (forced_filetype == FILETYPE_UNKNOWN) {
785                                         fprintf(stderr, "Unknown language '%s'\n", opt);
786                                         argument_errors = true;
787                                 }
788                         } else if (streq(option, "M")) {
789                                 mode = PreprocessOnly;
790                                 add_flag(&cppflags_obst, "-M");
791                         } else if (streq(option, "MMD") ||
792                                    streq(option, "MD")) {
793                             construct_dep_target = true;
794                                 add_flag(&cppflags_obst, "-%s", option);
795                         } else if (streq(option, "MM")  ||
796                                    streq(option, "MP")) {
797                                 add_flag(&cppflags_obst, "-%s", option);
798                         } else if (streq(option, "MT") ||
799                                    streq(option, "MQ") ||
800                                    streq(option, "MF")) {
801                                 const char *opt;
802                                 GET_ARG_AFTER(opt, "-MT");
803                                 add_flag(&cppflags_obst, "-%s", option);
804                                 add_flag(&cppflags_obst, "%s", opt);
805                         } else if (streq(option, "include")) {
806                                 const char *opt;
807                                 GET_ARG_AFTER(opt, "-include");
808                                 add_flag(&cppflags_obst, "-include");
809                                 add_flag(&cppflags_obst, "%s", opt);
810                         } else if (streq(option, "isystem")) {
811                                 const char *opt;
812                                 GET_ARG_AFTER(opt, "-isystem");
813                                 add_flag(&cppflags_obst, "-isystem");
814                                 add_flag(&cppflags_obst, "%s", opt);
815                         } else if (streq(option, "nostdinc")
816                                         || streq(option, "trigraphs")) {
817                                 /* pass these through to the preprocessor */
818                                 add_flag(&cppflags_obst, "%s", arg);
819                         } else if (streq(option, "pipe")) {
820                                 /* here for gcc compatibility */
821                         } else if (option[0] == 'f') {
822                                 char const *orig_opt;
823                                 GET_ARG_AFTER(orig_opt, "-f");
824
825                                 if (strstart(orig_opt, "align-loops=") ||
826                                     strstart(orig_opt, "align-jumps=") ||
827                                     strstart(orig_opt, "align-functions=")) {
828                                         fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
829                                 } else if (strstart(orig_opt, "input-charset=")) {
830                                         char const* const encoding = strchr(orig_opt, '=') + 1;
831                                         select_input_encoding(encoding);
832                                 } else if (streq(orig_opt, "verbose-asm")) {
833                                         /* ignore: we always print verbose assembler */
834                                 } else {
835                                         char const *opt         = orig_opt;
836                                         bool        truth_value = true;
837                                         if (opt[0] == 'n' && opt[1] == 'o' && opt[2] == '-') {
838                                                 truth_value = false;
839                                                 opt += 3;
840                                         }
841
842                                         if (streq(opt, "builtins")) {
843                                                 use_builtins = truth_value;
844                                         } else if (streq(opt, "dollars-in-identifiers")) {
845                                                 allow_dollar_in_symbol = truth_value;
846                                         } else if (streq(opt, "omit-frame-pointer")) {
847                                                 set_be_option(truth_value ? "omitfp" : "omitfp=no");
848                                         } else if (streq(opt, "short-wchar")) {
849                                                 wchar_atomic_kind = truth_value ? ATOMIC_TYPE_USHORT
850                                                         : ATOMIC_TYPE_INT;
851                                         } else if (streq(opt, "signed-char")) {
852                                                 char_is_signed = truth_value;
853                                         } else if (streq(opt, "strength-reduce")) {
854                                                 firm_option(truth_value ? "strength-red" : "no-strength-red");
855                                         } else if (streq(opt, "syntax-only")) {
856                                                 mode = truth_value ? ParseOnly : CompileAssembleLink;
857                                         } else if (streq(opt, "unsigned-char")) {
858                                                 char_is_signed = !truth_value;
859                                         } else if (streq(opt, "fast-math")               ||
860                                                    streq(opt, "jump-tables")             ||
861                                                    streq(opt, "unroll-loops")            ||
862                                                    streq(opt, "expensive-optimizations") ||
863                                                    streq(opt, "common")                  ||
864                                                    streq(opt, "PIC")                     ||
865                                                    streq(opt, "align-loops")             ||
866                                                    streq(opt, "align-jumps")             ||
867                                                    streq(opt, "align-functions")) {
868                                                 fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
869                                         } else {
870                                                 int res = firm_option(orig_opt);
871                                                 if (res == 0) {
872                                                         fprintf(stderr, "error: unknown Firm option '-f%s'\n",
873                                                                 orig_opt);
874                                                         argument_errors = true;
875                                                         continue;
876                                                 } else if (res == -1) {
877                                                         help_displayed = true;
878                                                 }
879                                         }
880                                 }
881                         } else if (option[0] == 'b') {
882                                 const char *opt;
883                                 GET_ARG_AFTER(opt, "-b");
884                                 int res = firm_be_option(opt);
885                                 if (res == 0) {
886                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
887                                                 opt);
888                                         argument_errors = true;
889                                 } else if (res == -1) {
890                                         help_displayed = true;
891                                 } else if (strstart(opt, "isa=")) {
892                                         strncpy(cpu_arch, opt, sizeof(cpu_arch));
893                                 }
894                         } else if (option[0] == 'W') {
895                                 if (strstart(option + 1, "p,")) {
896                                         // pass options directly to the preprocessor
897                                         const char *opt;
898                                         GET_ARG_AFTER(opt, "-Wp,");
899                                         add_flag(&cppflags_obst, "-Wp,%s", opt);
900                                 } else if (strstart(option + 1, "l,")) {
901                                         // pass options directly to the linker
902                                         const char *opt;
903                                         GET_ARG_AFTER(opt, "-Wl,");
904                                         add_flag(&ldflags_obst, "-Wl,%s", opt);
905                                 } else if (streq(option + 1, "no-trigraphs")
906                                                         || streq(option + 1, "undef")) {
907                                         add_flag(&cppflags_obst, "%s", arg);
908                                 } else {
909                                         set_warning_opt(&option[1]);
910                                 }
911                         } else if (option[0] == 'm') {
912                                 /* -m options */
913                                 const char *opt;
914                                 char arch_opt[64];
915
916                                 GET_ARG_AFTER(opt, "-m");
917                                 if (strstart(opt, "arch=")) {
918                                         GET_ARG_AFTER(opt, "-march=");
919                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
920                                         int res = firm_be_option(arch_opt);
921                                         if (res == 0)
922                                                 argument_errors = true;
923                                         else {
924                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
925                                                 int res = firm_be_option(arch_opt);
926                                                 if (res == 0)
927                                                         argument_errors = true;
928                                         }
929                                 } else if (strstart(opt, "tune=")) {
930                                         GET_ARG_AFTER(opt, "-mtune=");
931                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
932                                         int res = firm_be_option(arch_opt);
933                                         if (res == 0)
934                                                 argument_errors = true;
935                                 } else if (strstart(opt, "cpu=")) {
936                                         GET_ARG_AFTER(opt, "-mcpu=");
937                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
938                                         int res = firm_be_option(arch_opt);
939                                         if (res == 0)
940                                                 argument_errors = true;
941                                 } else if (strstart(opt, "fpmath=")) {
942                                         GET_ARG_AFTER(opt, "-mfpmath=");
943                                         if (streq(opt, "387"))
944                                                 opt = "x87";
945                                         else if (streq(opt, "sse"))
946                                                 opt = "sse2";
947                                         else {
948                                                 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
949                                                 argument_errors = true;
950                                         }
951                                         if (!argument_errors) {
952                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
953                                                 int res = firm_be_option(arch_opt);
954                                                 if (res == 0)
955                                                         argument_errors = true;
956                                         }
957                                 } else if (strstart(opt, "preferred-stack-boundary=")) {
958                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
959                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
960                                         int res = firm_be_option(arch_opt);
961                                         if (res == 0)
962                                                 argument_errors = true;
963                                 } else if (streq(opt, "omit-leaf-frame-pointer")) {
964                                         set_be_option("omitleaffp=1");
965                                 } else if (streq(opt, "no-omit-leaf-frame-pointer")) {
966                                         set_be_option("omitleaffp=0");
967                                 } else {
968                                         char *endptr;
969                                         long int value = strtol(opt, &endptr, 10);
970                                         if (*endptr != '\0') {
971                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
972                                                 argument_errors = true;
973                                         }
974                                         if (value != 16 && value != 32 && value != 64) {
975                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
976                                                 argument_errors = true;
977                                         } else {
978                                                 machine_size = (unsigned int)value;
979                                         }
980                                 }
981                         } else if (streq(option, "pg")) {
982                                 set_be_option("gprof");
983                                 add_flag(&ldflags_obst, "-pg");
984                         } else if (streq(option, "pedantic") ||
985                                    streq(option, "ansi")) {
986                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
987                         } else if (streq(option, "shared")) {
988                                 add_flag(&ldflags_obst, "-shared");
989                         } else if (strstart(option, "std=")) {
990                                 const char *const o = &option[4];
991                                 standard =
992                                         streq(o, "c++")            ? STANDARD_CXX98   :
993                                         streq(o, "c++98")          ? STANDARD_CXX98   :
994                                         streq(o, "c89")            ? STANDARD_C89     :
995                                         streq(o, "c99")            ? STANDARD_C99     :
996                                         streq(o, "c9x")            ? STANDARD_C99     : // deprecated
997                                         streq(o, "gnu++98")        ? STANDARD_GNUXX98 :
998                                         streq(o, "gnu89")          ? STANDARD_GNU89   :
999                                         streq(o, "gnu99")          ? STANDARD_GNU99   :
1000                                         streq(o, "gnu9x")          ? STANDARD_GNU99   : // deprecated
1001                                         streq(o, "iso9899:1990")   ? STANDARD_C89     :
1002                                         streq(o, "iso9899:199409") ? STANDARD_C90     :
1003                                         streq(o, "iso9899:1999")   ? STANDARD_C99     :
1004                                         streq(o, "iso9899:199x")   ? STANDARD_C99     : // deprecated
1005                                         (fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg), standard);
1006                         } else if (streq(option, "version")) {
1007                                 print_cparser_version();
1008                         } else if (strstart(option, "print-file-name=")) {
1009                                 GET_ARG_AFTER(print_file_name_file, "-print-file-name=");
1010                         } else if (option[0] == '-') {
1011                                 /* double dash option */
1012                                 ++option;
1013                                 if (streq(option, "gcc")) {
1014                                         features_on  |=  _GNUC;
1015                                         features_off &= ~_GNUC;
1016                                 } else if (streq(option, "no-gcc")) {
1017                                         features_on  &= ~_GNUC;
1018                                         features_off |=  _GNUC;
1019                                 } else if (streq(option, "ms")) {
1020                                         features_on  |=  _MS;
1021                                         features_off &= ~_MS;
1022                                 } else if (streq(option, "no-ms")) {
1023                                         features_on  &= ~_MS;
1024                                         features_off |=  _MS;
1025                                 } else if (streq(option, "strict")) {
1026                                         strict_mode = true;
1027                                 } else if (streq(option, "lextest")) {
1028                                         mode = LexTest;
1029                                 } else if (streq(option, "benchmark")) {
1030                                         mode = BenchmarkParser;
1031                                 } else if (streq(option, "print-ast")) {
1032                                         mode = PrintAst;
1033                                 } else if (streq(option, "print-implicit-cast")) {
1034                                         print_implicit_casts = true;
1035                                 } else if (streq(option, "print-parenthesis")) {
1036                                         print_parenthesis = true;
1037                                 } else if (streq(option, "print-fluffy")) {
1038                                         mode = PrintFluffy;
1039                                 } else if (streq(option, "print-caml")) {
1040                                         mode = PrintCaml;
1041                                 } else if (streq(option, "print-jna")) {
1042                                         mode = PrintJna;
1043                                 } else if (streq(option, "version")) {
1044                                         print_cparser_version();
1045                                         exit(EXIT_SUCCESS);
1046                                 } else if (streq(option, "dump-function")) {
1047                                         ++i;
1048                                         if (i >= argc) {
1049                                                 fprintf(stderr, "error: "
1050                                                         "expected argument after '--dump-function'\n");
1051                                                 argument_errors = true;
1052                                                 break;
1053                                         }
1054                                         dumpfunction = argv[i];
1055                                         mode         = CompileDump;
1056                                 } else {
1057                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
1058                                         argument_errors = true;
1059                                 }
1060                         } else {
1061                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
1062                                 argument_errors = true;
1063                         }
1064                 } else {
1065                         filetype_t type = forced_filetype;
1066                         if (type == FILETYPE_AUTODETECT) {
1067                                 if (streq(arg, "-")) {
1068                                         /* - implicitly means C source file */
1069                                         type = FILETYPE_C;
1070                                 } else {
1071                                         const char *suffix = strrchr(arg, '.');
1072                                         /* Ensure there is at least one char before the suffix */
1073                                         if (suffix != NULL && suffix != arg) {
1074                                                 ++suffix;
1075                                                 type =
1076                                                         streq(suffix, "S")   ? FILETYPE_ASSEMBLER              :
1077                                                         streq(suffix, "a")   ? FILETYPE_OBJECT                 :
1078                                                         streq(suffix, "c")   ? FILETYPE_C                      :
1079                                                         streq(suffix, "cc")  ? FILETYPE_CXX                    :
1080                                                         streq(suffix, "cpp") ? FILETYPE_CXX                    :
1081                                                         streq(suffix, "cxx") ? FILETYPE_CXX                    :
1082                                                         streq(suffix, "h")   ? FILETYPE_C                      :
1083                                                         streq(suffix, "o")   ? FILETYPE_OBJECT                 :
1084                                                         streq(suffix, "s")   ? FILETYPE_PREPROCESSED_ASSEMBLER :
1085                                                         streq(suffix, "so")  ? FILETYPE_OBJECT                 :
1086                                                         FILETYPE_AUTODETECT;
1087                                         }
1088                                 }
1089
1090                                 if (type == FILETYPE_AUTODETECT) {
1091                                         fprintf(stderr, "'%s': file format not recognized\n", arg);
1092                                         continue;
1093                                 }
1094                         }
1095
1096                         file_list_entry_t *entry
1097                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
1098                         memset(entry, 0, sizeof(entry[0]));
1099                         entry->name = arg;
1100                         entry->type = type;
1101
1102                         if (last_file != NULL) {
1103                                 last_file->next = entry;
1104                         } else {
1105                                 files = entry;
1106                         }
1107                         last_file = entry;
1108                 }
1109         }
1110
1111         if (print_file_name_file != NULL) {
1112                 print_file_name(print_file_name_file);
1113                 return 0;
1114         }
1115
1116         if (files == NULL) {
1117                 fprintf(stderr, "error: no input files specified\n");
1118                 argument_errors = true;
1119         }
1120
1121         if (help_displayed) {
1122                 return !argument_errors;
1123         }
1124         if (argument_errors) {
1125                 usage(argv[0]);
1126                 return 1;
1127         }
1128
1129         /* we do the lowering in ast2firm */
1130         firm_opt.lower_bitfields = FALSE;
1131
1132         /* set the c_mode here, types depends on it */
1133         c_mode |= features_on;
1134         c_mode &= ~features_off;
1135
1136         gen_firm_init();
1137         init_symbol_table();
1138         init_types();
1139         init_typehash();
1140         init_basic_types();
1141         init_lexer();
1142         init_ast();
1143         init_parser();
1144         init_ast2firm();
1145         init_mangle();
1146
1147         if (construct_dep_target) {
1148                 if (outname != 0 && strlen(outname) >= 2) {
1149                         get_output_name(dep_target, sizeof(dep_target), outname, ".d");
1150                 } else {
1151                         get_output_name(dep_target, sizeof(dep_target), files->name, ".d");
1152                 }
1153         } else {
1154                 dep_target[0] = '\0';
1155         }
1156
1157         char outnamebuf[4096];
1158         if (outname == NULL) {
1159                 const char *filename = files->name;
1160
1161                 switch(mode) {
1162                 case BenchmarkParser:
1163                 case PrintAst:
1164                 case PrintFluffy:
1165                 case PrintCaml:
1166                 case PrintJna:
1167                 case LexTest:
1168                 case PreprocessOnly:
1169                 case ParseOnly:
1170                         outname = "-";
1171                         break;
1172                 case Compile:
1173                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".s");
1174                         outname = outnamebuf;
1175                         break;
1176                 case CompileAssemble:
1177                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".o");
1178                         outname = outnamebuf;
1179                         break;
1180                 case CompileDump:
1181                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
1182                                         ".vcg");
1183                         outname = outnamebuf;
1184                         break;
1185                 case CompileAssembleLink:
1186 #ifdef _WIN32
1187                         outname = "a.exe";
1188 #else
1189                         outname = "a.out";
1190 #endif
1191                         break;
1192                 }
1193         }
1194
1195         assert(outname != NULL);
1196
1197         FILE *out;
1198         if (streq(outname, "-")) {
1199                 out = stdout;
1200         } else {
1201                 out = fopen(outname, "w");
1202                 if (out == NULL) {
1203                         fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
1204                                         strerror(errno));
1205                         return 1;
1206                 }
1207         }
1208
1209         file_list_entry_t *file;
1210         for (file = files; file != NULL; file = file->next) {
1211                 char        asm_tempfile[1024];
1212                 const char *filename = file->name;
1213                 filetype_t  filetype = file->type;
1214
1215                 if (filetype == FILETYPE_OBJECT)
1216                         continue;
1217
1218                 FILE *in = NULL;
1219                 if (mode == LexTest) {
1220                         if (in == NULL)
1221                                 in = open_file(filename);
1222                         lextest(in, filename);
1223                         fclose(in);
1224                         exit(EXIT_SUCCESS);
1225                 }
1226
1227                 FILE *preprocessed_in = NULL;
1228                 switch (filetype) {
1229                         case FILETYPE_C:
1230                                 filetype = FILETYPE_PREPROCESSED_C;
1231                                 goto preprocess;
1232                         case FILETYPE_CXX:
1233                                 filetype = FILETYPE_PREPROCESSED_CXX;
1234                                 goto preprocess;
1235                         case FILETYPE_ASSEMBLER:
1236                                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1237                                 add_flag(&cppflags_obst, "-x");
1238                                 add_flag(&cppflags_obst, "assembler-with-cpp");
1239                                 goto preprocess;
1240 preprocess:
1241                                 /* no support for input on FILE* yet */
1242                                 if (in != NULL)
1243                                         panic("internal compiler error: in for preprocessor != NULL");
1244
1245                                 preprocessed_in = preprocess(filename);
1246                                 if (mode == PreprocessOnly) {
1247                                         copy_file(out, preprocessed_in);
1248                                         int result = pclose(preprocessed_in);
1249                                         fclose(out);
1250                                         /* remove output file in case of error */
1251                                         if (out != stdout && result != EXIT_SUCCESS) {
1252                                                 unlink(outname);
1253                                         }
1254                                         return result;
1255                                 }
1256
1257                                 in = preprocessed_in;
1258                                 break;
1259
1260                         default:
1261                                 break;
1262                 }
1263
1264                 FILE *asm_out;
1265                 if (mode == Compile) {
1266                         asm_out = out;
1267                 } else {
1268                         asm_out = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "ccs");
1269                 }
1270
1271                 if (in == NULL)
1272                         in = open_file(filename);
1273
1274                 /* preprocess and compile */
1275                 if (filetype == FILETYPE_PREPROCESSED_C) {
1276                         char const* invalid_mode;
1277                         switch (standard) {
1278                                 case STANDARD_ANSI:
1279                                 case STANDARD_C89:   c_mode = _C89;                break;
1280                                 /* TODO ^v determine difference between these two */
1281                                 case STANDARD_C90:   c_mode = _C89;                break;
1282                                 case STANDARD_C99:   c_mode = _C89 | _C99;         break;
1283                                 case STANDARD_GNU89: c_mode = _C89 |        _GNUC; break;
1284
1285 default_c_warn:
1286                                         fprintf(stderr,
1287                                                         "warning: command line option \"-std=%s\" is not valid for C\n",
1288                                                         invalid_mode);
1289                                         /* FALLTHROUGH */
1290                                 case STANDARD_DEFAULT:
1291                                 case STANDARD_GNU99:   c_mode = _C89 | _C99 | _GNUC; break;
1292
1293                                 case STANDARD_CXX98:   invalid_mode = "c++98"; goto default_c_warn;
1294                                 case STANDARD_GNUXX98: invalid_mode = "gnu98"; goto default_c_warn;
1295                         }
1296                         goto do_parsing;
1297                 } else if (filetype == FILETYPE_PREPROCESSED_CXX) {
1298                         char const* invalid_mode;
1299                         switch (standard) {
1300                                 case STANDARD_C89:   invalid_mode = "c89";   goto default_cxx_warn;
1301                                 case STANDARD_C90:   invalid_mode = "c90";   goto default_cxx_warn;
1302                                 case STANDARD_C99:   invalid_mode = "c99";   goto default_cxx_warn;
1303                                 case STANDARD_GNU89: invalid_mode = "gnu89"; goto default_cxx_warn;
1304                                 case STANDARD_GNU99: invalid_mode = "gnu99"; goto default_cxx_warn;
1305
1306                                 case STANDARD_ANSI:
1307                                 case STANDARD_CXX98: c_mode = _CXX; break;
1308
1309 default_cxx_warn:
1310                                         fprintf(stderr,
1311                                                         "warning: command line option \"-std=%s\" is not valid for C++\n",
1312                                                         invalid_mode);
1313                                 case STANDARD_DEFAULT:
1314                                 case STANDARD_GNUXX98: c_mode = _CXX | _GNUC; break;
1315                         }
1316
1317 do_parsing:
1318                         c_mode |= features_on;
1319                         c_mode &= ~features_off;
1320
1321                         init_tokens();
1322                         translation_unit_t *const unit = do_parsing(in, filename);
1323
1324                         /* prints the AST even if errors occurred */
1325                         if (mode == PrintAst) {
1326                                 type_set_output(out);
1327                                 ast_set_output(out);
1328                                 print_ast(unit);
1329                         }
1330
1331                         if (error_count > 0) {
1332                                 /* parsing failed because of errors */
1333                                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count,
1334                                         warning_count);
1335                                 result = EXIT_FAILURE;
1336                                 continue;
1337                         } else if (warning_count > 0) {
1338                                 fprintf(stderr, "%u warning(s)\n", warning_count);
1339                         }
1340
1341                         if (in == preprocessed_in) {
1342                                 int pp_result = pclose(preprocessed_in);
1343                                 if (pp_result != EXIT_SUCCESS) {
1344                                         /* remove output file */
1345                                         if (out != stdout)
1346                                                 unlink(outname);
1347                                         exit(EXIT_FAILURE);
1348                                 }
1349                         }
1350
1351                         if (mode == BenchmarkParser) {
1352                                 return result;
1353                         } else if (mode == PrintFluffy) {
1354                                 write_fluffy_decls(out, unit);
1355                                 continue;
1356                         } else if (mode == PrintCaml) {
1357                                 write_caml_decls(out, unit);
1358                                 continue;
1359                         } else if (mode == PrintJna) {
1360                                 write_jna_decls(out, unit);
1361                                 continue;
1362                         }
1363
1364                         translation_unit_to_firm(unit);
1365
1366                         if (mode == ParseOnly) {
1367                                 continue;
1368                         }
1369
1370                         if (mode == CompileDump) {
1371                                 /* find irg */
1372                                 ident    *id     = new_id_from_str(dumpfunction);
1373                                 ir_graph *irg    = NULL;
1374                                 int       n_irgs = get_irp_n_irgs();
1375                                 for (int i = 0; i < n_irgs; ++i) {
1376                                         ir_graph *tirg   = get_irp_irg(i);
1377                                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
1378                                         if (irg_id == id) {
1379                                                 irg = tirg;
1380                                                 break;
1381                                         }
1382                                 }
1383
1384                                 if (irg == NULL) {
1385                                         fprintf(stderr, "No graph for function '%s' found\n",
1386                                                 dumpfunction);
1387                                         exit(1);
1388                                 }
1389
1390                                 dump_ir_block_graph_file(irg, out);
1391                                 fclose(out);
1392                                 exit(0);
1393                         }
1394
1395                         gen_firm_finish(asm_out, filename, /*c_mode=*/1,
1396                                         have_const_functions);
1397                         if (asm_out != out) {
1398                                 fclose(asm_out);
1399                         }
1400                 } else if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1401                         copy_file(asm_out, in);
1402                         if (in == preprocessed_in) {
1403                                 int pp_result = pclose(preprocessed_in);
1404                                 if (pp_result != EXIT_SUCCESS) {
1405                                         /* remove output in error case */
1406                                         if (out != stdout)
1407                                                 unlink(outname);
1408                                         return pp_result;
1409                                 }
1410                         }
1411                         if (asm_out != out) {
1412                                 fclose(asm_out);
1413                         }
1414                 }
1415
1416                 if (mode == Compile)
1417                         continue;
1418
1419                 /* if we're here then we have preprocessed assembly */
1420                 filename = asm_tempfile;
1421                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1422
1423                 /* assemble */
1424                 if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1425                         char        temp[1024];
1426                         const char *filename_o;
1427                         if (mode == CompileAssemble) {
1428                                 fclose(out);
1429                                 filename_o = outname;
1430                         } else {
1431                                 FILE *tempf = make_temp_file(temp, sizeof(temp), "cco");
1432                                 fclose(tempf);
1433                                 filename_o = temp;
1434                         }
1435
1436                         assemble(filename_o, filename);
1437
1438                         size_t len = strlen(filename_o) + 1;
1439                         filename = obstack_copy(&file_obst, filename_o, len);
1440                         filetype = FILETYPE_OBJECT;
1441                 }
1442
1443                 /* ok we're done here, process next file */
1444                 file->name = filename;
1445                 file->type = filetype;
1446         }
1447
1448         if (result != EXIT_SUCCESS) {
1449                 if (out != stdout)
1450                         unlink(outname);
1451                 return result;
1452         }
1453
1454         /* link program file */
1455         if (mode == CompileAssembleLink) {
1456                 obstack_1grow(&ldflags_obst, '\0');
1457                 const char *flags = obstack_finish(&ldflags_obst);
1458
1459                 /* construct commandline */
1460                 obstack_printf(&file_obst, "%s", LINKER);
1461                 for (file_list_entry_t *entry = files; entry != NULL;
1462                                 entry = entry->next) {
1463                         if (entry->type != FILETYPE_OBJECT)
1464                                 continue;
1465
1466                         add_flag(&file_obst, "%s", entry->name);
1467                 }
1468
1469                 add_flag(&file_obst, "-o");
1470                 add_flag(&file_obst, outname);
1471                 obstack_printf(&file_obst, "%s", flags);
1472                 obstack_1grow(&file_obst, '\0');
1473
1474                 char *commandline = obstack_finish(&file_obst);
1475
1476                 if (verbose) {
1477                         puts(commandline);
1478                 }
1479                 int err = system(commandline);
1480                 if (err != EXIT_SUCCESS) {
1481                         fprintf(stderr, "linker reported an error\n");
1482                         exit(1);
1483                 }
1484         }
1485
1486         obstack_free(&cppflags_obst, NULL);
1487         obstack_free(&ldflags_obst, NULL);
1488         obstack_free(&file_obst, NULL);
1489
1490         exit_mangle();
1491         exit_ast2firm();
1492         exit_parser();
1493         exit_ast();
1494         exit_lexer();
1495         exit_typehash();
1496         exit_types();
1497         exit_tokens();
1498         exit_symbol_table();
1499         return 0;
1500 }