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