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