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