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