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