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