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