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