ignore TARGET environment variable (Makefiles tend to set that and confuse cparser)
[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_cparser_version_short(void)
554 {
555         puts(cparser_REVISION);
556 }
557
558 static void print_help_basic(const char *argv0)
559 {
560         usage(argv0);
561         puts("");
562         put_help("--help",                   "Display this information");
563         put_help("--version",                "Display compiler version");
564         put_help("--help-parser",            "Display information about parser options");
565         put_help("--help-warnings",          "Display information about warning options");
566         put_help("--help-codegen",           "Display information about code-generation options");
567         put_help("--help-optimization",      "Display information about optimization options");
568         put_help("--help-linker",            "Display information about linker options");
569         put_help("--help-language-tools",    "Display information about language tools options");
570         put_help("--help-debug",             "Display information about compiler debugging options");
571         put_help("--help-firm",              "Display information about direct firm options");
572         put_help("--help-all",               "Display information about all options");
573         put_help("-c",                       "Compile and assemble but do not link");
574         put_help("-E",                       "Preprocess only");
575         put_help("-S",                       "Compile but do not assembler or link");
576         put_help("-o",                       "Specify output file");
577         put_help("-v",                       "Verbose output (show invocation of sub-processes)");
578         put_help("-x",                       "Force input language:");
579         put_choice("c",                      "C");
580         put_choice("c++",                    "C++");
581         put_choice("assembler",              "Assembler (no preprocessing)");
582         put_choice("assembler-with-cpp",     "Assembler with preprocessing");
583         put_choice("none",                   "Autodetection");
584         put_help("-pipe",                    "Ignored (gcc compatibility)");
585 }
586
587 static void print_help_preprocessor(void)
588 {
589         put_help("-nostdinc",                "Do not search standard system include directories");
590         put_help("-trigraphs",               "Support ISO C trigraphs");
591         put_help("-isystem",                 "");
592         put_help("-include",                 "");
593         put_help("-I PATH",                  "");
594         put_help("-D SYMBOL[=value]",        "");
595         put_help("-U SYMBOL",                "");
596         put_help("-Wp,OPTION",               "Pass option directly to preprocessor");
597         put_help("-M",                       "");
598         put_help("-MD",                      "");
599         put_help("-MMD",                     "");
600         put_help("-MM",                      "");
601         put_help("-MP",                      "");
602         put_help("-MT",                      "");
603         put_help("-MQ",                      "");
604         put_help("-MF",                      "");
605 }
606
607 static void print_help_parser(void)
608 {
609         put_help("-finput-charset=CHARSET",  "Select encoding of input files");
610         put_help("-fmessage-length=LEN",     "Ignored (gcc compatibility)");
611         put_help("-fshort-wchar",            "Type \"wchar_t\" is unsigned short instead of int");
612         put_help("-fshow-column",            "Show the column number in diagnostic messages");
613         put_help("-fsigned-char",            "Type \"char\" is a signed type");
614         put_help("-funsigned-char",          "Type \"char\" is an unsigned type");
615         put_help("--ms",                     "Enable msvc extensions");
616         put_help("--no-ms",                  "Disable msvc extensions");
617         put_help("--gcc",                    "Enable gcc extensions");
618         put_help("--no-gcc",                 "Disable gcc extensions");
619         put_help("-std=STANDARD",            "Specify language standard:");
620         put_choice("c99",                    "ISO C99 standard");
621         put_choice("c89",                    "ISO C89 standard");
622         put_choice("c9x",                    "Deprecated");
623         put_choice("c++",                    "ISO C++ 98");
624         put_choice("c++98",                  "ISO C++ 98");
625         put_choice("gnu99",                  "ISO C99 + GNU extensions (default)");
626         put_choice("gnu89",                  "ISO C89 + GNU extensions");
627         put_choice("gnu9x",                  "Deprecated");
628         put_choice("iso9899:1990",           "ISO C89");
629         put_choice("iso9899:199409",         "ISO C90");
630         put_choice("iso9899:1999",           "ISO C99");
631         put_choice("iso9899:199x",           "Deprecated");
632         put_help("-pedantic",                "Ignored (gcc compatibility)");
633         put_help("-ansi",                    "Ignored (gcc compatibility)");
634         put_help("--strict",                 "Enable strict conformance checking");
635 }
636
637 static void print_help_warnings(void)
638 {
639         put_help("-f[no-]diagnostics-show-option", "Show the switch, which controls a warning, after each warning");
640         put_help("-w",                             "Disable all warnings");
641         put_help("-Wno-trigraphs",                 "Warn if input contains trigraphs");
642         put_help("-Wundef",                        "Warn if an undefined macro is used in an #if");
643         put_help("-Wmissing-include-dirs",         "Warn about missing user-specified include directories");
644         put_help("-Wendif-labels",                 "Warn about stray text after #elif and #endif");
645         put_help("-Winit-self",                    "Ignored (gcc compatibility)");
646         put_help("-Wformat-y2k",                   "Ignored (gcc compatibility)");
647         put_help("-Wformat-security",              "Ignored (gcc compatibility)");
648         put_help("-Wold-style-declaration",        "Ignored (gcc compatibility)");
649         put_help("-Wtype-limits",                  "Ignored (gcc compatibility)");
650         print_warning_opt_help();
651 }
652
653 static void print_help_optimization(void)
654 {
655         put_help("-O LEVEL",                 "Select optimization level (0-4)");
656         firm_option_help(put_help);
657         put_help("-fexpensive-optimizations","Ignored (gcc compatibility)");
658 }
659
660 static void print_help_codegeneration(void)
661 {
662         put_help("-g",                       "Generate debug information");
663         put_help("-pg",                      "Instrument code for gnu gprof");
664         put_help("-fomit-frame-pointer",     "Produce code without frame pointer where possible");
665         put_help("-ffreestanding",           "Compile in freestanding mode (see ISO C standard)");
666         put_help("-fhosted",                 "Compile in hosted (not freestanding) mode");
667         put_help("-fprofile-generate",       "Generate instrumented code to collect profile information");
668         put_help("-fprofile-use",            "Use profile information generated by instrumented binaries");
669         put_help("-ffp-precise",             "Precise floating point model");
670         put_help("-ffp-fast",                "Imprecise floating point model");
671         put_help("-ffp-strict",              "Strict floating point model");
672         put_help("-pthread",                 "Use pthread threading library");
673         put_help("-mtarget=TARGET",          "Specify target architecture as CPU-manufacturer-OS triple");
674         put_help("-mtriple=TARGET",          "Alias for -mtarget (clang compatibility)");
675         put_help("-march=ARCH",              "");
676         put_help("-mtune=ARCH",              "");
677         put_help("-mcpu=CPU",                "");
678         put_help("-mfpmath=",                "");
679         put_help("-mpreferred-stack-boundary=", "");
680         put_help("-mrtd",                    "");
681         put_help("-mregparm=",               "Not supported yet");
682         put_help("-msoft-float",             "Not supported yet");
683         put_help("-m32",                     "Generate 32bit code");
684         put_help("-m64",                     "Generate 64bit code");
685         put_help("-fverbose-asm",            "Ignored (gcc compatibility)");
686         put_help("-fjump-tables",            "Ignored (gcc compatibility)");
687         put_help("-fcommon",                 "Ignored (gcc compatibility)");
688         put_help("-foptimize-sibling-calls", "Ignored (gcc compatibility)");
689         put_help("-falign-loops",            "Ignored (gcc compatibility)");
690         put_help("-falign-jumps",            "Ignored (gcc compatibility)");
691         put_help("-falign-functions",        "Ignored (gcc compatibility)");
692         put_help("-fPIC",                    "Ignored (gcc compatibility)");
693         put_help("-ffast-math",              "Same as -ffp-fast (gcc compatibility)");
694         puts("");
695         puts("\tMost of these options can be used with a no- prefix to disable them");
696         puts("\te.g. -fno-omit-frame-pointer");
697 }
698
699 static void print_help_linker(void)
700 {
701         put_help("-l LIBRARY",               "");
702         put_help("-L PATH",                  "");
703         put_help("-s",                       "Do not produce symbol table and relocation information");
704         put_help("-shared",                  "Produce a shared library");
705         put_help("-static",                  "Produce statically linked binary");
706         put_help("-Wl,OPTION",               "Pass option directly to linker");
707 }
708
709 static void print_help_debug(void)
710 {
711         put_help("--lextest",                "Preprocess and tokenize only");
712         put_help("--print-ast",              "Preprocess, parse and print AST");
713         put_help("--print-implicit-cast",    "");
714         put_help("--print-parenthesis",      "");
715         put_help("--benchmark",              "Preprocess and parse, produces no output");
716         put_help("--time",                   "Measure time of compiler passes");
717         put_help("--dump-function func",     "Preprocess, parse and output vcg graph of func");
718         put_help("--export-ir",              "Preprocess, parse and output compiler intermediate representation");
719 }
720
721 static void print_help_language_tools(void)
722 {
723         put_help("--print-fluffy",           "Preprocess, parse and generate declarations for the fluffy language");
724         put_help("--print-jna",              "Preprocess, parse and generate declarations for JNA");
725         put_help("--jna-limit filename",     "");
726         put_help("--jna-libname name",       "");
727 }
728
729 static void print_help_firm(void)
730 {
731         put_help("-bOPTION",                 "Directly pass option to libFirm backend");
732         int res = be_parse_arg("help");
733         (void) res;
734         assert(res);
735 }
736
737 typedef enum {
738         HELP_NONE          = 0,
739         HELP_BASIC         = 1 << 0,
740         HELP_PREPROCESSOR  = 1 << 1,
741         HELP_PARSER        = 1 << 2,
742         HELP_WARNINGS      = 1 << 3,
743         HELP_OPTIMIZATION  = 1 << 4,
744         HELP_CODEGEN       = 1 << 5,
745         HELP_LINKER        = 1 << 6,
746         HELP_LANGUAGETOOLS = 1 << 7,
747         HELP_DEBUG         = 1 << 8,
748         HELP_FIRM          = 1 << 9,
749
750         HELP_ALL           = -1
751 } help_sections_t;
752
753 static void print_help(const char *argv0, help_sections_t sections)
754 {
755         if (sections & HELP_BASIC)         print_help_basic(argv0);
756         if (sections & HELP_PREPROCESSOR)  print_help_preprocessor();
757         if (sections & HELP_PARSER)        print_help_parser();
758         if (sections & HELP_WARNINGS)      print_help_warnings();
759         if (sections & HELP_OPTIMIZATION)  print_help_optimization();
760         if (sections & HELP_CODEGEN)       print_help_codegeneration();
761         if (sections & HELP_LINKER)        print_help_linker();
762         if (sections & HELP_LANGUAGETOOLS) print_help_language_tools();
763         if (sections & HELP_DEBUG)         print_help_debug();
764         if (sections & HELP_FIRM)          print_help_firm();
765 }
766
767 static void set_be_option(const char *arg)
768 {
769         int res = be_parse_arg(arg);
770         (void) res;
771         assert(res);
772 }
773
774 static void copy_file(FILE *dest, FILE *input)
775 {
776         char buf[16384];
777
778         while (!feof(input) && !ferror(dest)) {
779                 size_t read = fread(buf, 1, sizeof(buf), input);
780                 if (fwrite(buf, 1, read, dest) != read) {
781                         perror("could not write output");
782                 }
783         }
784 }
785
786 static FILE *open_file(const char *filename)
787 {
788         if (streq(filename, "-")) {
789                 return stdin;
790         }
791
792         FILE *in = fopen(filename, "r");
793         if (in == NULL) {
794                 fprintf(stderr, "Could not open '%s': %s\n", filename,
795                                 strerror(errno));
796                 exit(EXIT_FAILURE);
797         }
798
799         return in;
800 }
801
802 static filetype_t get_filetype_from_string(const char *string)
803 {
804         if (streq(string, "c") || streq(string, "c-header"))
805                 return FILETYPE_C;
806         if (streq(string, "c++") || streq(string, "c++-header"))
807                 return FILETYPE_CXX;
808         if (streq(string, "assembler"))
809                 return FILETYPE_PREPROCESSED_ASSEMBLER;
810         if (streq(string, "assembler-with-cpp"))
811                 return FILETYPE_ASSEMBLER;
812         if (streq(string, "none"))
813                 return FILETYPE_AUTODETECT;
814
815         return FILETYPE_UNKNOWN;
816 }
817
818 static bool is_windows_os(const char *os)
819 {
820         return strstr(os, "mingw") != NULL || streq(os, "win32");
821 }
822
823 static bool is_unixish_os(const char *os)
824 {
825         return strstr(os, "linux") != NULL || strstr(os, "bsd") != NULL
826                || streq(os, "solaris");
827 }
828
829 static bool is_darwin_os(const char *os)
830 {
831         return streq(os, "darwin");
832 }
833
834 static bool init_os_support(void)
835 {
836         const char *os = target_machine->operating_system;
837         wchar_atomic_kind         = ATOMIC_TYPE_INT;
838         enable_main_collect2_hack = false;
839         define_intmax_types       = false;
840
841         if (is_unixish_os(os)) {
842                 set_create_ld_ident(create_name_linux_elf);
843         } else if (is_darwin_os(os)) {
844                 set_create_ld_ident(create_name_macho);
845                 define_intmax_types = true;
846         } else if (is_windows_os(os)) {
847                 wchar_atomic_kind         = ATOMIC_TYPE_USHORT;
848                 enable_main_collect2_hack = true;
849                 set_create_ld_ident(create_name_win32);
850         } else {
851                 return false;
852         }
853
854         return true;
855 }
856
857 static bool parse_target_triple(const char *arg)
858 {
859         machine_triple_t *triple = firm_parse_machine_triple(arg);
860         if (triple == NULL) {
861                 fprintf(stderr, "Target-triple is not in the form 'cpu_type-manufacturer-operating_system'\n");
862                 return false;
863         }
864         target_machine = triple;
865         return true;
866 }
867
868 static unsigned decide_modulo_shift(unsigned type_size)
869 {
870         if (architecture_modulo_shift == 0)
871                 return 0;
872         if (type_size < architecture_modulo_shift)
873                 return architecture_modulo_shift;
874         return type_size;
875 }
876
877 static bool is_ia32_cpu(const char *architecture)
878 {
879         return streq(architecture, "i386")
880             || streq(architecture, "i486")
881             || streq(architecture, "i586")
882             || streq(architecture, "i686")
883             || streq(architecture, "i786");
884 }
885
886 static const char *setup_isa_from_tripel(const machine_triple_t *machine)
887 {
888         const char *cpu = machine->cpu_type;
889
890         if (is_ia32_cpu(cpu)) {
891                 return "ia32";
892         } else if (streq(cpu, "x86_64")) {
893                 return "amd64";
894         } else if (streq(cpu, "sparc")) {
895                 return "sparc";
896         } else if (streq(cpu, "arm")) {
897                 return "arm";
898         } else {
899                 fprintf(stderr, "Unknown cpu '%s' in target-triple\n", cpu);
900                 return NULL;
901         }
902 }
903
904 static const char *setup_target_machine(void)
905 {
906         if (!setup_firm_for_machine(target_machine))
907                 exit(1);
908
909         const char *isa = setup_isa_from_tripel(target_machine);
910
911         if (isa == NULL)
912                 exit(1);
913
914         init_os_support();
915
916         return isa;
917 }
918
919 /**
920  * initialize cparser type properties based on a firm type
921  */
922 static void set_typeprops_type(atomic_type_properties_t* props, ir_type *type)
923 {
924         props->size             = get_type_size_bytes(type);
925         props->alignment        = get_type_alignment_bytes(type);
926         props->struct_alignment = props->alignment;
927 }
928
929 /**
930  * Copy atomic type properties except the integer conversion rank
931  */
932 static void copy_typeprops(atomic_type_properties_t *dest,
933                            const atomic_type_properties_t *src)
934 {
935         dest->size             = src->size;
936         dest->alignment        = src->alignment;
937         dest->struct_alignment = src->struct_alignment;
938         dest->flags            = src->flags;
939 }
940
941 static void init_types_and_adjust(void)
942 {
943         const backend_params *be_params = be_get_backend_param();
944         unsigned machine_size = be_params->machine_size;
945         init_types(machine_size);
946
947         atomic_type_properties_t *props = atomic_type_properties;
948
949         /* adjust types as requested by target architecture */
950         ir_type *type_long_double = be_params->type_long_double;
951         if (type_long_double != NULL) {
952                 set_typeprops_type(&props[ATOMIC_TYPE_LONG_DOUBLE], type_long_double);
953                 atomic_modes[ATOMIC_TYPE_LONG_DOUBLE] = get_type_mode(type_long_double);
954         }
955
956         ir_type *type_long_long = be_params->type_long_long;
957         if (type_long_long != NULL)
958                 set_typeprops_type(&props[ATOMIC_TYPE_LONGLONG], type_long_long);
959
960         ir_type *type_unsigned_long_long = be_params->type_unsigned_long_long;
961         if (type_unsigned_long_long != NULL)
962                 set_typeprops_type(&props[ATOMIC_TYPE_ULONGLONG], type_unsigned_long_long);
963
964         /* operating system ABI specifics */
965         const char *os = target_machine->operating_system;
966         if (is_darwin_os(os)) {
967                 if (machine_size == 32) {
968                         props[ATOMIC_TYPE_LONGLONG].struct_alignment    =  4;
969                         props[ATOMIC_TYPE_ULONGLONG].struct_alignment   =  4;
970                         props[ATOMIC_TYPE_DOUBLE].struct_alignment      =  4;
971                         props[ATOMIC_TYPE_LONG_DOUBLE].size             = 16;
972                         props[ATOMIC_TYPE_LONG_DOUBLE].alignment        = 16;
973                         props[ATOMIC_TYPE_LONG_DOUBLE].struct_alignment = 16;
974                 }
975         } else if (is_windows_os(os)) {
976                 if (machine_size == 64) {
977                         /* to ease porting of old c-code microsoft decided to use 32bits
978                          * even for long */
979                         props[ATOMIC_TYPE_LONG]  = props[ATOMIC_TYPE_INT];
980                         props[ATOMIC_TYPE_ULONG] = props[ATOMIC_TYPE_UINT];
981                 }
982
983                 /* on windows long double is not supported */
984                 props[ATOMIC_TYPE_LONG_DOUBLE] = props[ATOMIC_TYPE_DOUBLE];
985         } else if (is_unixish_os(os)) {
986                 if (is_ia32_cpu(target_machine->cpu_type)) {
987                         /* System V has a broken alignment for double so we have to add
988                          * a hack here */
989                         props[ATOMIC_TYPE_DOUBLE].struct_alignment    = 4;
990                         props[ATOMIC_TYPE_LONGLONG].struct_alignment  = 4;
991                         props[ATOMIC_TYPE_ULONGLONG].struct_alignment = 4;
992                 }
993         }
994
995         /* stuff decided after processing operating system specifics and
996          * commandline flags */
997         if (char_is_signed) {
998                 props[ATOMIC_TYPE_CHAR].flags |= ATOMIC_TYPE_FLAG_SIGNED;
999         } else {
1000                 props[ATOMIC_TYPE_CHAR].flags &= ~ATOMIC_TYPE_FLAG_SIGNED;
1001         }
1002         /* copy over wchar_t properties (including rank) */
1003         props[ATOMIC_TYPE_WCHAR_T] = props[wchar_atomic_kind];
1004
1005         /* initialize defaults for unsupported types */
1006         if (type_long_long == NULL) {
1007                 copy_typeprops(&props[ATOMIC_TYPE_LONGLONG], &props[ATOMIC_TYPE_LONG]);
1008         }
1009         if (type_unsigned_long_long == NULL) {
1010                 copy_typeprops(&props[ATOMIC_TYPE_ULONGLONG],
1011                                &props[ATOMIC_TYPE_ULONG]);
1012         }
1013         if (type_long_double == NULL) {
1014                 copy_typeprops(&props[ATOMIC_TYPE_LONG_DOUBLE],
1015                                &props[ATOMIC_TYPE_DOUBLE]);
1016         }
1017
1018         /* initialize firm pointer modes */
1019         char               name[64];
1020         unsigned           bit_size     = machine_size;
1021         unsigned           modulo_shift = decide_modulo_shift(bit_size);
1022
1023         snprintf(name, sizeof(name), "p%u", machine_size);
1024         ir_mode *ptr_mode = new_reference_mode(name, irma_twos_complement, bit_size, modulo_shift);
1025
1026         if (machine_size == 16) {
1027                 set_reference_mode_signed_eq(ptr_mode, mode_Hs);
1028                 set_reference_mode_unsigned_eq(ptr_mode, mode_Hu);
1029         } else if (machine_size == 32) {
1030                 set_reference_mode_signed_eq(ptr_mode, mode_Is);
1031                 set_reference_mode_unsigned_eq(ptr_mode, mode_Iu);
1032         } else if (machine_size == 64) {
1033                 set_reference_mode_signed_eq(ptr_mode, mode_Ls);
1034                 set_reference_mode_unsigned_eq(ptr_mode, mode_Lu);
1035         } else {
1036                 panic("strange machine_size when determining pointer modes");
1037         }
1038
1039         /* Hmm, pointers should be machine size */
1040         set_modeP_data(ptr_mode);
1041         set_modeP_code(ptr_mode);
1042
1043         byte_order_big_endian = be_params->byte_order_big_endian;
1044         if (be_params->modulo_shift_efficient) {
1045                 architecture_modulo_shift = machine_size;
1046         } else {
1047                 architecture_modulo_shift = 0;
1048         }
1049 }
1050
1051 int main(int argc, char **argv)
1052 {
1053         const char        *dumpfunction         = NULL;
1054         const char        *print_file_name_file = NULL;
1055         compile_mode_t     mode                 = CompileAssembleLink;
1056         int                opt_level            = 1;
1057         int                result               = EXIT_SUCCESS;
1058         char               cpu_arch[16]         = "ia32";
1059         file_list_entry_t *files                = NULL;
1060         file_list_entry_t *last_file            = NULL;
1061         bool               construct_dep_target = false;
1062         bool               do_timing            = false;
1063         bool               profile_generate     = false;
1064         bool               profile_use          = false;
1065         struct obstack     file_obst;
1066
1067         atexit(free_temp_files);
1068
1069         /* hack for now... */
1070         if (strstr(argv[0], "pptest") != NULL) {
1071                 extern int pptest_main(int argc, char **argv);
1072                 return pptest_main(argc, argv);
1073         }
1074
1075         obstack_init(&cppflags_obst);
1076         obstack_init(&ldflags_obst);
1077         obstack_init(&asflags_obst);
1078         obstack_init(&file_obst);
1079
1080 #define GET_ARG_AFTER(def, args)                                             \
1081         do {                                                                     \
1082         def = &arg[sizeof(args)-1];                                              \
1083         if (def[0] == '\0') {                                                    \
1084                 ++i;                                                                 \
1085                 if (i >= argc) {                                                     \
1086                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
1087                         argument_errors = true;                                          \
1088                         break;                                                           \
1089                 }                                                                    \
1090                 def = argv[i];                                                       \
1091                 if (def[0] == '-' && def[1] != '\0') {                               \
1092                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
1093                         argument_errors = true;                                          \
1094                         continue;                                                        \
1095                 }                                                                    \
1096         }                                                                        \
1097         } while (0)
1098
1099 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
1100
1101         /* initialize this early because it has to parse options */
1102         gen_firm_init();
1103
1104         /* early options parsing (find out optimization level and OS) */
1105         for (int i = 1; i < argc; ++i) {
1106                 const char *arg = argv[i];
1107                 if (arg[0] != '-')
1108                         continue;
1109
1110                 const char *option = &arg[1];
1111                 if (option[0] == 'O') {
1112                         sscanf(&option[1], "%d", &opt_level);
1113                 }
1114         }
1115
1116         if (target_machine == NULL) {
1117                 target_machine = firm_get_host_machine();
1118         }
1119         choose_optimization_pack(opt_level);
1120         setup_target_machine();
1121
1122         /* parse rest of options */
1123                         standard        = STANDARD_DEFAULT;
1124         unsigned        features_on     = 0;
1125         unsigned        features_off    = 0;
1126         filetype_t      forced_filetype = FILETYPE_AUTODETECT;
1127         help_sections_t help            = HELP_NONE;
1128         bool            argument_errors = false;
1129         for (int i = 1; i < argc; ++i) {
1130                 const char *arg = argv[i];
1131                 if (arg[0] == '-' && arg[1] != '\0') {
1132                         /* an option */
1133                         const char *option = &arg[1];
1134                         if (option[0] == 'o') {
1135                                 GET_ARG_AFTER(outname, "-o");
1136                         } else if (option[0] == 'g') {
1137                                 set_be_option("debuginfo=stabs");
1138                                 set_be_option("omitfp=no");
1139                                 set_be_option("ia32-nooptcc=yes");
1140                         } else if (SINGLE_OPTION('c')) {
1141                                 mode = CompileAssemble;
1142                         } else if (SINGLE_OPTION('E')) {
1143                                 mode = PreprocessOnly;
1144                         } else if (SINGLE_OPTION('s')) {
1145                                 add_flag(&ldflags_obst, "-s");
1146                         } else if (SINGLE_OPTION('S')) {
1147                                 mode = Compile;
1148                         } else if (option[0] == 'O') {
1149                                 continue;
1150                         } else if (option[0] == 'I') {
1151                                 const char *opt;
1152                                 GET_ARG_AFTER(opt, "-I");
1153                                 add_flag(&cppflags_obst, "-I%s", opt);
1154                         } else if (option[0] == 'D') {
1155                                 const char *opt;
1156                                 GET_ARG_AFTER(opt, "-D");
1157                                 add_flag(&cppflags_obst, "-D%s", opt);
1158                         } else if (option[0] == 'U') {
1159                                 const char *opt;
1160                                 GET_ARG_AFTER(opt, "-U");
1161                                 add_flag(&cppflags_obst, "-U%s", opt);
1162                         } else if (option[0] == 'l') {
1163                                 const char *opt;
1164                                 GET_ARG_AFTER(opt, "-l");
1165                                 add_flag(&ldflags_obst, "-l%s", opt);
1166                         } else if (option[0] == 'L') {
1167                                 const char *opt;
1168                                 GET_ARG_AFTER(opt, "-L");
1169                                 add_flag(&ldflags_obst, "-L%s", opt);
1170                         } else if (SINGLE_OPTION('v')) {
1171                                 verbose = 1;
1172                         } else if (SINGLE_OPTION('w')) {
1173                                 add_flag(&cppflags_obst, "-w");
1174                                 disable_all_warnings();
1175                         } else if (option[0] == 'x') {
1176                                 const char *opt;
1177                                 GET_ARG_AFTER(opt, "-x");
1178                                 forced_filetype = get_filetype_from_string(opt);
1179                                 if (forced_filetype == FILETYPE_UNKNOWN) {
1180                                         fprintf(stderr, "Unknown language '%s'\n", opt);
1181                                         argument_errors = true;
1182                                 }
1183                         } else if (streq(option, "M")) {
1184                                 mode = PreprocessOnly;
1185                                 add_flag(&cppflags_obst, "-M");
1186                         } else if (streq(option, "MMD") ||
1187                                    streq(option, "MD")) {
1188                             construct_dep_target = true;
1189                                 add_flag(&cppflags_obst, "-%s", option);
1190                         } else if (streq(option, "MM")  ||
1191                                    streq(option, "MP")) {
1192                                 add_flag(&cppflags_obst, "-%s", option);
1193                         } else if (streq(option, "MT") ||
1194                                    streq(option, "MQ") ||
1195                                    streq(option, "MF")) {
1196                                 const char *opt;
1197                                 GET_ARG_AFTER(opt, "-MT");
1198                                 add_flag(&cppflags_obst, "-%s", option);
1199                                 add_flag(&cppflags_obst, "%s", opt);
1200                         } else if (streq(option, "include")) {
1201                                 const char *opt;
1202                                 GET_ARG_AFTER(opt, "-include");
1203                                 add_flag(&cppflags_obst, "-include");
1204                                 add_flag(&cppflags_obst, "%s", opt);
1205                         } else if (streq(option, "isystem")) {
1206                                 const char *opt;
1207                                 GET_ARG_AFTER(opt, "-isystem");
1208                                 add_flag(&cppflags_obst, "-isystem");
1209                                 add_flag(&cppflags_obst, "%s", opt);
1210 #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__CYGWIN__)
1211                         } else if (streq(option, "pthread")) {
1212                                 /* set flags for the preprocessor */
1213                                 add_flag(&cppflags_obst, "-D_REENTRANT");
1214                                 /* set flags for the linker */
1215                                 add_flag(&ldflags_obst, "-lpthread");
1216 #endif
1217                         } else if (streq(option, "nostdinc")
1218                                         || streq(option, "trigraphs")) {
1219                                 /* pass these through to the preprocessor */
1220                                 add_flag(&cppflags_obst, "%s", arg);
1221                         } else if (streq(option, "pipe")) {
1222                                 /* here for gcc compatibility */
1223                         } else if (streq(option, "static")) {
1224                                 add_flag(&ldflags_obst, "-static");
1225                         } else if (streq(option, "shared")) {
1226                                 add_flag(&ldflags_obst, "-shared");
1227                         } else if (option[0] == 'f') {
1228                                 char const *orig_opt;
1229                                 GET_ARG_AFTER(orig_opt, "-f");
1230
1231                                 if (strstart(orig_opt, "input-charset=")) {
1232                                         char const* const encoding = strchr(orig_opt, '=') + 1;
1233                                         input_encoding = encoding;
1234                                 } else if (strstart(orig_opt, "align-loops=") ||
1235                                            strstart(orig_opt, "align-jumps=") ||
1236                                            strstart(orig_opt, "align-functions=")) {
1237                                         fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
1238                                 } else if (strstart(orig_opt, "visibility=")) {
1239                                         const char *val = strchr(orig_opt, '=')+1;
1240                                         elf_visibility_tag_t visibility
1241                                                 = get_elf_visibility_from_string(val);
1242                                         if (visibility == ELF_VISIBILITY_ERROR) {
1243                                                 fprintf(stderr, "invalid visibility '%s' specified\n",
1244                                                         val);
1245                                                 argument_errors = true;
1246                                         } else {
1247                                                 set_default_visibility(visibility);
1248                                         }
1249                                 } else if (strstart(orig_opt, "message-length=")) {
1250                                         /* ignore: would only affect error message format */
1251                                 } else if (streq(orig_opt, "fast-math") ||
1252                                            streq(orig_opt, "fp-fast")) {
1253                                         firm_fp_model = fp_model_fast;
1254                                 } else if (streq(orig_opt, "fp-precise")) {
1255                                         firm_fp_model = fp_model_precise;
1256                                 } else if (streq(orig_opt, "fp-strict")) {
1257                                         firm_fp_model = fp_model_strict;
1258                                 } else if (streq(orig_opt, "help")) {
1259                                         fprintf(stderr, "warning: -fhelp is deprecated\n");
1260                                         help |= HELP_OPTIMIZATION;
1261                                 } else {
1262                                         /* -f options which have an -fno- variant */
1263                                         char const *opt         = orig_opt;
1264                                         bool        truth_value = true;
1265                                         if (opt[0] == 'n' && opt[1] == 'o' && opt[2] == '-') {
1266                                                 truth_value = false;
1267                                                 opt += 3;
1268                                         }
1269
1270                                         if (streq(opt, "diagnostics-show-option")) {
1271                                                 diagnostics_show_option = truth_value;
1272                                         } else if (streq(opt, "dollars-in-identifiers")) {
1273                                                 allow_dollar_in_symbol = truth_value;
1274                                         } else if (streq(opt, "omit-frame-pointer")) {
1275                                                 set_be_option(truth_value ? "omitfp" : "omitfp=no");
1276                                         } else if (streq(opt, "short-wchar")) {
1277                                                 wchar_atomic_kind = truth_value ? ATOMIC_TYPE_USHORT
1278                                                         : ATOMIC_TYPE_INT;
1279                                         } else if (streq(opt, "show-column")) {
1280                                                 show_column = truth_value;
1281                                         } else if (streq(opt, "signed-char")) {
1282                                                 char_is_signed = truth_value;
1283                                         } else if (streq(opt, "strength-reduce")) {
1284                                                 /* does nothing, for gcc compatibility (even gcc does
1285                                                  * nothing for this switch anymore) */
1286                                         } else if (streq(opt, "syntax-only")) {
1287                                                 mode = truth_value ? ParseOnly : CompileAssembleLink;
1288                                         } else if (streq(opt, "unsigned-char")) {
1289                                                 char_is_signed = !truth_value;
1290                                         } else if (streq(opt, "freestanding")) {
1291                                                 freestanding = truth_value;
1292                                         } else if (streq(opt, "hosted")) {
1293                                                 freestanding = !truth_value;
1294                                         } else if (streq(opt, "profile-generate")) {
1295                                                 profile_generate = truth_value;
1296                                         } else if (streq(opt, "profile-use")) {
1297                                                 profile_use = truth_value;
1298                                         } else if (!truth_value &&
1299                                                    streq(opt, "asynchronous-unwind-tables")) {
1300                                             /* nothing todo, a gcc feature which we do not support
1301                                              * anyway was deactivated */
1302                                         } else if (streq(opt, "verbose-asm")) {
1303                                                 /* ignore: we always print verbose assembler */
1304                                         } else if (streq(opt, "jump-tables")             ||
1305                                                    streq(opt, "expensive-optimizations") ||
1306                                                    streq(opt, "common")                  ||
1307                                                    streq(opt, "optimize-sibling-calls")  ||
1308                                                    streq(opt, "align-loops")             ||
1309                                                    streq(opt, "align-jumps")             ||
1310                                                    streq(opt, "align-functions")         ||
1311                                                    streq(opt, "unroll-loops")            ||
1312                                                    streq(opt, "PIC")                     ||
1313                                                    streq(opt, "stack-protector")         ||
1314                                                    streq(opt, "stack-protector-all")) {
1315                                                 fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
1316                                         } else {
1317                                                 int res = firm_option(orig_opt);
1318                                                 if (res == 0) {
1319                                                         fprintf(stderr, "error: unknown Firm option '-f%s'\n",
1320                                                                 orig_opt);
1321                                                         argument_errors = true;
1322                                                         continue;
1323                                                 }
1324                                         }
1325                                 }
1326                         } else if (option[0] == 'b') {
1327                                 const char *opt;
1328                                 GET_ARG_AFTER(opt, "-b");
1329
1330                                 if (streq(opt, "help")) {
1331                                         fprintf(stderr, "warning: -bhelp is deprecated (use --help-firm)\n");
1332                                         help |= HELP_FIRM;
1333                                 } else {
1334                                         int res = be_parse_arg(opt);
1335                                         if (res == 0) {
1336                                                 fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
1337                                                                 opt);
1338                                                 argument_errors = true;
1339                                         } else if (strstart(opt, "isa=")) {
1340                                                 strncpy(cpu_arch, opt, sizeof(cpu_arch));
1341                                         }
1342                                 }
1343                         } else if (option[0] == 'W') {
1344                                 if (strstart(option + 1, "p,")) {
1345                                         // pass options directly to the preprocessor
1346                                         const char *opt;
1347                                         GET_ARG_AFTER(opt, "-Wp,");
1348                                         add_flag(&cppflags_obst, "-Wp,%s", opt);
1349                                 } else if (strstart(option + 1, "l,")) {
1350                                         // pass options directly to the linker
1351                                         const char *opt;
1352                                         GET_ARG_AFTER(opt, "-Wl,");
1353                                         add_flag(&ldflags_obst, "-Wl,%s", opt);
1354                                 } else if (streq(option + 1, "no-trigraphs")
1355                                                         || streq(option + 1, "undef")
1356                                                         || streq(option + 1, "missing-include-dirs")
1357                                                         || streq(option + 1, "endif-labels")) {
1358                                         add_flag(&cppflags_obst, "%s", arg);
1359                                 } else if (streq(option+1, "init-self")) {
1360                                         /* ignored (same as gcc does) */
1361                                 } else if (streq(option+1, "format-y2k")
1362                                            || streq(option+1, "format-security")
1363                                            || streq(option+1, "old-style-declaration")
1364                                            || streq(option+1, "type-limits")) {
1365                                     /* ignore (gcc compatibility) */
1366                                 } else {
1367                                         set_warning_opt(&option[1]);
1368                                 }
1369                         } else if (option[0] == 'm') {
1370                                 /* -m options */
1371                                 const char *opt;
1372                                 char arch_opt[64];
1373
1374                                 GET_ARG_AFTER(opt, "-m");
1375                                 if (strstart(opt, "target=")) {
1376                                         GET_ARG_AFTER(opt, "-mtarget=");
1377                                         if (!parse_target_triple(opt)) {
1378                                                 argument_errors = true;
1379                                         } else {
1380                                                 const char *isa = setup_target_machine();
1381                                                 strncpy(cpu_arch, isa, sizeof(cpu_arch));
1382                                                 target_triple = opt;
1383                                         }
1384                                 } else if (strstart(opt, "triple=")) {
1385                                         GET_ARG_AFTER(opt, "-mtriple=");
1386                                         if (!parse_target_triple(opt)) {
1387                                                 argument_errors = true;
1388                                         } else {
1389                                                 const char *isa = setup_target_machine();
1390                                                 strncpy(cpu_arch, isa, sizeof(cpu_arch));
1391                                                 target_triple = opt;
1392                                         }
1393                                 } else if (strstart(opt, "arch=")) {
1394                                         GET_ARG_AFTER(opt, "-march=");
1395                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
1396                                         int res = be_parse_arg(arch_opt);
1397                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
1398                                         res &= be_parse_arg(arch_opt);
1399
1400                                         if (res == 0) {
1401                                                 fprintf(stderr, "Unknown architecture '%s'\n", arch_opt);
1402                                                 argument_errors = true;
1403                                         }
1404                                 } else if (strstart(opt, "tune=")) {
1405                                         GET_ARG_AFTER(opt, "-mtune=");
1406                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
1407                                         int res = be_parse_arg(arch_opt);
1408                                         if (res == 0)
1409                                                 argument_errors = true;
1410                                 } else if (strstart(opt, "cpu=")) {
1411                                         GET_ARG_AFTER(opt, "-mcpu=");
1412                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
1413                                         int res = be_parse_arg(arch_opt);
1414                                         if (res == 0)
1415                                                 argument_errors = true;
1416                                 } else if (strstart(opt, "fpmath=")) {
1417                                         GET_ARG_AFTER(opt, "-mfpmath=");
1418                                         if (streq(opt, "387"))
1419                                                 opt = "x87";
1420                                         else if (streq(opt, "sse"))
1421                                                 opt = "sse2";
1422                                         else {
1423                                                 fprintf(stderr, "error: option -mfpmath supports only 387 or sse\n");
1424                                                 argument_errors = true;
1425                                         }
1426                                         if (!argument_errors) {
1427                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
1428                                                 int res = be_parse_arg(arch_opt);
1429                                                 if (res == 0)
1430                                                         argument_errors = true;
1431                                         }
1432                                 } else if (strstart(opt, "preferred-stack-boundary=")) {
1433                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
1434                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
1435                                         int res = be_parse_arg(arch_opt);
1436                                         if (res == 0)
1437                                                 argument_errors = true;
1438                                 } else if (streq(opt, "rtd")) {
1439                                         default_calling_convention = CC_STDCALL;
1440                                 } else if (strstart(opt, "regparm=")) {
1441                                         fprintf(stderr, "error: regparm convention not supported yet\n");
1442                                         argument_errors = true;
1443                                 } else if (streq(opt, "soft-float")) {
1444                                         add_flag(&ldflags_obst, "-msoft-float");
1445                                         snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=softfloat", cpu_arch);
1446                                         int res = be_parse_arg(arch_opt);
1447                                         if (res == 0)
1448                                                 argument_errors = true;
1449                                 } else {
1450                                         long int value = strtol(opt, NULL, 10);
1451                                         if (value == 0) {
1452                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
1453                                                 argument_errors = true;
1454                                         } else if (value != 16 && value != 32 && value != 64) {
1455                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
1456                                                 argument_errors = true;
1457                                         } else {
1458                                                 unsigned machine_size = (unsigned)value;
1459                                                 /* TODO: choose/change backend based on this */
1460                                                 add_flag(&cppflags_obst, "-m%u", machine_size);
1461                                                 add_flag(&asflags_obst, "-m%u", machine_size);
1462                                                 add_flag(&ldflags_obst, "-m%u", machine_size);
1463                                         }
1464                                 }
1465                         } else if (streq(option, "pg")) {
1466                                 set_be_option("gprof");
1467                                 add_flag(&ldflags_obst, "-pg");
1468                         } else if (streq(option, "ansi")) {
1469                                 add_flag(&cppflags_obst, "-ansi");
1470                         } else if (streq(option, "pedantic")) {
1471                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
1472                         } else if (strstart(option, "std=")) {
1473                                 const char *const o = &option[4];
1474                                 standard =
1475                                         streq(o, "c++")            ? STANDARD_CXX98   :
1476                                         streq(o, "c++98")          ? STANDARD_CXX98   :
1477                                         streq(o, "c89")            ? STANDARD_C89     :
1478                                         streq(o, "c99")            ? STANDARD_C99     :
1479                                         streq(o, "c9x")            ? STANDARD_C99     : // deprecated
1480                                         streq(o, "gnu++98")        ? STANDARD_GNUXX98 :
1481                                         streq(o, "gnu89")          ? STANDARD_GNU89   :
1482                                         streq(o, "gnu99")          ? STANDARD_GNU99   :
1483                                         streq(o, "gnu9x")          ? STANDARD_GNU99   : // deprecated
1484                                         streq(o, "iso9899:1990")   ? STANDARD_C89     :
1485                                         streq(o, "iso9899:199409") ? STANDARD_C90     :
1486                                         streq(o, "iso9899:1999")   ? STANDARD_C99     :
1487                                         streq(o, "iso9899:199x")   ? STANDARD_C99     : // deprecated
1488                                         (fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg), standard);
1489                         } else if (streq(option, "version")) {
1490                                 print_cparser_version();
1491                                 return EXIT_SUCCESS;
1492                         } else if (streq(option, "dumpversion")) {
1493                                 /* gcc compatibility option */
1494                                 print_cparser_version_short();
1495                                 return EXIT_SUCCESS;
1496                         } else if (strstart(option, "print-file-name=")) {
1497                                 GET_ARG_AFTER(print_file_name_file, "-print-file-name=");
1498                         } else if (option[0] == '-') {
1499                                 /* double dash option */
1500                                 ++option;
1501                                 if (streq(option, "gcc")) {
1502                                         features_on  |=  _GNUC;
1503                                         features_off &= ~_GNUC;
1504                                 } else if (streq(option, "no-gcc")) {
1505                                         features_on  &= ~_GNUC;
1506                                         features_off |=  _GNUC;
1507                                 } else if (streq(option, "ms")) {
1508                                         features_on  |=  _MS;
1509                                         features_off &= ~_MS;
1510                                 } else if (streq(option, "no-ms")) {
1511                                         features_on  &= ~_MS;
1512                                         features_off |=  _MS;
1513                                 } else if (streq(option, "strict")) {
1514                                         strict_mode = true;
1515                                 } else if (streq(option, "lextest")) {
1516                                         mode = LexTest;
1517                                 } else if (streq(option, "benchmark")) {
1518                                         mode = BenchmarkParser;
1519                                 } else if (streq(option, "print-ast")) {
1520                                         mode = PrintAst;
1521                                 } else if (streq(option, "print-implicit-cast")) {
1522                                         print_implicit_casts = true;
1523                                 } else if (streq(option, "print-parenthesis")) {
1524                                         print_parenthesis = true;
1525                                 } else if (streq(option, "print-fluffy")) {
1526                                         mode = PrintFluffy;
1527                                 } else if (streq(option, "print-jna")) {
1528                                         mode = PrintJna;
1529                                 } else if (streq(option, "jna-limit")) {
1530                                         ++i;
1531                                         if (i >= argc) {
1532                                                 fprintf(stderr, "error: "
1533                                                         "expected argument after '--jna-limit'\n");
1534                                                 argument_errors = true;
1535                                                 break;
1536                                         }
1537                                         jna_limit_output(argv[i]);
1538                                 } else if (streq(option, "jna-libname")) {
1539                                         ++i;
1540                                         if (i >= argc) {
1541                                                 fprintf(stderr, "error: "
1542                                                         "expected argument after '--jna-libname'\n");
1543                                                 argument_errors = true;
1544                                                 break;
1545                                         }
1546                                         jna_set_libname(argv[i]);
1547                                 } else if (streq(option, "time")) {
1548                                         do_timing = true;
1549                                 } else if (streq(option, "version")) {
1550                                         print_cparser_version();
1551                                         return EXIT_SUCCESS;
1552                                 } else if (streq(option, "help")) {
1553                                         help |= HELP_BASIC;
1554                                 } else if (streq(option, "help-parser")) {
1555                                         help |= HELP_PARSER;
1556                                 } else if (streq(option, "help-warnings")) {
1557                                         help |= HELP_WARNINGS;
1558                                 } else if (streq(option, "help-codegen")) {
1559                                         help |= HELP_CODEGEN;
1560                                 } else if (streq(option, "help-linker")) {
1561                                         help |= HELP_LINKER;
1562                                 } else if (streq(option, "help-optimization")) {
1563                                         help |= HELP_OPTIMIZATION;
1564                                 } else if (streq(option, "help-language-tools")) {
1565                                         help |= HELP_LANGUAGETOOLS;
1566                                 } else if (streq(option, "help-debug")) {
1567                                         help |= HELP_DEBUG;
1568                                 } else if (streq(option, "help-firm")) {
1569                                         help |= HELP_FIRM;
1570                                 } else if (streq(option, "help-all")) {
1571                                         help |= HELP_ALL;
1572                                 } else if (streq(option, "dump-function")) {
1573                                         ++i;
1574                                         if (i >= argc) {
1575                                                 fprintf(stderr, "error: "
1576                                                         "expected argument after '--dump-function'\n");
1577                                                 argument_errors = true;
1578                                                 break;
1579                                         }
1580                                         dumpfunction = argv[i];
1581                                         mode         = CompileDump;
1582                                 } else if (streq(option, "export-ir")) {
1583                                         mode = CompileExportIR;
1584                                 } else if (streq(option, "unroll-loops")) {
1585                                         /* ignore (gcc compatibility) */
1586                                 } else {
1587                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
1588                                         argument_errors = true;
1589                                 }
1590                         } else {
1591                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
1592                                 argument_errors = true;
1593                         }
1594                 } else {
1595                         filetype_t type = forced_filetype;
1596                         if (type == FILETYPE_AUTODETECT) {
1597                                 if (streq(arg, "-")) {
1598                                         /* - implicitly means C source file */
1599                                         type = FILETYPE_C;
1600                                 } else {
1601                                         const char *suffix = strrchr(arg, '.');
1602                                         /* Ensure there is at least one char before the suffix */
1603                                         if (suffix != NULL && suffix != arg) {
1604                                                 ++suffix;
1605                                                 type =
1606                                                         streq(suffix, "S")   ? FILETYPE_ASSEMBLER              :
1607                                                         streq(suffix, "a")   ? FILETYPE_OBJECT                 :
1608                                                         streq(suffix, "c")   ? FILETYPE_C                      :
1609                                                         streq(suffix, "i")   ? FILETYPE_PREPROCESSED_C         :
1610                                                         streq(suffix, "C")   ? FILETYPE_CXX                    :
1611                                                         streq(suffix, "cc")  ? FILETYPE_CXX                    :
1612                                                         streq(suffix, "cp")  ? FILETYPE_CXX                    :
1613                                                         streq(suffix, "cpp") ? FILETYPE_CXX                    :
1614                                                         streq(suffix, "CPP") ? FILETYPE_CXX                    :
1615                                                         streq(suffix, "cxx") ? FILETYPE_CXX                    :
1616                                                         streq(suffix, "c++") ? FILETYPE_CXX                    :
1617                                                         streq(suffix, "ii")  ? FILETYPE_PREPROCESSED_CXX       :
1618                                                         streq(suffix, "h")   ? FILETYPE_C                      :
1619                                                         streq(suffix, "ir")  ? FILETYPE_IR                     :
1620                                                         streq(suffix, "o")   ? FILETYPE_OBJECT                 :
1621                                                         streq(suffix, "s")   ? FILETYPE_PREPROCESSED_ASSEMBLER :
1622                                                         streq(suffix, "so")  ? FILETYPE_OBJECT                 :
1623                                                         FILETYPE_OBJECT; /* gcc behavior: unknown file extension means object file */
1624                                         }
1625                                 }
1626                         }
1627
1628                         file_list_entry_t *entry
1629                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
1630                         memset(entry, 0, sizeof(entry[0]));
1631                         entry->name = arg;
1632                         entry->type = type;
1633
1634                         if (last_file != NULL) {
1635                                 last_file->next = entry;
1636                         } else {
1637                                 files = entry;
1638                         }
1639                         last_file = entry;
1640                 }
1641         }
1642
1643         if (help != HELP_NONE) {
1644                 print_help(argv[0], help);
1645                 return !argument_errors;
1646         }
1647
1648         if (print_file_name_file != NULL) {
1649                 print_file_name(print_file_name_file);
1650                 return EXIT_SUCCESS;
1651         }
1652         if (files == NULL) {
1653                 fprintf(stderr, "error: no input files specified\n");
1654                 argument_errors = true;
1655         }
1656
1657         if (argument_errors) {
1658                 usage(argv[0]);
1659                 return EXIT_FAILURE;
1660         }
1661
1662         /* apply some effects from switches */
1663         c_mode |= features_on;
1664         c_mode &= ~features_off;
1665         if (profile_generate) {
1666                 add_flag(&ldflags_obst, "-lfirmprof");
1667                 set_be_option("profilegenerate");
1668         }
1669         if (profile_use) {
1670                 set_be_option("profileuse");
1671         }
1672
1673         init_symbol_table();
1674         init_types_and_adjust();
1675         init_typehash();
1676         init_basic_types();
1677         if (wchar_atomic_kind == ATOMIC_TYPE_INT)
1678                 init_wchar_types(type_int);
1679         else if (wchar_atomic_kind == ATOMIC_TYPE_USHORT)
1680                 init_wchar_types(type_short);
1681         else
1682                 panic("unexpected wchar type");
1683         init_lexer();
1684         init_ast();
1685         init_parser();
1686         init_ast2firm();
1687         init_mangle();
1688
1689         if (do_timing)
1690                 timer_init();
1691
1692         if (construct_dep_target) {
1693                 if (outname != 0 && strlen(outname) >= 2) {
1694                         get_output_name(dep_target, sizeof(dep_target), outname, ".d");
1695                 } else {
1696                         get_output_name(dep_target, sizeof(dep_target), files->name, ".d");
1697                 }
1698         } else {
1699                 dep_target[0] = '\0';
1700         }
1701
1702         char outnamebuf[4096];
1703         if (outname == NULL) {
1704                 const char *filename = files->name;
1705
1706                 switch(mode) {
1707                 case BenchmarkParser:
1708                 case PrintAst:
1709                 case PrintFluffy:
1710                 case PrintJna:
1711                 case LexTest:
1712                 case PreprocessOnly:
1713                 case ParseOnly:
1714                         outname = "-";
1715                         break;
1716                 case Compile:
1717                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".s");
1718                         outname = outnamebuf;
1719                         break;
1720                 case CompileAssemble:
1721                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".o");
1722                         outname = outnamebuf;
1723                         break;
1724                 case CompileDump:
1725                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
1726                                         ".vcg");
1727                         outname = outnamebuf;
1728                         break;
1729                 case CompileExportIR:
1730                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".ir");
1731                         outname = outnamebuf;
1732                         break;
1733                 case CompileAssembleLink:
1734 #ifdef _WIN32
1735                         outname = "a.exe";
1736 #else
1737                         outname = "a.out";
1738 #endif
1739                         break;
1740                 }
1741         }
1742
1743         assert(outname != NULL);
1744
1745         FILE *out;
1746         if (streq(outname, "-")) {
1747                 out = stdout;
1748         } else {
1749                 out = fopen(outname, "w");
1750                 if (out == NULL) {
1751                         fprintf(stderr, "Could not open '%s' for writing: %s\n", outname,
1752                                         strerror(errno));
1753                         return EXIT_FAILURE;
1754                 }
1755         }
1756
1757         file_list_entry_t *file;
1758         bool               already_constructed_firm = false;
1759         for (file = files; file != NULL; file = file->next) {
1760                 char        asm_tempfile[1024];
1761                 const char *filename = file->name;
1762                 filetype_t  filetype = file->type;
1763
1764                 if (filetype == FILETYPE_OBJECT)
1765                         continue;
1766
1767                 FILE *in = NULL;
1768                 if (mode == LexTest) {
1769                         if (in == NULL)
1770                                 in = open_file(filename);
1771                         lextest(in, filename);
1772                         fclose(in);
1773                         return EXIT_SUCCESS;
1774                 }
1775
1776                 FILE *preprocessed_in = NULL;
1777                 filetype_t next_filetype = filetype;
1778                 switch (filetype) {
1779                         case FILETYPE_C:
1780                                 next_filetype = FILETYPE_PREPROCESSED_C;
1781                                 goto preprocess;
1782                         case FILETYPE_CXX:
1783                                 next_filetype = FILETYPE_PREPROCESSED_CXX;
1784                                 goto preprocess;
1785                         case FILETYPE_ASSEMBLER:
1786                                 next_filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1787                                 goto preprocess;
1788 preprocess:
1789                                 /* no support for input on FILE* yet */
1790                                 if (in != NULL)
1791                                         panic("internal compiler error: in for preprocessor != NULL");
1792
1793                                 preprocessed_in = preprocess(filename, filetype);
1794                                 if (mode == PreprocessOnly) {
1795                                         copy_file(out, preprocessed_in);
1796                                         int pp_result = pclose(preprocessed_in);
1797                                         fclose(out);
1798                                         /* remove output file in case of error */
1799                                         if (out != stdout && pp_result != EXIT_SUCCESS) {
1800                                                 unlink(outname);
1801                                         }
1802                                         return pp_result;
1803                                 }
1804
1805                                 in = preprocessed_in;
1806                                 filetype = next_filetype;
1807                                 break;
1808
1809                         default:
1810                                 break;
1811                 }
1812
1813                 FILE *asm_out;
1814                 if (mode == Compile) {
1815                         asm_out = out;
1816                 } else {
1817                         asm_out = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "ccs");
1818                 }
1819
1820                 if (in == NULL)
1821                         in = open_file(filename);
1822
1823                 /* preprocess and compile */
1824                 if (filetype == FILETYPE_PREPROCESSED_C) {
1825                         char const* invalid_mode;
1826                         switch (standard) {
1827                                 case STANDARD_ANSI:
1828                                 case STANDARD_C89:   c_mode = _C89;                break;
1829                                 /* TODO determine difference between these two */
1830                                 case STANDARD_C90:   c_mode = _C89;                break;
1831                                 case STANDARD_C99:   c_mode = _C89 | _C99;         break;
1832                                 case STANDARD_GNU89: c_mode = _C89 |        _GNUC; break;
1833
1834 default_c_warn:
1835                                         fprintf(stderr,
1836                                                         "warning: command line option \"-std=%s\" is not valid for C\n",
1837                                                         invalid_mode);
1838                                         /* FALLTHROUGH */
1839                                 case STANDARD_DEFAULT:
1840                                 case STANDARD_GNU99:   c_mode = _C89 | _C99 | _GNUC; break;
1841
1842                                 case STANDARD_CXX98:   invalid_mode = "c++98"; goto default_c_warn;
1843                                 case STANDARD_GNUXX98: invalid_mode = "gnu98"; goto default_c_warn;
1844                         }
1845                         goto do_parsing;
1846                 } else if (filetype == FILETYPE_PREPROCESSED_CXX) {
1847                         char const* invalid_mode;
1848                         switch (standard) {
1849                                 case STANDARD_C89:   invalid_mode = "c89";   goto default_cxx_warn;
1850                                 case STANDARD_C90:   invalid_mode = "c90";   goto default_cxx_warn;
1851                                 case STANDARD_C99:   invalid_mode = "c99";   goto default_cxx_warn;
1852                                 case STANDARD_GNU89: invalid_mode = "gnu89"; goto default_cxx_warn;
1853                                 case STANDARD_GNU99: invalid_mode = "gnu99"; goto default_cxx_warn;
1854
1855                                 case STANDARD_ANSI:
1856                                 case STANDARD_CXX98: c_mode = _CXX; break;
1857
1858 default_cxx_warn:
1859                                         fprintf(stderr,
1860                                                         "warning: command line option \"-std=%s\" is not valid for C++\n",
1861                                                         invalid_mode);
1862                                 case STANDARD_DEFAULT:
1863                                 case STANDARD_GNUXX98: c_mode = _CXX | _GNUC; break;
1864                         }
1865
1866 do_parsing:
1867                         c_mode |= features_on;
1868                         c_mode &= ~features_off;
1869
1870                         /* do the actual parsing */
1871                         ir_timer_t *t_parsing = ir_timer_new();
1872                         timer_register(t_parsing, "Frontend: Parsing");
1873                         timer_push(t_parsing);
1874                         init_tokens();
1875                         translation_unit_t *const unit = do_parsing(in, filename);
1876                         timer_pop(t_parsing);
1877
1878                         /* prints the AST even if errors occurred */
1879                         if (mode == PrintAst) {
1880                                 print_to_file(out);
1881                                 print_ast(unit);
1882                         }
1883
1884                         if (error_count > 0) {
1885                                 /* parsing failed because of errors */
1886                                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count,
1887                                         warning_count);
1888                                 result = EXIT_FAILURE;
1889                                 continue;
1890                         } else if (warning_count > 0) {
1891                                 fprintf(stderr, "%u warning(s)\n", warning_count);
1892                         }
1893
1894                         if (in == preprocessed_in) {
1895                                 int pp_result = pclose(preprocessed_in);
1896                                 if (pp_result != EXIT_SUCCESS) {
1897                                         /* remove output file */
1898                                         if (out != stdout)
1899                                                 unlink(outname);
1900                                         return EXIT_FAILURE;
1901                                 }
1902                         }
1903
1904                         if (mode == BenchmarkParser) {
1905                                 return result;
1906                         } else if (mode == PrintFluffy) {
1907                                 write_fluffy_decls(out, unit);
1908                                 continue;
1909                         } else if (mode == PrintJna) {
1910                                 write_jna_decls(out, unit);
1911                                 continue;
1912                         }
1913
1914                         /* build the firm graph */
1915                         ir_timer_t *t_construct = ir_timer_new();
1916                         timer_register(t_construct, "Frontend: Graph construction");
1917                         timer_push(t_construct);
1918                         if (already_constructed_firm) {
1919                                 panic("compiling multiple files/translation units not possible");
1920                         }
1921                         translation_unit_to_firm(unit);
1922                         already_constructed_firm = true;
1923                         timer_pop(t_construct);
1924
1925 graph_built:
1926                         if (mode == ParseOnly) {
1927                                 continue;
1928                         }
1929
1930                         if (mode == CompileDump) {
1931                                 /* find irg */
1932                                 ident    *id     = new_id_from_str(dumpfunction);
1933                                 ir_graph *irg    = NULL;
1934                                 int       n_irgs = get_irp_n_irgs();
1935                                 for (int i = 0; i < n_irgs; ++i) {
1936                                         ir_graph *tirg   = get_irp_irg(i);
1937                                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
1938                                         if (irg_id == id) {
1939                                                 irg = tirg;
1940                                                 break;
1941                                         }
1942                                 }
1943
1944                                 if (irg == NULL) {
1945                                         fprintf(stderr, "No graph for function '%s' found\n",
1946                                                 dumpfunction);
1947                                         return EXIT_FAILURE;
1948                                 }
1949
1950                                 dump_ir_graph_file(out, irg);
1951                                 fclose(out);
1952                                 return EXIT_SUCCESS;
1953                         }
1954
1955                         if (mode == CompileExportIR) {
1956                                 ir_export_file(out);
1957                                 if (ferror(out) != 0) {
1958                                         fprintf(stderr, "Error while writing to output\n");
1959                                         return EXIT_FAILURE;
1960                                 }
1961                                 return EXIT_SUCCESS;
1962                         }
1963
1964                         generate_code(asm_out, filename);
1965                         if (asm_out != out) {
1966                                 fclose(asm_out);
1967                         }
1968                 } else if (filetype == FILETYPE_IR) {
1969                         fclose(in);
1970                         int res = ir_import(filename);
1971                         if (res != 0) {
1972                                 fprintf(stderr, "Firm-Program import failed\n");
1973                                 return EXIT_FAILURE;
1974                         }
1975                         goto graph_built;
1976                 } else if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1977                         copy_file(asm_out, in);
1978                         if (in == preprocessed_in) {
1979                                 int pp_result = pclose(preprocessed_in);
1980                                 if (pp_result != EXIT_SUCCESS) {
1981                                         /* remove output in error case */
1982                                         if (out != stdout)
1983                                                 unlink(outname);
1984                                         return pp_result;
1985                                 }
1986                         }
1987                         if (asm_out != out) {
1988                                 fclose(asm_out);
1989                         }
1990                 }
1991
1992                 if (mode == Compile)
1993                         continue;
1994
1995                 /* if we're here then we have preprocessed assembly */
1996                 filename = asm_tempfile;
1997                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1998
1999                 /* assemble */
2000                 if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
2001                         char        temp[1024];
2002                         const char *filename_o;
2003                         if (mode == CompileAssemble) {
2004                                 fclose(out);
2005                                 filename_o = outname;
2006                         } else {
2007                                 FILE *tempf = make_temp_file(temp, sizeof(temp), "cco");
2008                                 fclose(tempf);
2009                                 filename_o = temp;
2010                         }
2011
2012                         assemble(filename_o, filename);
2013
2014                         size_t len = strlen(filename_o) + 1;
2015                         filename = obstack_copy(&file_obst, filename_o, len);
2016                         filetype = FILETYPE_OBJECT;
2017                 }
2018
2019                 /* ok we're done here, process next file */
2020                 file->name = filename;
2021                 file->type = filetype;
2022         }
2023
2024         if (result != EXIT_SUCCESS) {
2025                 if (out != stdout)
2026                         unlink(outname);
2027                 return result;
2028         }
2029
2030         /* link program file */
2031         if (mode == CompileAssembleLink) {
2032                 obstack_1grow(&ldflags_obst, '\0');
2033                 const char *flags = obstack_finish(&ldflags_obst);
2034
2035                 /* construct commandline */
2036                 const char *linker = getenv("CPARSER_LINK");
2037                 if (linker != NULL) {
2038                         obstack_printf(&file_obst, "%s ", linker);
2039                 } else {
2040                         if (target_triple != NULL)
2041                                 obstack_printf(&file_obst, "%s-", target_triple);
2042                         obstack_printf(&file_obst, "%s ", LINKER);
2043                 }
2044
2045                 for (file_list_entry_t *entry = files; entry != NULL;
2046                                 entry = entry->next) {
2047                         if (entry->type != FILETYPE_OBJECT)
2048                                 continue;
2049
2050                         add_flag(&file_obst, "%s", entry->name);
2051                 }
2052
2053                 add_flag(&file_obst, "-o");
2054                 add_flag(&file_obst, outname);
2055                 obstack_printf(&file_obst, "%s", flags);
2056                 obstack_1grow(&file_obst, '\0');
2057
2058                 char *commandline = obstack_finish(&file_obst);
2059
2060                 if (verbose) {
2061                         puts(commandline);
2062                 }
2063                 int err = system(commandline);
2064                 if (err != EXIT_SUCCESS) {
2065                         fprintf(stderr, "linker reported an error\n");
2066                         return EXIT_FAILURE;
2067                 }
2068         }
2069
2070         if (do_timing)
2071                 timer_term(stderr);
2072
2073         obstack_free(&cppflags_obst, NULL);
2074         obstack_free(&ldflags_obst, NULL);
2075         obstack_free(&asflags_obst, NULL);
2076         obstack_free(&file_obst, NULL);
2077
2078         gen_firm_finish();
2079         exit_mangle();
2080         exit_ast2firm();
2081         exit_parser();
2082         exit_ast();
2083         exit_lexer();
2084         exit_typehash();
2085         exit_types();
2086         exit_tokens();
2087         exit_symbol_table();
2088         return EXIT_SUCCESS;
2089 }