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