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