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