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