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