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