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