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