Add -std=c90 as alias for -std=c89.
[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 "preprocessor.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_timing.h"
74 #include "driver/firm_machine.h"
75 #include "adt/error.h"
76 #include "adt/strutil.h"
77 #include "wrappergen/write_fluffy.h"
78 #include "wrappergen/write_jna.h"
79 #include "revision.h"
80 #include "warning.h"
81 #include "help.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 | _C99 | _GNUC;
102 bool                byte_order_big_endian     = false;
103 bool                strict_mode               = false;
104 bool                enable_main_collect2_hack = false;
105 bool                freestanding              = false;
106 unsigned            architecture_modulo_shift = 0;
107
108 static bool               char_is_signed      = true;
109 static atomic_type_kind_t wchar_atomic_kind   = ATOMIC_TYPE_INT;
110
111 static machine_triple_t *target_machine;
112 static const char       *target_triple;
113 static int               verbose;
114 static struct obstack    cppflags_obst;
115 static struct obstack    ldflags_obst;
116 static struct obstack    asflags_obst;
117 static char              dep_target[1024];
118 static const char       *outname;
119 static bool              define_intmax_types;
120 static const char       *input_encoding;
121
122 typedef enum lang_standard_t {
123         STANDARD_DEFAULT, /* gnu99 (for C, GCC does gnu89) or gnu++98 (for C++) */
124         STANDARD_C89,     /* ISO C90 (sic) */
125         STANDARD_C89AMD1, /* ISO C90 as modified in amendment 1 */
126         STANDARD_C99,     /* ISO C99 */
127         STANDARD_GNU89,   /* ISO C90 plus GNU extensions (including some C99) */
128         STANDARD_GNU99,   /* ISO C99 plus GNU extensions */
129         STANDARD_CXX98,   /* ISO C++ 1998 plus amendments */
130         STANDARD_GNUXX98  /* ISO C++ 1998 plus amendments and GNU extensions */
131 } lang_standard_t;
132
133 typedef struct file_list_entry_t file_list_entry_t;
134
135 typedef enum filetype_t {
136         FILETYPE_AUTODETECT,
137         FILETYPE_C,
138         FILETYPE_PREPROCESSED_C,
139         FILETYPE_CXX,
140         FILETYPE_PREPROCESSED_CXX,
141         FILETYPE_ASSEMBLER,
142         FILETYPE_PREPROCESSED_ASSEMBLER,
143         FILETYPE_OBJECT,
144         FILETYPE_IR,
145         FILETYPE_UNKNOWN
146 } filetype_t;
147
148 struct file_list_entry_t {
149         const char  *name; /**< filename or NULL for stdin */
150         filetype_t   type;
151         file_list_entry_t *next;
152 };
153
154 static file_list_entry_t *temp_files;
155
156 static void get_output_name(char *buf, size_t buflen, const char *inputname,
157                             const char *newext)
158 {
159         if (inputname == NULL)
160                 inputname = "a";
161
162         char const *const last_slash = strrchr(inputname, '/');
163         char const *const filename   =
164                 last_slash != NULL ? last_slash + 1 : inputname;
165         char const *const last_dot   = strrchr(filename, '.');
166         char const *const name_end   =
167                 last_dot != NULL ? last_dot : strchr(filename, '\0');
168
169         int const len = snprintf(buf, buflen, "%.*s%s",
170                         (int)(name_end - filename), filename, newext);
171 #ifdef _WIN32
172         if (len < 0 || buflen <= (size_t)len)
173 #else
174         if (buflen <= (size_t)len)
175 #endif
176                 panic("filename too long");
177 }
178
179 static translation_unit_t *do_parsing(FILE *const in, const char *const input_name)
180 {
181         start_parsing();
182
183         switch_input(in, input_name);
184         parse();
185         translation_unit_t *unit = finish_parsing();
186         close_input();
187
188         return unit;
189 }
190
191 static void lextest(FILE *in, const char *fname)
192 {
193         switch_input(in, fname);
194         do {
195                 next_preprocessing_token();
196                 print_token(stdout, &pp_token);
197                 putchar('\n');
198         } while (pp_token.kind != T_EOF);
199         close_input();
200 }
201
202 static void add_flag(struct obstack *obst, const char *format, ...)
203 {
204         char buf[65536];
205         va_list ap;
206
207         va_start(ap, format);
208 #ifdef _WIN32
209         int len =
210 #endif
211                 vsnprintf(buf, sizeof(buf), format, ap);
212         va_end(ap);
213
214         obstack_1grow(obst, ' ');
215 #ifdef _WIN32
216         obstack_1grow(obst, '"');
217         obstack_grow(obst, buf, len);
218         obstack_1grow(obst, '"');
219 #else
220         /* escape stuff... */
221         for (char *c = buf; *c != '\0'; ++c) {
222                 switch(*c) {
223                 case ' ':
224                 case '"':
225                 case '$':
226                 case '&':
227                 case '(':
228                 case ')':
229                 case ';':
230                 case '<':
231                 case '>':
232                 case '\'':
233                 case '\\':
234                 case '\n':
235                 case '\r':
236                 case '\t':
237                 case '`':
238                 case '|':
239                         obstack_1grow(obst, '\\');
240                         /* FALLTHROUGH */
241                 default:
242                         obstack_1grow(obst, *c);
243                         break;
244                 }
245         }
246 #endif
247 }
248
249 static const char *type_to_string(type_t *type)
250 {
251         assert(type->kind == TYPE_ATOMIC);
252         return get_atomic_kind_name(type->atomic.akind);
253 }
254
255 static char const* str_lang_standard(lang_standard_t const standard)
256 {
257         switch (standard) {
258         case STANDARD_C89:     return "c89";
259         case STANDARD_C89AMD1: return "iso9899:199409";
260         case STANDARD_C99:     return "c99";
261         case STANDARD_GNU89:   return "gnu89";
262         case STANDARD_GNU99:   return "gnu99";
263         case STANDARD_CXX98:   return "c++98";
264         case STANDARD_GNUXX98: return "gnu++98";
265         case STANDARD_DEFAULT: break;
266         }
267         panic("invalid standard");
268 }
269
270 static FILE *preprocess(const char *fname, filetype_t filetype,
271                         lang_standard_t standard)
272 {
273         static const char *common_flags = NULL;
274
275         if (common_flags == NULL) {
276                 obstack_1grow(&cppflags_obst, '\0');
277                 const char *flags = obstack_finish(&cppflags_obst);
278
279                 /* setup default defines */
280                 add_flag(&cppflags_obst, "-U__WCHAR_TYPE__");
281                 add_flag(&cppflags_obst, "-D__WCHAR_TYPE__=%s", type_to_string(type_wchar_t));
282                 add_flag(&cppflags_obst, "-U__SIZE_TYPE__");
283                 add_flag(&cppflags_obst, "-D__SIZE_TYPE__=%s", type_to_string(type_size_t));
284
285                 add_flag(&cppflags_obst, "-U__VERSION__");
286                 add_flag(&cppflags_obst, "-D__VERSION__=\"%s\"", cparser_REVISION);
287
288                 if (define_intmax_types) {
289                         add_flag(&cppflags_obst, "-U__INTMAX_TYPE__");
290                         add_flag(&cppflags_obst, "-D__INTMAX_TYPE__=%s", type_to_string(type_intmax_t));
291                         add_flag(&cppflags_obst, "-U__UINTMAX_TYPE__");
292                         add_flag(&cppflags_obst, "-D__UINTMAX_TYPE__=%s", type_to_string(type_uintmax_t));
293                 }
294
295                 if (flags[0] != '\0') {
296                         size_t len = strlen(flags);
297                         obstack_1grow(&cppflags_obst, ' ');
298                         obstack_grow(&cppflags_obst, flags, len);
299                 }
300                 obstack_1grow(&cppflags_obst, '\0');
301                 common_flags = obstack_finish(&cppflags_obst);
302         }
303
304         assert(obstack_object_size(&cppflags_obst) == 0);
305
306         const char *preprocessor = getenv("CPARSER_PP");
307         if (preprocessor != NULL) {
308                 obstack_printf(&cppflags_obst, "%s ", preprocessor);
309         } else {
310                 if (target_triple != NULL)
311                         obstack_printf(&cppflags_obst, "%s-", target_triple);
312                 obstack_printf(&cppflags_obst, PREPROCESSOR);
313         }
314
315         char const *lang;
316         switch (filetype) {
317         case FILETYPE_C:         lang = "c";                  break;
318         case FILETYPE_CXX:       lang = "c++";                break;
319         case FILETYPE_ASSEMBLER: lang = "assembler-with-cpp"; break;
320         default:                 lang = NULL;                 break;
321         }
322         if (lang)
323                 add_flag(&cppflags_obst, "-x%s", lang);
324
325         add_flag(&cppflags_obst, "-std=%s", str_lang_standard(standard));
326
327         obstack_printf(&cppflags_obst, "%s", common_flags);
328
329         /* handle dependency generation */
330         if (dep_target[0] != '\0') {
331                 add_flag(&cppflags_obst, "-MF");
332                 add_flag(&cppflags_obst, dep_target);
333                 if (outname != NULL) {
334                         add_flag(&cppflags_obst, "-MQ");
335                         add_flag(&cppflags_obst, outname);
336                 }
337         }
338         add_flag(&cppflags_obst, fname);
339         obstack_1grow(&cppflags_obst, '\0');
340
341         char *commandline = obstack_finish(&cppflags_obst);
342         if (verbose) {
343                 puts(commandline);
344         }
345         FILE *f = popen(commandline, "r");
346         if (f == NULL) {
347                 fprintf(stderr, "invoking preprocessor failed\n");
348                 exit(EXIT_FAILURE);
349         }
350         /* we do not really need that anymore */
351         obstack_free(&cppflags_obst, commandline);
352
353         return f;
354 }
355
356 static void assemble(const char *out, const char *in)
357 {
358         obstack_1grow(&asflags_obst, '\0');
359         const char *flags = obstack_finish(&asflags_obst);
360
361         const char *assembler = getenv("CPARSER_AS");
362         if (assembler != NULL) {
363                 obstack_printf(&asflags_obst, "%s", assembler);
364         } else {
365                 if (target_triple != NULL)
366                         obstack_printf(&asflags_obst, "%s-", target_triple);
367                 obstack_printf(&asflags_obst, "%s", ASSEMBLER);
368         }
369         if (flags[0] != '\0')
370                 obstack_printf(&asflags_obst, " %s", flags);
371
372         obstack_printf(&asflags_obst, " %s -o %s", in, out);
373         obstack_1grow(&asflags_obst, '\0');
374
375         char *commandline = obstack_finish(&asflags_obst);
376         if (verbose) {
377                 puts(commandline);
378         }
379         int err = system(commandline);
380         if (err != EXIT_SUCCESS) {
381                 fprintf(stderr, "assembler reported an error\n");
382                 exit(EXIT_FAILURE);
383         }
384         obstack_free(&asflags_obst, commandline);
385 }
386
387 static void print_file_name(const char *file)
388 {
389         add_flag(&ldflags_obst, "-print-file-name=%s", file);
390
391         obstack_1grow(&ldflags_obst, '\0');
392         const char *flags = obstack_finish(&ldflags_obst);
393
394         /* construct commandline */
395         const char *linker = getenv("CPARSER_LINK");
396         if (linker != NULL) {
397                 obstack_printf(&ldflags_obst, "%s ", linker);
398         } else {
399                 if (target_triple != NULL)
400                         obstack_printf(&ldflags_obst, "%s-", target_triple);
401                 obstack_printf(&ldflags_obst, "%s ", LINKER);
402         }
403         obstack_printf(&ldflags_obst, "%s ", linker);
404         obstack_printf(&ldflags_obst, "%s", flags);
405         obstack_1grow(&ldflags_obst, '\0');
406
407         char *commandline = obstack_finish(&ldflags_obst);
408         if (verbose) {
409                 puts(commandline);
410         }
411         int err = system(commandline);
412         if (err != EXIT_SUCCESS) {
413                 fprintf(stderr, "linker reported an error\n");
414                 exit(EXIT_FAILURE);
415         }
416         obstack_free(&ldflags_obst, commandline);
417 }
418
419 static const char *try_dir(const char *dir)
420 {
421         if (dir == NULL)
422                 return dir;
423         if (access(dir, R_OK | W_OK | X_OK) == 0)
424                 return dir;
425         return NULL;
426 }
427
428 static const char *get_tempdir(void)
429 {
430         static const char *tmpdir = NULL;
431
432         if (tmpdir != NULL)
433                 return tmpdir;
434
435         if (tmpdir == NULL)
436                 tmpdir = try_dir(getenv("TMPDIR"));
437         if (tmpdir == NULL)
438                 tmpdir = try_dir(getenv("TMP"));
439         if (tmpdir == NULL)
440                 tmpdir = try_dir(getenv("TEMP"));
441
442 #ifdef P_tmpdir
443         if (tmpdir == NULL)
444                 tmpdir = try_dir(P_tmpdir);
445 #endif
446
447         if (tmpdir == NULL)
448                 tmpdir = try_dir("/var/tmp");
449         if (tmpdir == NULL)
450                 tmpdir = try_dir("/usr/tmp");
451         if (tmpdir == NULL)
452                 tmpdir = try_dir("/tmp");
453
454         if (tmpdir == NULL)
455                 tmpdir = ".";
456
457         return tmpdir;
458 }
459
460 #ifndef HAVE_MKSTEMP
461 /* cheap and nasty mkstemp replacement */
462 static int mkstemp(char *templ)
463 {
464         mktemp(templ);
465         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
466 }
467 #endif
468
469 /**
470  * an own version of tmpnam, which: writes in a buffer, emits no warnings
471  * during linking (like glibc/gnu ld do for tmpnam)...
472  */
473 static FILE *make_temp_file(char *buffer, size_t buflen, const char *prefix)
474 {
475         const char *tempdir = get_tempdir();
476
477         snprintf(buffer, buflen, "%s/%sXXXXXX", tempdir, prefix);
478
479         int fd = mkstemp(buffer);
480         if (fd == -1) {
481                 fprintf(stderr, "could not create temporary file: %s\n",
482                         strerror(errno));
483                 exit(EXIT_FAILURE);
484         }
485         FILE *out = fdopen(fd, "w");
486         if (out == NULL) {
487                 fprintf(stderr, "could not create temporary file FILE*\n");
488                 exit(EXIT_FAILURE);
489         }
490
491         file_list_entry_t *entry = xmalloc(sizeof(*entry));
492         memset(entry, 0, sizeof(*entry));
493
494         size_t  name_len = strlen(buffer) + 1;
495         char   *name     = malloc(name_len);
496         memcpy(name, buffer, name_len);
497         entry->name      = name;
498
499         entry->next = temp_files;
500         temp_files  = entry;
501
502         return out;
503 }
504
505 static void free_temp_files(void)
506 {
507         file_list_entry_t *entry = temp_files;
508         file_list_entry_t *next;
509         for ( ; entry != NULL; entry = next) {
510                 next = entry->next;
511
512                 unlink(entry->name);
513                 free((char*) entry->name);
514                 free(entry);
515         }
516         temp_files = NULL;
517 }
518
519 typedef enum compile_mode_t {
520         BenchmarkParser,
521         PreprocessOnly,
522         ParseOnly,
523         Compile,
524         CompileDump,
525         CompileExportIR,
526         CompileAssemble,
527         CompileAssembleLink,
528         LexTest,
529         PrintAst,
530         PrintFluffy,
531         PrintJna
532 } compile_mode_t;
533
534 static void usage(const char *argv0)
535 {
536         fprintf(stderr, "Usage %s [options] input [-o output]\n", argv0);
537 }
538
539 static void print_cparser_version(void)
540 {
541         printf("cparser (%s) using libFirm (%u.%u",
542                cparser_REVISION, ir_get_version_major(),
543                ir_get_version_minor());
544
545         const char *revision = ir_get_version_revision();
546         if (revision[0] != 0) {
547                 putchar('-');
548                 fputs(revision, stdout);
549         }
550
551         const char *build = ir_get_version_build();
552         if (build[0] != 0) {
553                 putchar(' ');
554                 fputs(build, stdout);
555         }
556         puts(")");
557         puts("This is free software; see the source for copying conditions.  There is NO\n"
558              "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
559 }
560
561 static void print_cparser_version_short(void)
562 {
563         puts(cparser_REVISION);
564 }
565
566 static void print_help_basic(const char *argv0)
567 {
568         usage(argv0);
569         puts("");
570         put_help("--help",                   "Display this information");
571         put_help("--version",                "Display compiler version");
572         put_help("--help-parser",            "Display information about parser options");
573         put_help("--help-warnings",          "Display information about warning options");
574         put_help("--help-codegen",           "Display information about code-generation options");
575         put_help("--help-optimization",      "Display information about optimization options");
576         put_help("--help-linker",            "Display information about linker options");
577         put_help("--help-language-tools",    "Display information about language tools options");
578         put_help("--help-debug",             "Display information about compiler debugging options");
579         put_help("--help-firm",              "Display information about direct firm options");
580         put_help("--help-all",               "Display information about all options");
581         put_help("-c",                       "Compile and assemble but do not link");
582         put_help("-E",                       "Preprocess only");
583         put_help("-S",                       "Compile but do not assembler or link");
584         put_help("-o",                       "Specify output file");
585         put_help("-v",                       "Verbose output (show invocation of sub-processes)");
586         put_help("-x",                       "Force input language:");
587         put_choice("c",                      "C");
588         put_choice("c++",                    "C++");
589         put_choice("assembler",              "Assembler (no preprocessing)");
590         put_choice("assembler-with-cpp",     "Assembler with preprocessing");
591         put_choice("none",                   "Autodetection");
592         put_help("-pipe",                    "Ignored (gcc compatibility)");
593 }
594
595 static void print_help_preprocessor(void)
596 {
597         put_help("-nostdinc",                "Do not search standard system include directories");
598         put_help("-trigraphs",               "Support ISO C trigraphs");
599         put_help("-isystem",                 "");
600         put_help("-include",                 "");
601         put_help("-I PATH",                  "");
602         put_help("-D SYMBOL[=value]",        "");
603         put_help("-U SYMBOL",                "");
604         put_help("-Wp,OPTION",               "Pass option directly to preprocessor");
605         put_help("-M",                       "");
606         put_help("-MD",                      "");
607         put_help("-MMD",                     "");
608         put_help("-MM",                      "");
609         put_help("-MP",                      "");
610         put_help("-MT",                      "");
611         put_help("-MQ",                      "");
612         put_help("-MF",                      "");
613 }
614
615 static void print_help_parser(void)
616 {
617         put_help("-finput-charset=CHARSET",  "Select encoding of input files");
618         put_help("-fmessage-length=LEN",     "Ignored (gcc compatibility)");
619         put_help("-fshort-wchar",            "Type \"wchar_t\" is unsigned short instead of int");
620         put_help("-fshow-column",            "Show the column number in diagnostic messages");
621         put_help("-fsigned-char",            "Type \"char\" is a signed type");
622         put_help("-funsigned-char",          "Type \"char\" is an unsigned type");
623         put_help("--ms",                     "Enable msvc extensions");
624         put_help("--no-ms",                  "Disable msvc extensions");
625         put_help("--gcc",                    "Enable gcc extensions");
626         put_help("--no-gcc",                 "Disable gcc extensions");
627         put_help("-std=STANDARD",            "Specify language standard:");
628         put_choice("c99",                    "ISO C99 standard");
629         put_choice("c89",                    "ISO C89 standard");
630         put_choice("c9x",                    "Deprecated");
631         put_choice("c++",                    "ISO C++ 98");
632         put_choice("c++98",                  "ISO C++ 98");
633         put_choice("gnu99",                  "ISO C99 + GNU extensions (default)");
634         put_choice("gnu89",                  "ISO C89 + GNU extensions");
635         put_choice("gnu9x",                  "Deprecated");
636         put_choice("iso9899:1990",           "ISO C89");
637         put_choice("iso9899:199409",         "ISO C90");
638         put_choice("iso9899:1999",           "ISO C99");
639         put_choice("iso9899:199x",           "Deprecated");
640         put_help("-pedantic",                "Ignored (gcc compatibility)");
641         put_help("-ansi",                    "Ignored (gcc compatibility)");
642         put_help("--strict",                 "Enable strict conformance checking");
643 }
644
645 static void print_help_warnings(void)
646 {
647         put_help("-f[no-]diagnostics-show-option", "Show the switch, which controls a warning, after each warning");
648         put_help("-w",                             "Disable all warnings");
649         put_help("-Wno-trigraphs",                 "Warn if input contains trigraphs");
650         put_help("-Wundef",                        "Warn if an undefined macro is used in an #if");
651         put_help("-Wmissing-include-dirs",         "Warn about missing user-specified include directories");
652         put_help("-Wendif-labels",                 "Warn about stray text after #elif and #endif");
653         put_help("-Winit-self",                    "Ignored (gcc compatibility)");
654         put_help("-Wformat-y2k",                   "Ignored (gcc compatibility)");
655         put_help("-Wformat-security",              "Ignored (gcc compatibility)");
656         put_help("-Wold-style-declaration",        "Ignored (gcc compatibility)");
657         put_help("-Wtype-limits",                  "Ignored (gcc compatibility)");
658         print_warning_opt_help();
659 }
660
661 static void print_help_optimization(void)
662 {
663         put_help("-O LEVEL",                 "Select optimization level (0-4)");
664         firm_option_help(put_help);
665         put_help("-fexpensive-optimizations","Ignored (gcc compatibility)");
666 }
667
668 static void print_help_codegeneration(void)
669 {
670         put_help("-g",                       "Generate debug information");
671         put_help("-pg",                      "Instrument code for gnu gprof");
672         put_help("-fomit-frame-pointer",     "Produce code without frame pointer where possible");
673         put_help("-ffreestanding",           "Compile in freestanding mode (see ISO C standard)");
674         put_help("-fhosted",                 "Compile in hosted (not freestanding) mode");
675         put_help("-fprofile-generate",       "Generate instrumented code to collect profile information");
676         put_help("-fprofile-use",            "Use profile information generated by instrumented binaries");
677         put_help("-ffp-precise",             "Precise floating point model");
678         put_help("-ffp-fast",                "Imprecise floating point model");
679         put_help("-ffp-strict",              "Strict floating point model");
680         put_help("-pthread",                 "Use pthread threading library");
681         put_help("-mtarget=TARGET",          "Specify target architecture as CPU-manufacturer-OS triple");
682         put_help("-mtriple=TARGET",          "Alias for -mtarget (clang compatibility)");
683         put_help("-march=ARCH",              "");
684         put_help("-mtune=ARCH",              "");
685         put_help("-mcpu=CPU",                "");
686         put_help("-mfpmath=",                "");
687         put_help("-mpreferred-stack-boundary=", "");
688         put_help("-mrtd",                    "");
689         put_help("-mregparm=",               "Not supported yet");
690         put_help("-msoft-float",             "Not supported yet");
691         put_help("-m32",                     "Generate 32bit code");
692         put_help("-m64",                     "Generate 64bit code");
693         put_help("-fverbose-asm",            "Ignored (gcc compatibility)");
694         put_help("-fjump-tables",            "Ignored (gcc compatibility)");
695         put_help("-fcommon",                 "Ignored (gcc compatibility)");
696         put_help("-foptimize-sibling-calls", "Ignored (gcc compatibility)");
697         put_help("-falign-loops",            "Ignored (gcc compatibility)");
698         put_help("-falign-jumps",            "Ignored (gcc compatibility)");
699         put_help("-falign-functions",        "Ignored (gcc compatibility)");
700         put_help("-fPIC",                    "Ignored (gcc compatibility)");
701         put_help("-ffast-math",              "Same as -ffp-fast (gcc compatibility)");
702         puts("");
703         puts("\tMost of these options can be used with a no- prefix to disable them");
704         puts("\te.g. -fno-omit-frame-pointer");
705 }
706
707 static void print_help_linker(void)
708 {
709         put_help("-l LIBRARY",               "");
710         put_help("-L PATH",                  "");
711         put_help("-s",                       "Do not produce symbol table and relocation information");
712         put_help("-shared",                  "Produce a shared library");
713         put_help("-static",                  "Produce statically linked binary");
714         put_help("-Wl,OPTION",               "Pass option directly to linker");
715 }
716
717 static void print_help_debug(void)
718 {
719         put_help("--lextest",                "Preprocess and tokenize only");
720         put_help("--print-ast",              "Preprocess, parse and print AST");
721         put_help("--print-implicit-cast",    "");
722         put_help("--print-parenthesis",      "");
723         put_help("--benchmark",              "Preprocess and parse, produces no output");
724         put_help("--time",                   "Measure time of compiler passes");
725         put_help("--dump-function func",     "Preprocess, parse and output vcg graph of func");
726         put_help("--export-ir",              "Preprocess, parse and output compiler intermediate representation");
727 }
728
729 static void print_help_language_tools(void)
730 {
731         put_help("--print-fluffy",           "Preprocess, parse and generate declarations for the fluffy language");
732         put_help("--print-jna",              "Preprocess, parse and generate declarations for JNA");
733         put_help("--jna-limit filename",     "");
734         put_help("--jna-libname name",       "");
735 }
736
737 static void print_help_firm(void)
738 {
739         put_help("-bOPTION",                 "Directly pass option to libFirm backend");
740         int res = be_parse_arg("help");
741         (void) res;
742         assert(res);
743 }
744
745 typedef enum {
746         HELP_NONE          = 0,
747         HELP_BASIC         = 1 << 0,
748         HELP_PREPROCESSOR  = 1 << 1,
749         HELP_PARSER        = 1 << 2,
750         HELP_WARNINGS      = 1 << 3,
751         HELP_OPTIMIZATION  = 1 << 4,
752         HELP_CODEGEN       = 1 << 5,
753         HELP_LINKER        = 1 << 6,
754         HELP_LANGUAGETOOLS = 1 << 7,
755         HELP_DEBUG         = 1 << 8,
756         HELP_FIRM          = 1 << 9,
757
758         HELP_ALL           = -1
759 } help_sections_t;
760
761 static void print_help(const char *argv0, help_sections_t sections)
762 {
763         if (sections & HELP_BASIC)         print_help_basic(argv0);
764         if (sections & HELP_PREPROCESSOR)  print_help_preprocessor();
765         if (sections & HELP_PARSER)        print_help_parser();
766         if (sections & HELP_WARNINGS)      print_help_warnings();
767         if (sections & HELP_OPTIMIZATION)  print_help_optimization();
768         if (sections & HELP_CODEGEN)       print_help_codegeneration();
769         if (sections & HELP_LINKER)        print_help_linker();
770         if (sections & HELP_LANGUAGETOOLS) print_help_language_tools();
771         if (sections & HELP_DEBUG)         print_help_debug();
772         if (sections & HELP_FIRM)          print_help_firm();
773 }
774
775 static void set_be_option(const char *arg)
776 {
777         int res = be_parse_arg(arg);
778         (void) res;
779         assert(res);
780 }
781
782 static void copy_file(FILE *dest, FILE *input)
783 {
784         char buf[16384];
785
786         while (!feof(input) && !ferror(dest)) {
787                 size_t read = fread(buf, 1, sizeof(buf), input);
788                 if (fwrite(buf, 1, read, dest) != read) {
789                         perror("could not write output");
790                 }
791         }
792 }
793
794 static FILE *open_file(const char *filename)
795 {
796         if (streq(filename, "-")) {
797                 return stdin;
798         }
799
800         FILE *in = fopen(filename, "r");
801         if (in == NULL) {
802                 fprintf(stderr, "Could not open '%s': %s\n", filename,
803                                 strerror(errno));
804                 exit(EXIT_FAILURE);
805         }
806
807         return in;
808 }
809
810 static filetype_t get_filetype_from_string(const char *string)
811 {
812         if (streq(string, "c") || streq(string, "c-header"))
813                 return FILETYPE_C;
814         if (streq(string, "c++") || streq(string, "c++-header"))
815                 return FILETYPE_CXX;
816         if (streq(string, "assembler"))
817                 return FILETYPE_PREPROCESSED_ASSEMBLER;
818         if (streq(string, "assembler-with-cpp"))
819                 return FILETYPE_ASSEMBLER;
820         if (streq(string, "none"))
821                 return FILETYPE_AUTODETECT;
822
823         return FILETYPE_UNKNOWN;
824 }
825
826 static bool init_os_support(void)
827 {
828         wchar_atomic_kind         = ATOMIC_TYPE_INT;
829         enable_main_collect2_hack = false;
830         define_intmax_types       = false;
831
832         if (firm_is_unixish_os(target_machine)) {
833                 set_create_ld_ident(create_name_linux_elf);
834         } else if (firm_is_darwin_os(target_machine)) {
835                 set_create_ld_ident(create_name_macho);
836                 define_intmax_types = true;
837         } else if (firm_is_windows_os(target_machine)) {
838                 wchar_atomic_kind         = ATOMIC_TYPE_USHORT;
839                 enable_main_collect2_hack = true;
840                 set_create_ld_ident(create_name_win32);
841         } else {
842                 return false;
843         }
844
845         return true;
846 }
847
848 static bool parse_target_triple(const char *arg)
849 {
850         machine_triple_t *triple = firm_parse_machine_triple(arg);
851         if (triple == NULL) {
852                 fprintf(stderr, "Target-triple is not in the form 'cpu_type-manufacturer-operating_system'\n");
853                 return false;
854         }
855         target_machine = triple;
856         return true;
857 }
858
859 static unsigned decide_modulo_shift(unsigned type_size)
860 {
861         if (architecture_modulo_shift == 0)
862                 return 0;
863         if (type_size < architecture_modulo_shift)
864                 return architecture_modulo_shift;
865         return type_size;
866 }
867
868 static bool is_ia32_cpu(const char *architecture)
869 {
870         return streq(architecture, "i386")
871             || streq(architecture, "i486")
872             || streq(architecture, "i586")
873             || streq(architecture, "i686")
874             || streq(architecture, "i786");
875 }
876
877 static const char *setup_isa_from_tripel(const machine_triple_t *machine)
878 {
879         const char *cpu = machine->cpu_type;
880
881         if (is_ia32_cpu(cpu)) {
882                 return "ia32";
883         } else if (streq(cpu, "x86_64")) {
884                 return "amd64";
885         } else if (streq(cpu, "sparc")) {
886                 return "sparc";
887         } else if (streq(cpu, "arm")) {
888                 return "arm";
889         } else {
890                 fprintf(stderr, "Unknown cpu '%s' in target-triple\n", cpu);
891                 return NULL;
892         }
893 }
894
895 static const char *setup_target_machine(void)
896 {
897         if (!setup_firm_for_machine(target_machine))
898                 exit(1);
899
900         const char *isa = setup_isa_from_tripel(target_machine);
901
902         if (isa == NULL)
903                 exit(1);
904
905         init_os_support();
906
907         return isa;
908 }
909
910 /**
911  * initialize cparser type properties based on a firm type
912  */
913 static void set_typeprops_type(atomic_type_properties_t* props, ir_type *type)
914 {
915         props->size             = get_type_size_bytes(type);
916         props->alignment        = get_type_alignment_bytes(type);
917         props->struct_alignment = props->alignment;
918 }
919
920 /**
921  * Copy atomic type properties except the integer conversion rank
922  */
923 static void copy_typeprops(atomic_type_properties_t *dest,
924                            const atomic_type_properties_t *src)
925 {
926         dest->size             = src->size;
927         dest->alignment        = src->alignment;
928         dest->struct_alignment = src->struct_alignment;
929         dest->flags            = src->flags;
930 }
931
932 static void init_types_and_adjust(void)
933 {
934         const backend_params *be_params = be_get_backend_param();
935         unsigned machine_size = be_params->machine_size;
936         init_types(machine_size);
937
938         atomic_type_properties_t *props = atomic_type_properties;
939
940         /* adjust types as requested by target architecture */
941         ir_type *type_long_double = be_params->type_long_double;
942         if (type_long_double != NULL) {
943                 set_typeprops_type(&props[ATOMIC_TYPE_LONG_DOUBLE], type_long_double);
944                 atomic_modes[ATOMIC_TYPE_LONG_DOUBLE] = get_type_mode(type_long_double);
945         }
946
947         ir_type *type_long_long = be_params->type_long_long;
948         if (type_long_long != NULL)
949                 set_typeprops_type(&props[ATOMIC_TYPE_LONGLONG], type_long_long);
950
951         ir_type *type_unsigned_long_long = be_params->type_unsigned_long_long;
952         if (type_unsigned_long_long != NULL)
953                 set_typeprops_type(&props[ATOMIC_TYPE_ULONGLONG], type_unsigned_long_long);
954
955         /* operating system ABI specifics */
956         if (firm_is_darwin_os(target_machine)) {
957                 if (machine_size == 32) {
958                         props[ATOMIC_TYPE_LONGLONG].struct_alignment    =  4;
959                         props[ATOMIC_TYPE_ULONGLONG].struct_alignment   =  4;
960                         props[ATOMIC_TYPE_DOUBLE].struct_alignment      =  4;
961                         props[ATOMIC_TYPE_LONG_DOUBLE].size             = 16;
962                         props[ATOMIC_TYPE_LONG_DOUBLE].alignment        = 16;
963                         props[ATOMIC_TYPE_LONG_DOUBLE].struct_alignment = 16;
964                 }
965         } else if (firm_is_windows_os(target_machine)) {
966                 if (machine_size == 64) {
967                         /* to ease porting of old c-code microsoft decided to use 32bits
968                          * even for long */
969                         props[ATOMIC_TYPE_LONG]  = props[ATOMIC_TYPE_INT];
970                         props[ATOMIC_TYPE_ULONG] = props[ATOMIC_TYPE_UINT];
971                 }
972
973                 /* on windows long double is not supported */
974                 props[ATOMIC_TYPE_LONG_DOUBLE] = props[ATOMIC_TYPE_DOUBLE];
975         } else if (firm_is_unixish_os(target_machine)) {
976                 if (is_ia32_cpu(target_machine->cpu_type)) {
977                         /* System V has a broken alignment for double so we have to add
978                          * a hack here */
979                         props[ATOMIC_TYPE_DOUBLE].struct_alignment    = 4;
980                         props[ATOMIC_TYPE_LONGLONG].struct_alignment  = 4;
981                         props[ATOMIC_TYPE_ULONGLONG].struct_alignment = 4;
982                 }
983         }
984
985         /* stuff decided after processing operating system specifics and
986          * commandline flags */
987         if (char_is_signed) {
988                 props[ATOMIC_TYPE_CHAR].flags |= ATOMIC_TYPE_FLAG_SIGNED;
989         } else {
990                 props[ATOMIC_TYPE_CHAR].flags &= ~ATOMIC_TYPE_FLAG_SIGNED;
991         }
992         /* copy over wchar_t properties (including rank) */
993         props[ATOMIC_TYPE_WCHAR_T] = props[wchar_atomic_kind];
994
995         /* initialize defaults for unsupported types */
996         if (type_long_long == NULL) {
997                 copy_typeprops(&props[ATOMIC_TYPE_LONGLONG], &props[ATOMIC_TYPE_LONG]);
998         }
999         if (type_unsigned_long_long == NULL) {
1000                 copy_typeprops(&props[ATOMIC_TYPE_ULONGLONG],
1001                                &props[ATOMIC_TYPE_ULONG]);
1002         }
1003         if (type_long_double == NULL) {
1004                 copy_typeprops(&props[ATOMIC_TYPE_LONG_DOUBLE],
1005                                &props[ATOMIC_TYPE_DOUBLE]);
1006         }
1007
1008         /* initialize firm pointer modes */
1009         char               name[64];
1010         unsigned           bit_size     = machine_size;
1011         unsigned           modulo_shift = decide_modulo_shift(bit_size);
1012
1013         snprintf(name, sizeof(name), "p%u", machine_size);
1014         ir_mode *ptr_mode = new_reference_mode(name, irma_twos_complement, bit_size, modulo_shift);
1015
1016         if (machine_size == 16) {
1017                 set_reference_mode_signed_eq(ptr_mode, mode_Hs);
1018                 set_reference_mode_unsigned_eq(ptr_mode, mode_Hu);
1019         } else if (machine_size == 32) {
1020                 set_reference_mode_signed_eq(ptr_mode, mode_Is);
1021                 set_reference_mode_unsigned_eq(ptr_mode, mode_Iu);
1022         } else if (machine_size == 64) {
1023                 set_reference_mode_signed_eq(ptr_mode, mode_Ls);
1024                 set_reference_mode_unsigned_eq(ptr_mode, mode_Lu);
1025         } else {
1026                 panic("strange machine_size when determining pointer modes");
1027         }
1028
1029         /* Hmm, pointers should be machine size */
1030         set_modeP_data(ptr_mode);
1031         set_modeP_code(ptr_mode);
1032
1033         byte_order_big_endian = be_params->byte_order_big_endian;
1034         if (be_params->modulo_shift_efficient) {
1035                 architecture_modulo_shift = machine_size;
1036         } else {
1037                 architecture_modulo_shift = 0;
1038         }
1039 }
1040
1041 int main(int argc, char **argv)
1042 {
1043         const char        *dumpfunction         = NULL;
1044         const char        *print_file_name_file = NULL;
1045         compile_mode_t     mode                 = CompileAssembleLink;
1046         int                opt_level            = 1;
1047         int                result               = EXIT_SUCCESS;
1048         char               cpu_arch[16]         = "ia32";
1049         file_list_entry_t *files                = NULL;
1050         file_list_entry_t *last_file            = NULL;
1051         bool               construct_dep_target = false;
1052         bool               do_timing            = false;
1053         bool               profile_generate     = false;
1054         bool               profile_use          = false;
1055         struct obstack     file_obst;
1056
1057         atexit(free_temp_files);
1058
1059         /* hack for now... */
1060         if (strstr(argv[0], "pptest") != NULL) {
1061                 extern int pptest_main(int argc, char **argv);
1062                 return pptest_main(argc, argv);
1063         }
1064
1065         obstack_init(&cppflags_obst);
1066         obstack_init(&ldflags_obst);
1067         obstack_init(&asflags_obst);
1068         obstack_init(&file_obst);
1069
1070 #define GET_ARG_AFTER(def, args)                                             \
1071         do {                                                                     \
1072         def = &arg[sizeof(args)-1];                                              \
1073         if (def[0] == '\0') {                                                    \
1074                 ++i;                                                                 \
1075                 if (i >= argc) {                                                     \
1076                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
1077                         argument_errors = true;                                          \
1078                         break;                                                           \
1079                 }                                                                    \
1080                 def = argv[i];                                                       \
1081                 if (def[0] == '-' && def[1] != '\0') {                               \
1082                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
1083                         argument_errors = true;                                          \
1084                         continue;                                                        \
1085                 }                                                                    \
1086         }                                                                        \
1087         } while (0)
1088
1089 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
1090
1091         /* initialize this early because it has to parse options */
1092         gen_firm_init();
1093
1094         /* early options parsing (find out optimization level and OS) */
1095         for (int i = 1; i < argc; ++i) {
1096                 const char *arg = argv[i];
1097                 if (arg[0] != '-')
1098                         continue;
1099
1100                 const char *option = &arg[1];
1101                 if (option[0] == 'O') {
1102                         sscanf(&option[1], "%d", &opt_level);
1103                 }
1104         }
1105
1106         if (target_machine == NULL) {
1107                 target_machine = firm_get_host_machine();
1108         }
1109         choose_optimization_pack(opt_level);
1110         setup_target_machine();
1111
1112         /* parse rest of options */
1113         lang_standard_t standard        = STANDARD_DEFAULT;
1114         unsigned        features_on     = 0;
1115         unsigned        features_off    = 0;
1116         filetype_t      forced_filetype = FILETYPE_AUTODETECT;
1117         help_sections_t help            = HELP_NONE;
1118         bool            argument_errors = false;
1119         for (int i = 1; i < argc; ++i) {
1120                 const char *arg = argv[i];
1121                 if (arg[0] == '-' && arg[1] != '\0') {
1122                         /* an option */
1123                         const char *option = &arg[1];
1124                         if (option[0] == 'o') {
1125                                 GET_ARG_AFTER(outname, "-o");
1126                         } else if (option[0] == 'g') {
1127                                 /* TODO: parse -gX with 0<=x<=3... */
1128                                 set_be_option("debug=frameinfo");
1129                                 set_be_option("ia32-nooptcc=yes");
1130                         } else if (SINGLE_OPTION('c')) {
1131                                 mode = CompileAssemble;
1132                         } else if (SINGLE_OPTION('E')) {
1133                                 mode = PreprocessOnly;
1134                         } else if (SINGLE_OPTION('s')) {
1135                                 add_flag(&ldflags_obst, "-s");
1136                         } else if (SINGLE_OPTION('S')) {
1137                                 mode = Compile;
1138                         } else if (option[0] == 'O') {
1139                                 continue;
1140                         } else if (option[0] == 'I') {
1141                                 const char *opt;
1142                                 GET_ARG_AFTER(opt, "-I");
1143                                 add_flag(&cppflags_obst, "-I%s", opt);
1144                         } else if (option[0] == 'D') {
1145                                 const char *opt;
1146                                 GET_ARG_AFTER(opt, "-D");
1147                                 add_flag(&cppflags_obst, "-D%s", opt);
1148                         } else if (option[0] == 'U') {
1149                                 const char *opt;
1150                                 GET_ARG_AFTER(opt, "-U");
1151                                 add_flag(&cppflags_obst, "-U%s", opt);
1152                         } else if (option[0] == 'l') {
1153                                 const char *opt;
1154                                 GET_ARG_AFTER(opt, "-l");
1155                                 add_flag(&ldflags_obst, "-l%s", opt);
1156                         } else if (option[0] == 'L') {
1157                                 const char *opt;
1158                                 GET_ARG_AFTER(opt, "-L");
1159                                 add_flag(&ldflags_obst, "-L%s", opt);
1160                         } else if (SINGLE_OPTION('v')) {
1161                                 verbose = 1;
1162                         } else if (SINGLE_OPTION('w')) {
1163                                 add_flag(&cppflags_obst, "-w");
1164                                 disable_all_warnings();
1165                         } else if (option[0] == 'x') {
1166                                 const char *opt;
1167                                 GET_ARG_AFTER(opt, "-x");
1168                                 forced_filetype = get_filetype_from_string(opt);
1169                                 if (forced_filetype == FILETYPE_UNKNOWN) {
1170                                         fprintf(stderr, "Unknown language '%s'\n", opt);
1171                                         argument_errors = true;
1172                                 }
1173                         } else if (streq(option, "M")) {
1174                                 mode = PreprocessOnly;
1175                                 add_flag(&cppflags_obst, "-M");
1176                         } else if (streq(option, "MMD") ||
1177                                    streq(option, "MD")) {
1178                             construct_dep_target = true;
1179                                 add_flag(&cppflags_obst, "-%s", option);
1180                         } else if (streq(option, "MM")  ||
1181                                    streq(option, "MP")) {
1182                                 add_flag(&cppflags_obst, "-%s", option);
1183                         } else if (streq(option, "MT") ||
1184                                    streq(option, "MQ") ||
1185                                    streq(option, "MF")) {
1186                                 const char *opt;
1187                                 GET_ARG_AFTER(opt, "-MT");
1188                                 add_flag(&cppflags_obst, "-%s", option);
1189                                 add_flag(&cppflags_obst, "%s", opt);
1190                         } else if (streq(option, "include")) {
1191                                 const char *opt;
1192                                 GET_ARG_AFTER(opt, "-include");
1193                                 add_flag(&cppflags_obst, "-include");
1194                                 add_flag(&cppflags_obst, "%s", opt);
1195                         } else if (streq(option, "isystem")) {
1196                                 const char *opt;
1197                                 GET_ARG_AFTER(opt, "-isystem");
1198                                 add_flag(&cppflags_obst, "-isystem");
1199                                 add_flag(&cppflags_obst, "%s", opt);
1200 #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__CYGWIN__)
1201                         } else if (streq(option, "pthread")) {
1202                                 /* set flags for the preprocessor */
1203                                 add_flag(&cppflags_obst, "-D_REENTRANT");
1204                                 /* set flags for the linker */
1205                                 add_flag(&ldflags_obst, "-lpthread");
1206 #endif
1207                         } else if (streq(option, "nostdinc")
1208                                         || streq(option, "trigraphs")) {
1209                                 /* pass these through to the preprocessor */
1210                                 add_flag(&cppflags_obst, "%s", arg);
1211                         } else if (streq(option, "pipe")) {
1212                                 /* here for gcc compatibility */
1213                         } else if (streq(option, "static")) {
1214                                 add_flag(&ldflags_obst, "-static");
1215                         } else if (streq(option, "shared")) {
1216                                 add_flag(&ldflags_obst, "-shared");
1217                         } else if (option[0] == 'f') {
1218                                 char const *orig_opt;
1219                                 GET_ARG_AFTER(orig_opt, "-f");
1220
1221                                 if (strstart(orig_opt, "input-charset=")) {
1222                                         char const* const encoding = strchr(orig_opt, '=') + 1;
1223                                         input_encoding = encoding;
1224                                 } else if (strstart(orig_opt, "align-loops=") ||
1225                                            strstart(orig_opt, "align-jumps=") ||
1226                                            strstart(orig_opt, "align-functions=")) {
1227                                         fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
1228                                 } else if (strstart(orig_opt, "visibility=")) {
1229                                         const char *val = strchr(orig_opt, '=')+1;
1230                                         elf_visibility_tag_t visibility
1231                                                 = get_elf_visibility_from_string(val);
1232                                         if (visibility == ELF_VISIBILITY_ERROR) {
1233                                                 fprintf(stderr, "invalid visibility '%s' specified\n",
1234                                                         val);
1235                                                 argument_errors = true;
1236                                         } else {
1237                                                 set_default_visibility(visibility);
1238                                         }
1239                                 } else if (strstart(orig_opt, "message-length=")) {
1240                                         /* ignore: would only affect error message format */
1241                                 } else if (streq(orig_opt, "fast-math") ||
1242                                            streq(orig_opt, "fp-fast")) {
1243                                         firm_fp_model = fp_model_fast;
1244                                 } else if (streq(orig_opt, "fp-precise")) {
1245                                         firm_fp_model = fp_model_precise;
1246                                 } else if (streq(orig_opt, "fp-strict")) {
1247                                         firm_fp_model = fp_model_strict;
1248                                 } else if (streq(orig_opt, "help")) {
1249                                         fprintf(stderr, "warning: -fhelp is deprecated\n");
1250                                         help |= HELP_OPTIMIZATION;
1251                                 } else {
1252                                         /* -f options which have an -fno- variant */
1253                                         char const *opt         = orig_opt;
1254                                         bool        truth_value = true;
1255                                         if (opt[0] == 'n' && opt[1] == 'o' && opt[2] == '-') {
1256                                                 truth_value = false;
1257                                                 opt += 3;
1258                                         }
1259
1260                                         if (streq(opt, "diagnostics-show-option")) {
1261                                                 diagnostics_show_option = truth_value;
1262                                         } else if (streq(opt, "dollars-in-identifiers")) {
1263                                                 allow_dollar_in_symbol = truth_value;
1264                                         } else if (streq(opt, "omit-frame-pointer")) {
1265                                                 set_be_option(truth_value ? "omitfp" : "omitfp=no");
1266                                         } else if (streq(opt, "short-wchar")) {
1267                                                 wchar_atomic_kind = truth_value ? ATOMIC_TYPE_USHORT
1268                                                         : ATOMIC_TYPE_INT;
1269                                         } else if (streq(opt, "show-column")) {
1270                                                 show_column = truth_value;
1271                                         } else if (streq(opt, "signed-char")) {
1272                                                 char_is_signed = truth_value;
1273                                         } else if (streq(opt, "strength-reduce")) {
1274                                                 /* does nothing, for gcc compatibility (even gcc does
1275                                                  * nothing for this switch anymore) */
1276                                         } else if (streq(opt, "syntax-only")) {
1277                                                 mode = truth_value ? ParseOnly : CompileAssembleLink;
1278                                         } else if (streq(opt, "unsigned-char")) {
1279                                                 char_is_signed = !truth_value;
1280                                         } else if (streq(opt, "freestanding")) {
1281                                                 freestanding = truth_value;
1282                                         } else if (streq(opt, "hosted")) {
1283                                                 freestanding = !truth_value;
1284                                         } else if (streq(opt, "profile-generate")) {
1285                                                 profile_generate = truth_value;
1286                                         } else if (streq(opt, "profile-use")) {
1287                                                 profile_use = truth_value;
1288                                         } else if (!truth_value &&
1289                                                    streq(opt, "asynchronous-unwind-tables")) {
1290                                             /* nothing todo, a gcc feature which we do not support
1291                                              * anyway was deactivated */
1292                                         } else if (streq(opt, "verbose-asm")) {
1293                                                 /* ignore: we always print verbose assembler */
1294                                         } else if (streq(opt, "jump-tables")             ||
1295                                                    streq(opt, "expensive-optimizations") ||
1296                                                    streq(opt, "common")                  ||
1297                                                    streq(opt, "optimize-sibling-calls")  ||
1298                                                    streq(opt, "align-loops")             ||
1299                                                    streq(opt, "align-jumps")             ||
1300                                                    streq(opt, "align-functions")         ||
1301                                                    streq(opt, "unroll-loops")            ||
1302                                                    streq(opt, "PIC")                     ||
1303                                                    streq(opt, "stack-protector")         ||
1304                                                    streq(opt, "stack-protector-all")) {
1305                                                 fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
1306                                         } else {
1307                                                 int res = firm_option(orig_opt);
1308                                                 if (res == 0) {
1309                                                         fprintf(stderr, "error: unknown Firm option '-f%s'\n",
1310                                                                 orig_opt);
1311                                                         argument_errors = true;
1312                                                         continue;
1313                                                 }
1314                                         }
1315                                 }
1316                         } else if (option[0] == 'b') {
1317                                 const char *opt;
1318                                 GET_ARG_AFTER(opt, "-b");
1319
1320                                 if (streq(opt, "help")) {
1321                                         fprintf(stderr, "warning: -bhelp is deprecated (use --help-firm)\n");
1322                                         help |= HELP_FIRM;
1323                                 } else {
1324                                         int res = be_parse_arg(opt);
1325                                         if (res == 0) {
1326                                                 fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
1327                                                                 opt);
1328                                                 argument_errors = true;
1329                                         } else if (strstart(opt, "isa=")) {
1330                                                 strncpy(cpu_arch, opt, sizeof(cpu_arch));
1331                                         }
1332                                 }
1333                         } else if (option[0] == 'W') {
1334                                 if (strstart(option + 1, "p,")) {
1335                                         // pass options directly to the preprocessor
1336                                         const char *opt;
1337                                         GET_ARG_AFTER(opt, "-Wp,");
1338                                         add_flag(&cppflags_obst, "-Wp,%s", opt);
1339                                 } else if (strstart(option + 1, "l,")) {
1340                                         // pass options directly to the linker
1341                                         const char *opt;
1342                                         GET_ARG_AFTER(opt, "-Wl,");
1343                                         add_flag(&ldflags_obst, "-Wl,%s", opt);
1344                                 } else if (streq(option + 1, "no-trigraphs")
1345                                                         || streq(option + 1, "undef")
1346                                                         || streq(option + 1, "missing-include-dirs")
1347                                                         || streq(option + 1, "endif-labels")) {
1348                                         add_flag(&cppflags_obst, "%s", arg);
1349                                 } else if (streq(option+1, "init-self")) {
1350                                         /* ignored (same as gcc does) */
1351                                 } else if (streq(option+1, "format-y2k")
1352                                            || streq(option+1, "format-security")
1353                                            || streq(option+1, "old-style-declaration")
1354                                            || streq(option+1, "type-limits")) {
1355                                     /* ignore (gcc compatibility) */
1356                                 } else {
1357                                         set_warning_opt(&option[1]);
1358                                 }
1359                         } else if (option[0] == 'm') {
1360                                 /* -m options */
1361                                 const char *opt;
1362                                 char arch_opt[64];
1363
1364                                 GET_ARG_AFTER(opt, "-m");
1365                                 if (strstart(opt, "target=")) {
1366                                         GET_ARG_AFTER(opt, "-mtarget=");
1367                                         if (!parse_target_triple(opt)) {
1368                                                 argument_errors = true;
1369                                         } else {
1370                                                 const char *isa = setup_target_machine();
1371                                                 strncpy(cpu_arch, isa, sizeof(cpu_arch));
1372                                                 target_triple = opt;
1373                                         }
1374                                 } else if (strstart(opt, "triple=")) {
1375                                         GET_ARG_AFTER(opt, "-mtriple=");
1376                                         if (!parse_target_triple(opt)) {
1377                                                 argument_errors = true;
1378                                         } else {
1379                                                 const char *isa = setup_target_machine();
1380                                                 strncpy(cpu_arch, isa, sizeof(cpu_arch));
1381                                                 target_triple = opt;
1382                                         }
1383                                 } else if (strstart(opt, "arch=")) {
1384                                         GET_ARG_AFTER(opt, "-march=");
1385                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
1386                                         int res = be_parse_arg(arch_opt);
1387                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
1388                                         res &= be_parse_arg(arch_opt);
1389
1390                                         if (res == 0) {
1391                                                 fprintf(stderr, "Unknown architecture '%s'\n", arch_opt);
1392                                                 argument_errors = true;
1393                                         }
1394                                 } else if (strstart(opt, "tune=")) {
1395                                         GET_ARG_AFTER(opt, "-mtune=");
1396                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
1397                                         int res = be_parse_arg(arch_opt);
1398                                         if (res == 0)
1399                                                 argument_errors = true;
1400                                 } else if (strstart(opt, "cpu=")) {
1401                                         GET_ARG_AFTER(opt, "-mcpu=");
1402                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
1403                                         int res = be_parse_arg(arch_opt);
1404                                         if (res == 0)
1405                                                 argument_errors = true;
1406                                 } else if (strstart(opt, "fpmath=")) {
1407                                         GET_ARG_AFTER(opt, "-mfpmath=");
1408                                         if (streq(opt, "387"))
1409                                                 opt = "x87";
1410                                         else if (streq(opt, "sse"))
1411                                                 opt = "sse2";
1412                                         else {
1413                                                 fprintf(stderr, "error: option -mfpmath supports only 387 or sse\n");
1414                                                 argument_errors = true;
1415                                         }
1416                                         if (!argument_errors) {
1417                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
1418                                                 int res = be_parse_arg(arch_opt);
1419                                                 if (res == 0)
1420                                                         argument_errors = true;
1421                                         }
1422                                 } else if (strstart(opt, "preferred-stack-boundary=")) {
1423                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
1424                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
1425                                         int res = be_parse_arg(arch_opt);
1426                                         if (res == 0)
1427                                                 argument_errors = true;
1428                                 } else if (streq(opt, "rtd")) {
1429                                         default_calling_convention = CC_STDCALL;
1430                                 } else if (strstart(opt, "regparm=")) {
1431                                         fprintf(stderr, "error: regparm convention not supported yet\n");
1432                                         argument_errors = true;
1433                                 } else if (streq(opt, "soft-float")) {
1434                                         add_flag(&ldflags_obst, "-msoft-float");
1435                                         snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=softfloat", cpu_arch);
1436                                         int res = be_parse_arg(arch_opt);
1437                                         if (res == 0)
1438                                                 argument_errors = true;
1439                                 } else if (streq(opt, "sse2")) {
1440                                         /* ignore for now, our x86 backend always uses sse when
1441                                          * sse is requested */
1442                                 } else {
1443                                         long int value = strtol(opt, NULL, 10);
1444                                         if (value == 0) {
1445                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
1446                                                 argument_errors = true;
1447                                         } else if (value != 16 && value != 32 && value != 64) {
1448                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
1449                                                 argument_errors = true;
1450                                         } else {
1451                                                 unsigned machine_size = (unsigned)value;
1452                                                 /* TODO: choose/change backend based on this */
1453                                                 add_flag(&cppflags_obst, "-m%u", machine_size);
1454                                                 add_flag(&asflags_obst, "-m%u", machine_size);
1455                                                 add_flag(&ldflags_obst, "-m%u", machine_size);
1456                                         }
1457                                 }
1458                         } else if (streq(option, "pg")) {
1459                                 set_be_option("gprof");
1460                                 add_flag(&ldflags_obst, "-pg");
1461                         } else if (streq(option, "ansi")) {
1462                                 add_flag(&cppflags_obst, "-ansi");
1463                         } else if (streq(option, "pedantic")) {
1464                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
1465                         } else if (strstart(option, "std=")) {
1466                                 const char *const o = &option[4];
1467                                 standard =
1468                                         streq(o, "c++")            ? STANDARD_CXX98   :
1469                                         streq(o, "c++98")          ? STANDARD_CXX98   :
1470                                         streq(o, "c89")            ? STANDARD_C89     :
1471                                         streq(o, "c90")            ? STANDARD_C89     :
1472                                         streq(o, "c99")            ? STANDARD_C99     :
1473                                         streq(o, "c9x")            ? STANDARD_C99     : // deprecated
1474                                         streq(o, "gnu++98")        ? STANDARD_GNUXX98 :
1475                                         streq(o, "gnu89")          ? STANDARD_GNU89   :
1476                                         streq(o, "gnu99")          ? STANDARD_GNU99   :
1477                                         streq(o, "gnu9x")          ? STANDARD_GNU99   : // deprecated
1478                                         streq(o, "iso9899:1990")   ? STANDARD_C89     :
1479                                         streq(o, "iso9899:199409") ? STANDARD_C89AMD1 :
1480                                         streq(o, "iso9899:1999")   ? STANDARD_C99     :
1481                                         streq(o, "iso9899:199x")   ? STANDARD_C99     : // deprecated
1482                                         (fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg), standard);
1483                         } else if (streq(option, "version")) {
1484                                 print_cparser_version();
1485                                 return EXIT_SUCCESS;
1486                         } else if (streq(option, "dumpversion")) {
1487                                 /* gcc compatibility option */
1488                                 print_cparser_version_short();
1489                                 return EXIT_SUCCESS;
1490                         } else if (strstart(option, "print-file-name=")) {
1491                                 GET_ARG_AFTER(print_file_name_file, "-print-file-name=");
1492                         } else if (option[0] == '-') {
1493                                 /* double dash option */
1494                                 ++option;
1495                                 if (streq(option, "gcc")) {
1496                                         features_on  |=  _GNUC;
1497                                         features_off &= ~_GNUC;
1498                                 } else if (streq(option, "no-gcc")) {
1499                                         features_on  &= ~_GNUC;
1500                                         features_off |=  _GNUC;
1501                                 } else if (streq(option, "ms")) {
1502                                         features_on  |=  _MS;
1503                                         features_off &= ~_MS;
1504                                 } else if (streq(option, "no-ms")) {
1505                                         features_on  &= ~_MS;
1506                                         features_off |=  _MS;
1507                                 } else if (streq(option, "strict")) {
1508                                         strict_mode = true;
1509                                 } else if (streq(option, "lextest")) {
1510                                         mode = LexTest;
1511                                 } else if (streq(option, "benchmark")) {
1512                                         mode = BenchmarkParser;
1513                                 } else if (streq(option, "print-ast")) {
1514                                         mode = PrintAst;
1515                                 } else if (streq(option, "print-implicit-cast")) {
1516                                         print_implicit_casts = true;
1517                                 } else if (streq(option, "print-parenthesis")) {
1518                                         print_parenthesis = true;
1519                                 } else if (streq(option, "print-fluffy")) {
1520                                         mode = PrintFluffy;
1521                                 } else if (streq(option, "print-jna")) {
1522                                         mode = PrintJna;
1523                                 } else if (streq(option, "jna-limit")) {
1524                                         ++i;
1525                                         if (i >= argc) {
1526                                                 fprintf(stderr, "error: "
1527                                                         "expected argument after '--jna-limit'\n");
1528                                                 argument_errors = true;
1529                                                 break;
1530                                         }
1531                                         jna_limit_output(argv[i]);
1532                                 } else if (streq(option, "jna-libname")) {
1533                                         ++i;
1534                                         if (i >= argc) {
1535                                                 fprintf(stderr, "error: "
1536                                                         "expected argument after '--jna-libname'\n");
1537                                                 argument_errors = true;
1538                                                 break;
1539                                         }
1540                                         jna_set_libname(argv[i]);
1541                                 } else if (streq(option, "time")) {
1542                                         do_timing = true;
1543                                 } else if (streq(option, "version")) {
1544                                         print_cparser_version();
1545                                         return EXIT_SUCCESS;
1546                                 } else if (streq(option, "help")) {
1547                                         help |= HELP_BASIC;
1548                                 } else if (streq(option, "help-parser")) {
1549                                         help |= HELP_PARSER;
1550                                 } else if (streq(option, "help-warnings")) {
1551                                         help |= HELP_WARNINGS;
1552                                 } else if (streq(option, "help-codegen")) {
1553                                         help |= HELP_CODEGEN;
1554                                 } else if (streq(option, "help-linker")) {
1555                                         help |= HELP_LINKER;
1556                                 } else if (streq(option, "help-optimization")) {
1557                                         help |= HELP_OPTIMIZATION;
1558                                 } else if (streq(option, "help-language-tools")) {
1559                                         help |= HELP_LANGUAGETOOLS;
1560                                 } else if (streq(option, "help-debug")) {
1561                                         help |= HELP_DEBUG;
1562                                 } else if (streq(option, "help-firm")) {
1563                                         help |= HELP_FIRM;
1564                                 } else if (streq(option, "help-all")) {
1565                                         help |= HELP_ALL;
1566                                 } else if (streq(option, "dump-function")) {
1567                                         ++i;
1568                                         if (i >= argc) {
1569                                                 fprintf(stderr, "error: "
1570                                                         "expected argument after '--dump-function'\n");
1571                                                 argument_errors = true;
1572                                                 break;
1573                                         }
1574                                         dumpfunction = argv[i];
1575                                         mode         = CompileDump;
1576                                 } else if (streq(option, "export-ir")) {
1577                                         mode = CompileExportIR;
1578                                 } else if (streq(option, "unroll-loops")) {
1579                                         /* ignore (gcc compatibility) */
1580                                 } else {
1581                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
1582                                         argument_errors = true;
1583                                 }
1584                         } else {
1585                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
1586                                 argument_errors = true;
1587                         }
1588                 } else {
1589                         filetype_t type = forced_filetype;
1590                         if (type == FILETYPE_AUTODETECT) {
1591                                 if (streq(arg, "-")) {
1592                                         /* - implicitly means C source file */
1593                                         type = FILETYPE_C;
1594                                 } else {
1595                                         const char *suffix = strrchr(arg, '.');
1596                                         /* Ensure there is at least one char before the suffix */
1597                                         if (suffix != NULL && suffix != arg) {
1598                                                 ++suffix;
1599                                                 type =
1600                                                         streq(suffix, "S")   ? FILETYPE_ASSEMBLER              :
1601                                                         streq(suffix, "a")   ? FILETYPE_OBJECT                 :
1602                                                         streq(suffix, "c")   ? FILETYPE_C                      :
1603                                                         streq(suffix, "i")   ? FILETYPE_PREPROCESSED_C         :
1604                                                         streq(suffix, "C")   ? FILETYPE_CXX                    :
1605                                                         streq(suffix, "cc")  ? FILETYPE_CXX                    :
1606                                                         streq(suffix, "cp")  ? FILETYPE_CXX                    :
1607                                                         streq(suffix, "cpp") ? FILETYPE_CXX                    :
1608                                                         streq(suffix, "CPP") ? FILETYPE_CXX                    :
1609                                                         streq(suffix, "cxx") ? FILETYPE_CXX                    :
1610                                                         streq(suffix, "c++") ? FILETYPE_CXX                    :
1611                                                         streq(suffix, "ii")  ? FILETYPE_PREPROCESSED_CXX       :
1612                                                         streq(suffix, "h")   ? FILETYPE_C                      :
1613                                                         streq(suffix, "ir")  ? FILETYPE_IR                     :
1614                                                         streq(suffix, "o")   ? FILETYPE_OBJECT                 :
1615                                                         streq(suffix, "s")   ? FILETYPE_PREPROCESSED_ASSEMBLER :
1616                                                         streq(suffix, "so")  ? FILETYPE_OBJECT                 :
1617                                                         FILETYPE_OBJECT; /* gcc behavior: unknown file extension means object file */
1618                                         }
1619                                 }
1620                         }
1621
1622                         file_list_entry_t *entry
1623                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
1624                         memset(entry, 0, sizeof(entry[0]));
1625                         entry->name = arg;
1626                         entry->type = type;
1627
1628                         if (last_file != NULL) {
1629                                 last_file->next = entry;
1630                         } else {
1631                                 files = entry;
1632                         }
1633                         last_file = entry;
1634                 }
1635         }
1636
1637         if (help != HELP_NONE) {
1638                 print_help(argv[0], help);
1639                 return !argument_errors;
1640         }
1641
1642         if (print_file_name_file != NULL) {
1643                 print_file_name(print_file_name_file);
1644                 return EXIT_SUCCESS;
1645         }
1646         if (files == NULL) {
1647                 fprintf(stderr, "error: no input files specified\n");
1648                 argument_errors = true;
1649         }
1650
1651         if (argument_errors) {
1652                 usage(argv[0]);
1653                 return EXIT_FAILURE;
1654         }
1655
1656         /* apply some effects from switches */
1657         c_mode |= features_on;
1658         c_mode &= ~features_off;
1659         if (profile_generate) {
1660                 add_flag(&ldflags_obst, "-lfirmprof");
1661                 set_be_option("profilegenerate");
1662         }
1663         if (profile_use) {
1664                 set_be_option("profileuse");
1665         }
1666
1667         init_symbol_table();
1668         init_types_and_adjust();
1669         init_typehash();
1670         init_basic_types();
1671         if (wchar_atomic_kind == ATOMIC_TYPE_INT)
1672                 init_wchar_types(type_int);
1673         else if (wchar_atomic_kind == ATOMIC_TYPE_USHORT)
1674                 init_wchar_types(type_short);
1675         else
1676                 panic("unexpected wchar type");
1677         init_preprocessor();
1678         init_ast();
1679         init_parser();
1680         init_ast2firm();
1681         init_mangle();
1682
1683         if (do_timing)
1684                 timer_init();
1685
1686         if (construct_dep_target) {
1687                 if (outname != 0 && strlen(outname) >= 2) {
1688                         get_output_name(dep_target, sizeof(dep_target), outname, ".d");
1689                 } else {
1690                         get_output_name(dep_target, sizeof(dep_target), files->name, ".d");
1691                 }
1692         } else {
1693                 dep_target[0] = '\0';
1694         }
1695
1696         char outnamebuf[4096];
1697         if (outname == NULL) {
1698                 const char *filename = files->name;
1699
1700                 switch(mode) {
1701                 case BenchmarkParser:
1702                 case PrintAst:
1703                 case PrintFluffy:
1704                 case PrintJna:
1705                 case LexTest:
1706                 case PreprocessOnly:
1707                 case ParseOnly:
1708                         outname = "-";
1709                         break;
1710                 case Compile:
1711                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".s");
1712                         outname = outnamebuf;
1713                         break;
1714                 case CompileAssemble:
1715                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".o");
1716                         outname = outnamebuf;
1717                         break;
1718                 case CompileDump:
1719                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
1720                                         ".vcg");
1721                         outname = outnamebuf;
1722                         break;
1723                 case CompileExportIR:
1724                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".ir");
1725                         outname = outnamebuf;
1726                         break;
1727                 case CompileAssembleLink:
1728 #ifdef _WIN32
1729                         outname = "a.exe";
1730 #else
1731                         outname = "a.out";
1732 #endif
1733                         break;
1734                 }
1735         }
1736
1737         assert(outname != NULL);
1738
1739         FILE *out;
1740         if (streq(outname, "-")) {
1741                 out = stdout;
1742         } else {
1743                 out = fopen(outname, "w");
1744                 if (out == NULL) {
1745                         fprintf(stderr, "Could not open '%s' for writing: %s\n", outname,
1746                                         strerror(errno));
1747                         return EXIT_FAILURE;
1748                 }
1749         }
1750
1751         file_list_entry_t *file;
1752         bool               already_constructed_firm = false;
1753         for (file = files; file != NULL; file = file->next) {
1754                 char            asm_tempfile[1024];
1755                 const char     *filename = file->name;
1756                 filetype_t      filetype = file->type;
1757                 lang_standard_t file_standard = standard;
1758
1759                 if (filetype == FILETYPE_OBJECT)
1760                         continue;
1761                 if (file_standard == STANDARD_DEFAULT) {
1762                         switch (filetype) {
1763                         case FILETYPE_C:
1764                         case FILETYPE_PREPROCESSED_C:
1765                                 file_standard = STANDARD_GNU99;
1766                                 break;
1767                         case FILETYPE_CXX:
1768                         case FILETYPE_PREPROCESSED_CXX:
1769                                 file_standard = STANDARD_GNUXX98;
1770                                 break;
1771                         default:
1772                                 break;
1773                         }
1774                 }
1775
1776                 FILE *in = NULL;
1777                 if (mode == LexTest) {
1778                         if (in == NULL)
1779                                 in = open_file(filename);
1780                         lextest(in, filename);
1781                         fclose(in);
1782                         return EXIT_SUCCESS;
1783                 }
1784
1785                 FILE *preprocessed_in = NULL;
1786                 filetype_t next_filetype = filetype;
1787                 switch (filetype) {
1788                         case FILETYPE_C:
1789                                 next_filetype = FILETYPE_PREPROCESSED_C;
1790                                 goto preprocess;
1791                         case FILETYPE_CXX:
1792                                 next_filetype = FILETYPE_PREPROCESSED_CXX;
1793                                 goto preprocess;
1794                         case FILETYPE_ASSEMBLER:
1795                                 next_filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1796                                 goto preprocess;
1797 preprocess:
1798                                 /* no support for input on FILE* yet */
1799                                 if (in != NULL)
1800                                         panic("internal compiler error: in for preprocessor != NULL");
1801
1802                                 preprocessed_in = preprocess(filename, filetype,
1803                                                              file_standard);
1804                                 if (mode == PreprocessOnly) {
1805                                         copy_file(out, preprocessed_in);
1806                                         int pp_result = pclose(preprocessed_in);
1807                                         fclose(out);
1808                                         /* remove output file in case of error */
1809                                         if (out != stdout && pp_result != EXIT_SUCCESS) {
1810                                                 unlink(outname);
1811                                         }
1812                                         return pp_result;
1813                                 }
1814
1815                                 in = preprocessed_in;
1816                                 filetype = next_filetype;
1817                                 break;
1818
1819                         default:
1820                                 break;
1821                 }
1822
1823                 FILE *asm_out;
1824                 if (mode == Compile) {
1825                         asm_out = out;
1826                 } else {
1827                         asm_out = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "ccs");
1828                 }
1829
1830                 if (in == NULL)
1831                         in = open_file(filename);
1832
1833                 /* preprocess and compile */
1834                 if (filetype == FILETYPE_PREPROCESSED_C) {
1835                         switch (file_standard) {
1836                         case STANDARD_C89:     c_mode = _C89;                break;
1837                         /* TODO determine difference between these two */
1838                         case STANDARD_C89AMD1: c_mode = _C89;                break;
1839                         case STANDARD_C99:     c_mode = _C89 | _C99;         break;
1840                         case STANDARD_GNU89:   c_mode = _C89 |        _GNUC; break;
1841
1842                         case STANDARD_CXX98:
1843                         case STANDARD_GNUXX98:
1844                         case STANDARD_DEFAULT:
1845                                 fprintf(stderr, "warning: command line option \"-std=%s\" is not valid for C\n", str_lang_standard(file_standard));
1846                                 /* FALLTHROUGH */
1847                         case STANDARD_GNU99:   c_mode = _C89 | _C99 | _GNUC; break;
1848                         }
1849                         goto do_parsing;
1850                 } else if (filetype == FILETYPE_PREPROCESSED_CXX) {
1851                         switch (file_standard) {
1852                         case STANDARD_CXX98: c_mode = _CXX; break;
1853
1854                         case STANDARD_C89:
1855                         case STANDARD_C89AMD1:
1856                         case STANDARD_C99:
1857                         case STANDARD_GNU89:
1858                         case STANDARD_GNU99:
1859                         case STANDARD_DEFAULT:
1860                                 fprintf(stderr, "warning: command line option \"-std=%s\" is not valid for C++\n", str_lang_standard(file_standard));
1861                                 /* FALLTHROUGH */
1862                         case STANDARD_GNUXX98: c_mode = _CXX | _GNUC; break;
1863                         }
1864
1865 do_parsing:
1866                         c_mode |= features_on;
1867                         c_mode &= ~features_off;
1868
1869                         /* do the actual parsing */
1870                         ir_timer_t *t_parsing = ir_timer_new();
1871                         timer_register(t_parsing, "Frontend: Parsing");
1872                         timer_push(t_parsing);
1873                         init_tokens();
1874                         translation_unit_t *const unit = do_parsing(in, filename);
1875                         timer_pop(t_parsing);
1876
1877                         /* prints the AST even if errors occurred */
1878                         if (mode == PrintAst) {
1879                                 print_to_file(out);
1880                                 print_ast(unit);
1881                         }
1882
1883                         if (error_count > 0) {
1884                                 /* parsing failed because of errors */
1885                                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count,
1886                                         warning_count);
1887                                 result = EXIT_FAILURE;
1888                                 continue;
1889                         } else if (warning_count > 0) {
1890                                 fprintf(stderr, "%u warning(s)\n", warning_count);
1891                         }
1892
1893                         if (in == preprocessed_in) {
1894                                 int pp_result = pclose(preprocessed_in);
1895                                 if (pp_result != EXIT_SUCCESS) {
1896                                         /* remove output file */
1897                                         if (out != stdout)
1898                                                 unlink(outname);
1899                                         return EXIT_FAILURE;
1900                                 }
1901                         }
1902
1903                         if (mode == BenchmarkParser) {
1904                                 return result;
1905                         } else if (mode == PrintFluffy) {
1906                                 write_fluffy_decls(out, unit);
1907                                 continue;
1908                         } else if (mode == PrintJna) {
1909                                 write_jna_decls(out, unit);
1910                                 continue;
1911                         }
1912
1913                         /* build the firm graph */
1914                         ir_timer_t *t_construct = ir_timer_new();
1915                         timer_register(t_construct, "Frontend: Graph construction");
1916                         timer_push(t_construct);
1917                         if (already_constructed_firm) {
1918                                 panic("compiling multiple files/translation units not possible");
1919                         }
1920                         init_implicit_optimizations();
1921                         translation_unit_to_firm(unit);
1922                         already_constructed_firm = true;
1923                         timer_pop(t_construct);
1924
1925 graph_built:
1926                         if (mode == ParseOnly) {
1927                                 continue;
1928                         }
1929
1930                         if (mode == CompileDump) {
1931                                 /* find irg */
1932                                 ident    *id     = new_id_from_str(dumpfunction);
1933                                 ir_graph *irg    = NULL;
1934                                 int       n_irgs = get_irp_n_irgs();
1935                                 for (int i = 0; i < n_irgs; ++i) {
1936                                         ir_graph *tirg   = get_irp_irg(i);
1937                                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
1938                                         if (irg_id == id) {
1939                                                 irg = tirg;
1940                                                 break;
1941                                         }
1942                                 }
1943
1944                                 if (irg == NULL) {
1945                                         fprintf(stderr, "No graph for function '%s' found\n",
1946                                                 dumpfunction);
1947                                         return EXIT_FAILURE;
1948                                 }
1949
1950                                 dump_ir_graph_file(out, irg);
1951                                 fclose(out);
1952                                 return EXIT_SUCCESS;
1953                         }
1954
1955                         if (mode == CompileExportIR) {
1956                                 ir_export_file(out);
1957                                 if (ferror(out) != 0) {
1958                                         fprintf(stderr, "Error while writing to output\n");
1959                                         return EXIT_FAILURE;
1960                                 }
1961                                 return EXIT_SUCCESS;
1962                         }
1963
1964                         generate_code(asm_out, filename);
1965                         if (asm_out != out) {
1966                                 fclose(asm_out);
1967                         }
1968                 } else if (filetype == FILETYPE_IR) {
1969                         fclose(in);
1970                         int res = ir_import(filename);
1971                         if (res != 0) {
1972                                 fprintf(stderr, "Firm-Program import failed\n");
1973                                 return EXIT_FAILURE;
1974                         }
1975                         goto graph_built;
1976                 } else if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1977                         copy_file(asm_out, in);
1978                         if (in == preprocessed_in) {
1979                                 int pp_result = pclose(preprocessed_in);
1980                                 if (pp_result != EXIT_SUCCESS) {
1981                                         /* remove output in error case */
1982                                         if (out != stdout)
1983                                                 unlink(outname);
1984                                         return pp_result;
1985                                 }
1986                         }
1987                         if (asm_out != out) {
1988                                 fclose(asm_out);
1989                         }
1990                 }
1991
1992                 if (mode == Compile)
1993                         continue;
1994
1995                 /* if we're here then we have preprocessed assembly */
1996                 filename = asm_tempfile;
1997                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1998
1999                 /* assemble */
2000                 if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
2001                         char        temp[1024];
2002                         const char *filename_o;
2003                         if (mode == CompileAssemble) {
2004                                 fclose(out);
2005                                 filename_o = outname;
2006                         } else {
2007                                 FILE *tempf = make_temp_file(temp, sizeof(temp), "cco");
2008                                 fclose(tempf);
2009                                 filename_o = temp;
2010                         }
2011
2012                         assemble(filename_o, filename);
2013
2014                         size_t len = strlen(filename_o) + 1;
2015                         filename = obstack_copy(&file_obst, filename_o, len);
2016                         filetype = FILETYPE_OBJECT;
2017                 }
2018
2019                 /* ok we're done here, process next file */
2020                 file->name = filename;
2021                 file->type = filetype;
2022         }
2023
2024         if (result != EXIT_SUCCESS) {
2025                 if (out != stdout)
2026                         unlink(outname);
2027                 return result;
2028         }
2029
2030         /* link program file */
2031         if (mode == CompileAssembleLink) {
2032                 obstack_1grow(&ldflags_obst, '\0');
2033                 const char *flags = obstack_finish(&ldflags_obst);
2034
2035                 /* construct commandline */
2036                 const char *linker = getenv("CPARSER_LINK");
2037                 if (linker != NULL) {
2038                         obstack_printf(&file_obst, "%s ", linker);
2039                 } else {
2040                         if (target_triple != NULL)
2041                                 obstack_printf(&file_obst, "%s-", target_triple);
2042                         obstack_printf(&file_obst, "%s ", LINKER);
2043                 }
2044
2045                 for (file_list_entry_t *entry = files; entry != NULL;
2046                                 entry = entry->next) {
2047                         if (entry->type != FILETYPE_OBJECT)
2048                                 continue;
2049
2050                         add_flag(&file_obst, "%s", entry->name);
2051                 }
2052
2053                 add_flag(&file_obst, "-o");
2054                 add_flag(&file_obst, outname);
2055                 obstack_printf(&file_obst, "%s", flags);
2056                 obstack_1grow(&file_obst, '\0');
2057
2058                 char *commandline = obstack_finish(&file_obst);
2059
2060                 if (verbose) {
2061                         puts(commandline);
2062                 }
2063                 int err = system(commandline);
2064                 if (err != EXIT_SUCCESS) {
2065                         fprintf(stderr, "linker reported an error\n");
2066                         return EXIT_FAILURE;
2067                 }
2068         }
2069
2070         if (do_timing)
2071                 timer_term(stderr);
2072
2073         obstack_free(&cppflags_obst, NULL);
2074         obstack_free(&ldflags_obst, NULL);
2075         obstack_free(&asflags_obst, NULL);
2076         obstack_free(&file_obst, NULL);
2077
2078         gen_firm_finish();
2079         exit_mangle();
2080         exit_ast2firm();
2081         exit_parser();
2082         exit_ast();
2083         exit_preprocessor();
2084         exit_typehash();
2085         exit_types();
2086         exit_tokens();
2087         exit_symbol_table();
2088         return EXIT_SUCCESS;
2089 }