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