do not force -m32 by default but make -m32 work correctly
[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 "lexer.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_cmdline.h"
74 #include "driver/firm_timing.h"
75 #include "adt/error.h"
76 #include "wrappergen/write_fluffy.h"
77 #include "wrappergen/write_caml.h"
78 #include "wrappergen/write_jna.h"
79 #include "revision.h"
80 #include "warning.h"
81 #include "mangle.h"
82 #include "printer.h"
83
84 #ifndef PREPROCESSOR
85 #ifndef __WIN32__
86 #define PREPROCESSOR "gcc -E -U__STRICT_ANSI__"
87 #else
88 #define PREPROCESSOR "cpp -U__STRICT_ANSI__"
89 #endif
90 #endif
91
92 #ifndef LINKER
93 #define LINKER    "gcc"
94 #endif
95
96 #ifndef ASSEMBLER
97 #ifdef __APPLE__
98 #define ASSEMBLER "gcc -c -xassembler"
99 #else
100 #define ASSEMBLER "as"
101 #endif
102 #endif
103
104 unsigned int       c_mode                    = _C89 | _ANSI | _C99 | _GNUC;
105 unsigned int       machine_size              = 32;
106 bool               byte_order_big_endian     = false;
107 bool               char_is_signed            = true;
108 bool               strict_mode               = false;
109 bool               use_builtins              = false;
110 bool               have_const_functions      = false;
111 atomic_type_kind_t wchar_atomic_kind         = ATOMIC_TYPE_INT;
112 unsigned           force_long_double_size    = 0;
113 bool               enable_main_collect2_hack = false;
114 bool               freestanding              = false;
115
116 /* to switch on printing of implicit casts */
117 extern bool print_implicit_casts;
118
119 /* to switch on printing of parenthesis to indicate operator precedence */
120 extern bool print_parenthesis;
121
122 static const char     *target_triple;
123 static int             verbose;
124 static struct obstack  cppflags_obst;
125 static struct obstack  ldflags_obst;
126 static struct obstack  asflags_obst;
127 static char            dep_target[1024];
128 static const char     *outname;
129
130 typedef enum lang_standard_t {
131         STANDARD_DEFAULT, /* gnu99 (for C, GCC does gnu89) or gnu++98 (for C++) */
132         STANDARD_ANSI,    /* c89 (for C) or c++98 (for C++) */
133         STANDARD_C89,     /* ISO C90 (sic) */
134         STANDARD_C90,     /* ISO C90 as modified in amendment 1 */
135         STANDARD_C99,     /* ISO C99 */
136         STANDARD_GNU89,   /* ISO C90 plus GNU extensions (including some C99) */
137         STANDARD_GNU99,   /* ISO C99 plus GNU extensions */
138         STANDARD_CXX98,   /* ISO C++ 1998 plus amendments */
139         STANDARD_GNUXX98  /* ISO C++ 1998 plus amendments and GNU extensions */
140 } lang_standard_t;
141
142 static lang_standard_t standard;
143
144 typedef struct file_list_entry_t file_list_entry_t;
145
146 typedef enum filetype_t {
147         FILETYPE_AUTODETECT,
148         FILETYPE_C,
149         FILETYPE_PREPROCESSED_C,
150         FILETYPE_CXX,
151         FILETYPE_PREPROCESSED_CXX,
152         FILETYPE_ASSEMBLER,
153         FILETYPE_PREPROCESSED_ASSEMBLER,
154         FILETYPE_OBJECT,
155         FILETYPE_IR,
156         FILETYPE_UNKNOWN
157 } filetype_t;
158
159 struct file_list_entry_t {
160         const char  *name; /**< filename or NULL for stdin */
161         filetype_t   type;
162         file_list_entry_t *next;
163 };
164
165 static file_list_entry_t *temp_files;
166
167 static void initialize_firm(void)
168 {
169         firm_early_init();
170 }
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 #include "gen_builtins.h"
196
197 static translation_unit_t *do_parsing(FILE *const in, const char *const input_name)
198 {
199         start_parsing();
200
201         if (use_builtins) {
202                 lexer_open_buffer(builtins, sizeof(builtins)-1, "<builtin>");
203                 parse();
204         }
205
206         lexer_open_stream(in, input_name);
207         parse();
208
209         translation_unit_t *unit = finish_parsing();
210         return unit;
211 }
212
213 static void lextest(FILE *in, const char *fname)
214 {
215         lexer_open_stream(in, fname);
216
217         do {
218                 lexer_next_preprocessing_token();
219                 print_token(stdout, &lexer_token);
220                 putchar('\n');
221         } while (lexer_token.type != T_EOF);
222 }
223
224 static void add_flag(struct obstack *obst, const char *format, ...)
225 {
226         char buf[65536];
227         va_list ap;
228
229         va_start(ap, format);
230 #ifdef _WIN32
231         int len =
232 #endif
233                 vsnprintf(buf, sizeof(buf), format, ap);
234         va_end(ap);
235
236         obstack_1grow(obst, ' ');
237 #ifdef _WIN32
238         obstack_1grow(obst, '"');
239         obstack_grow(obst, buf, len);
240         obstack_1grow(obst, '"');
241 #else
242         /* escape stuff... */
243         for (char *c = buf; *c != '\0'; ++c) {
244                 switch(*c) {
245                 case ' ':
246                 case '"':
247                 case '$':
248                 case '&':
249                 case '(':
250                 case ')':
251                 case ';':
252                 case '<':
253                 case '>':
254                 case '\'':
255                 case '\\':
256                 case '\n':
257                 case '\r':
258                 case '\t':
259                 case '`':
260                 case '|':
261                         obstack_1grow(obst, '\\');
262                         /* FALLTHROUGH */
263                 default:
264                         obstack_1grow(obst, *c);
265                         break;
266                 }
267         }
268 #endif
269 }
270
271 static const char *type_to_string(type_t *type)
272 {
273         assert(type->kind == TYPE_ATOMIC);
274         return get_atomic_kind_name(type->atomic.akind);
275 }
276
277 static FILE *preprocess(const char *fname, filetype_t filetype)
278 {
279         static const char *common_flags = NULL;
280
281         if (common_flags == NULL) {
282                 obstack_1grow(&cppflags_obst, '\0');
283                 const char *flags = obstack_finish(&cppflags_obst);
284
285                 /* setup default defines */
286                 add_flag(&cppflags_obst, "-U__WCHAR_TYPE__");
287                 add_flag(&cppflags_obst, "-D__WCHAR_TYPE__=%s", type_to_string(type_wchar_t));
288                 add_flag(&cppflags_obst, "-U__SIZE_TYPE__");
289                 add_flag(&cppflags_obst, "-D__SIZE_TYPE__=%s", type_to_string(type_size_t));
290
291                 add_flag(&cppflags_obst, "-U__VERSION__");
292                 add_flag(&cppflags_obst, "-D__VERSION__=\"%s\"", cparser_REVISION);
293
294                 if (flags[0] != '\0') {
295                         size_t len = strlen(flags);
296                         obstack_1grow(&cppflags_obst, ' ');
297                         obstack_grow(&cppflags_obst, flags, len);
298                 }
299                 obstack_1grow(&cppflags_obst, '\0');
300                 common_flags = obstack_finish(&cppflags_obst);
301         }
302
303         assert(obstack_object_size(&cppflags_obst) == 0);
304
305         const char *preprocessor = getenv("CPARSER_PP");
306         if (preprocessor != NULL) {
307                 obstack_printf(&cppflags_obst, "%s ", preprocessor);
308         } else {
309                 if (target_triple != NULL)
310                         obstack_printf(&cppflags_obst, "%s-", target_triple);
311                 obstack_printf(&cppflags_obst, PREPROCESSOR);
312         }
313
314         switch (filetype) {
315         case FILETYPE_C:
316                 add_flag(&cppflags_obst, "-std=c99");
317                 break;
318         case FILETYPE_CXX:
319                 add_flag(&cppflags_obst, "-std=c++98");
320                 break;
321         case FILETYPE_ASSEMBLER:
322                 add_flag(&cppflags_obst, "-x");
323                 add_flag(&cppflags_obst, "assembler-with-cpp");
324                 break;
325         default:
326                 break;
327         }
328         obstack_printf(&cppflags_obst, "%s", common_flags);
329
330         /* handle dependency generation */
331         if (dep_target[0] != '\0') {
332                 add_flag(&cppflags_obst, "-MF");
333                 add_flag(&cppflags_obst, dep_target);
334                 if (outname != NULL) {
335                                 add_flag(&cppflags_obst, "-MQ");
336                                 add_flag(&cppflags_obst, outname);
337                 }
338         }
339         add_flag(&cppflags_obst, fname);
340         obstack_1grow(&cppflags_obst, '\0');
341
342         char *commandline = obstack_finish(&cppflags_obst);
343         if (verbose) {
344                 puts(commandline);
345         }
346         FILE *f = popen(commandline, "r");
347         if (f == NULL) {
348                 fprintf(stderr, "invoking preprocessor failed\n");
349                 exit(EXIT_FAILURE);
350         }
351         /* we don't really need that anymore */
352         obstack_free(&cppflags_obst, commandline);
353
354         return f;
355 }
356
357 static void assemble(const char *out, const char *in)
358 {
359         obstack_1grow(&asflags_obst, '\0');
360         const char *flags = obstack_finish(&asflags_obst);
361
362         const char *assembler = getenv("CPARSER_AS");
363         if (assembler != NULL) {
364                 obstack_printf(&asflags_obst, "%s", assembler);
365         } else {
366                 if (target_triple != NULL)
367                         obstack_printf(&asflags_obst, "%s-", target_triple);
368                 obstack_printf(&asflags_obst, "%s", ASSEMBLER);
369         }
370         if (flags[0] != '\0')
371                 obstack_printf(&asflags_obst, " %s", flags);
372
373         obstack_printf(&asflags_obst, " %s -o %s", in, out);
374         obstack_1grow(&asflags_obst, '\0');
375
376         char *commandline = obstack_finish(&asflags_obst);
377         if (verbose) {
378                 puts(commandline);
379         }
380         int err = system(commandline);
381         if (err != EXIT_SUCCESS) {
382                 fprintf(stderr, "assembler reported an error\n");
383                 exit(EXIT_FAILURE);
384         }
385         obstack_free(&asflags_obst, commandline);
386 }
387
388 static void print_file_name(const char *file)
389 {
390         add_flag(&ldflags_obst, "-print-file-name=%s", file);
391
392         obstack_1grow(&ldflags_obst, '\0');
393         const char *flags = obstack_finish(&ldflags_obst);
394
395         /* construct commandline */
396         const char *linker = getenv("CPARSER_LINK");
397         if (linker != NULL) {
398                 obstack_printf(&ldflags_obst, "%s ", linker);
399         } else {
400                 if (target_triple != NULL)
401                         obstack_printf(&ldflags_obst, "%s-", target_triple);
402                 obstack_printf(&ldflags_obst, "%s ", LINKER);
403         }
404         obstack_printf(&ldflags_obst, "%s ", linker);
405         obstack_printf(&ldflags_obst, "%s", flags);
406         obstack_1grow(&ldflags_obst, '\0');
407
408         char *commandline = obstack_finish(&ldflags_obst);
409         if (verbose) {
410                 puts(commandline);
411         }
412         int err = system(commandline);
413         if (err != EXIT_SUCCESS) {
414                 fprintf(stderr, "linker reported an error\n");
415                 exit(EXIT_FAILURE);
416         }
417         obstack_free(&ldflags_obst, commandline);
418 }
419
420 static const char *try_dir(const char *dir)
421 {
422         if (dir == NULL)
423                 return dir;
424         if (access(dir, R_OK | W_OK | X_OK) == 0)
425                 return dir;
426         return NULL;
427 }
428
429 static const char *get_tempdir(void)
430 {
431         static const char *tmpdir = NULL;
432
433         if (tmpdir != NULL)
434                 return tmpdir;
435
436         if (tmpdir == NULL)
437                 tmpdir = try_dir(getenv("TMPDIR"));
438         if (tmpdir == NULL)
439                 tmpdir = try_dir(getenv("TMP"));
440         if (tmpdir == NULL)
441                 tmpdir = try_dir(getenv("TEMP"));
442
443 #ifdef P_tmpdir
444         if (tmpdir == NULL)
445                 tmpdir = try_dir(P_tmpdir);
446 #endif
447
448         if (tmpdir == NULL)
449                 tmpdir = try_dir("/var/tmp");
450         if (tmpdir == NULL)
451                 tmpdir = try_dir("/usr/tmp");
452         if (tmpdir == NULL)
453                 tmpdir = try_dir("/tmp");
454
455         if (tmpdir == NULL)
456                 tmpdir = ".";
457
458         return tmpdir;
459 }
460
461 #ifndef HAVE_MKSTEMP
462 /* cheap and nasty mkstemp replacement */
463 static int mkstemp(char *templ)
464 {
465         mktemp(templ);
466         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
467 }
468 #endif
469
470 /**
471  * an own version of tmpnam, which: writes in a buffer, emits no warnings
472  * during linking (like glibc/gnu ld do for tmpnam)...
473  */
474 static FILE *make_temp_file(char *buffer, size_t buflen, const char *prefix)
475 {
476         const char *tempdir = get_tempdir();
477
478         snprintf(buffer, buflen, "%s/%sXXXXXX", tempdir, prefix);
479
480         int fd = mkstemp(buffer);
481         if (fd == -1) {
482                 fprintf(stderr, "couldn't create temporary file: %s\n",
483                         strerror(errno));
484                 exit(EXIT_FAILURE);
485         }
486         FILE *out = fdopen(fd, "w");
487         if (out == NULL) {
488                 fprintf(stderr, "couldn't create temporary file FILE*\n");
489                 exit(EXIT_FAILURE);
490         }
491
492         file_list_entry_t *entry = xmalloc(sizeof(*entry));
493         memset(entry, 0, sizeof(*entry));
494
495         size_t  name_len = strlen(buffer) + 1;
496         char   *name     = malloc(name_len);
497         memcpy(name, buffer, name_len);
498         entry->name      = name;
499
500         entry->next = temp_files;
501         temp_files  = entry;
502
503         return out;
504 }
505
506 static void free_temp_files(void)
507 {
508         file_list_entry_t *entry = temp_files;
509         file_list_entry_t *next;
510         for ( ; entry != NULL; entry = next) {
511                 next = entry->next;
512
513                 unlink(entry->name);
514                 free((char*) entry->name);
515                 free(entry);
516         }
517         temp_files = NULL;
518 }
519
520 typedef enum compile_mode_t {
521         BenchmarkParser,
522         PreprocessOnly,
523         ParseOnly,
524         Compile,
525         CompileDump,
526         CompileExportIR,
527         CompileAssemble,
528         CompileAssembleLink,
529         LexTest,
530         PrintAst,
531         PrintFluffy,
532         PrintCaml,
533         PrintJna
534 } compile_mode_t;
535
536 static void usage(const char *argv0)
537 {
538         fprintf(stderr, "Usage %s [options] input [-o output]\n", argv0);
539 }
540
541 static void print_cparser_version(void)
542 {
543         printf("cparser (%s) using libFirm (%u.%u",
544                cparser_REVISION, ir_get_version_major(),
545                ir_get_version_minor());
546
547         const char *revision = ir_get_version_revision();
548         if (revision[0] != 0) {
549                 putchar(' ');
550                 fputs(revision, stdout);
551         }
552
553         const char *build = ir_get_version_build();
554         if (build[0] != 0) {
555                 putchar(' ');
556                 fputs(build, stdout);
557         }
558         puts(")");
559         puts("This is free software; see the source for copying conditions.  There is NO\n"
560              "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
561 }
562
563 static void print_help(const char *argv0)
564 {
565         usage(argv0);
566         puts("");
567         puts("\t-fhelp     Display help about firm optimisation options");
568         puts("\t-bhelp     Display help about firm backend options");
569         puts("A big number of gcc flags is also supported");
570 }
571
572 static void set_be_option(const char *arg)
573 {
574         int res = be_parse_arg(arg);
575         (void) res;
576         assert(res);
577 }
578
579 static void set_option(const char *arg)
580 {
581         int res = firm_option(arg);
582         (void) res;
583         assert(res);
584 }
585
586 static void copy_file(FILE *dest, FILE *input)
587 {
588         char buf[16384];
589
590         while (!feof(input) && !ferror(dest)) {
591                 size_t read = fread(buf, 1, sizeof(buf), input);
592                 if (fwrite(buf, 1, read, dest) != read) {
593                         perror("couldn't write output");
594                 }
595         }
596 }
597
598 static inline bool streq(char const* a, char const* b)
599 {
600         return strcmp(a, b) == 0;
601 }
602
603 static inline bool strstart(char const* str, char const* start)
604 {
605         do {
606                 if (*start == '\0')
607                         return true;
608         } while (*str++ == *start++);
609         return false;
610 }
611
612 static FILE *open_file(const char *filename)
613 {
614         if (streq(filename, "-")) {
615                 return stdin;
616         }
617
618         FILE *in = fopen(filename, "r");
619         if (in == NULL) {
620                 fprintf(stderr, "Couldn't open '%s': %s\n", filename,
621                                 strerror(errno));
622                 exit(EXIT_FAILURE);
623         }
624
625         return in;
626 }
627
628 static filetype_t get_filetype_from_string(const char *string)
629 {
630         if (streq(string, "c") || streq(string, "c-header"))
631                 return FILETYPE_C;
632         if (streq(string, "c++") || streq(string, "c++-header"))
633                 return FILETYPE_CXX;
634         if (streq(string, "assembler"))
635                 return FILETYPE_PREPROCESSED_ASSEMBLER;
636         if (streq(string, "assembler-with-cpp"))
637                 return FILETYPE_ASSEMBLER;
638         if (streq(string, "none"))
639                 return FILETYPE_AUTODETECT;
640
641         return FILETYPE_UNKNOWN;
642 }
643
644 /**
645  * Initialize firm codegeneration for a specific operating system.
646  * The argument is the operating system part of a target-triple */
647 static bool set_os_support(const char *os)
648 {
649         wchar_atomic_kind         = ATOMIC_TYPE_INT;
650         force_long_double_size    = 0;
651         enable_main_collect2_hack = false;
652
653         if (strstr(os, "linux") != NULL || strstr(os, "bsd") != NULL
654                         || streq(os, "solaris")) {
655                 set_be_option("ia32-gasmode=elf");
656                 set_create_ld_ident(create_name_linux_elf);
657         } else if (streq(os, "darwin")) {
658                 force_long_double_size = 16;
659                 set_be_option("ia32-gasmode=macho");
660                 set_be_option("ia32-stackalign=4");
661                 set_be_option("pic=true");
662                 set_create_ld_ident(create_name_macho);
663         } else if (strstr(os, "mingw") != NULL || streq(os, "win32")) {
664                 wchar_atomic_kind         = ATOMIC_TYPE_USHORT;
665                 enable_main_collect2_hack = true;
666                 set_be_option("ia32-gasmode=mingw");
667                 set_create_ld_ident(create_name_win32);
668         } else {
669                 return false;
670         }
671
672         return true;
673 }
674
675 static bool parse_target_triple(const char *arg)
676 {
677         const char *manufacturer = strchr(arg, '-');
678         if (manufacturer == NULL) {
679                 fprintf(stderr, "Target-triple is not in the form 'cpu_type-manufacturer-operating_system'\n");
680                 return false;
681         }
682         manufacturer += 1;
683
684         const char *os = strchr(manufacturer, '-');
685         if (os == NULL) {
686                 fprintf(stderr, "Target-triple is not in the form 'cpu_type-manufacturer-operating_system'\n");
687                 return false;
688         }
689         os += 1;
690
691         /* Note: Triples are more or less defined by what the config.guess and
692          * config.sub scripts from GNU autoconf emit. We have to lookup there what
693          * triples are possible */
694
695         /* process cpu type */
696         if (strstart(arg, "i386-")) {
697                 be_parse_arg("isa=ia32");
698                 be_parse_arg("ia32-arch=i386");
699         } else if (strstart(arg, "i486-")) {
700                 be_parse_arg("isa=ia32");
701                 be_parse_arg("ia32-arch=i486");
702         } else if (strstart(arg, "i586-")) {
703                 be_parse_arg("isa=ia32");
704                 be_parse_arg("ia32-arch=i586");
705         } else if (strstart(arg, "i686-")) {
706                 be_parse_arg("isa=ia32");
707                 be_parse_arg("ia32-arch=i686");
708         } else if (strstart(arg, "i786-")) {
709                 be_parse_arg("isa=ia32");
710                 be_parse_arg("ia32-arch=pentium4");
711         } else if (strstart(arg, "x86_64")) {
712                 be_parse_arg("isa=amd64");
713         } else if (strstart(arg, "sparc-")) {
714                 be_parse_arg("isa=sparc");
715         } else if (strstart(arg, "arm-")) {
716                 be_parse_arg("isa=arm");
717         } else {
718                 fprintf(stderr, "Unknown cpu in triple '%s'\n", arg);
719                 return false;
720         }
721
722         /* process manufacturer, alot of people incorrectly leave out the
723          * manufacturer instead of using unknown- */
724         if (strstart(manufacturer, "linux")) {
725                 os = manufacturer;
726                 manufacturer = "unknown-";
727         }
728
729         /* process operating system */
730         if (!set_os_support(os)) {
731                 fprintf(stderr, "Unknown operating system '%s' in triple '%s'\n", os, arg);
732                 return false;
733         }
734
735         target_triple = arg;
736         return true;
737 }
738
739 int main(int argc, char **argv)
740 {
741         initialize_firm();
742
743         const char        *dumpfunction         = NULL;
744         const char        *print_file_name_file = NULL;
745         compile_mode_t     mode                 = CompileAssembleLink;
746         int                opt_level            = 1;
747         int                result               = EXIT_SUCCESS;
748         char               cpu_arch[16]         = "ia32";
749         file_list_entry_t *files                = NULL;
750         file_list_entry_t *last_file            = NULL;
751         bool               construct_dep_target = false;
752         bool               do_timing            = false;
753         struct obstack     file_obst;
754
755         atexit(free_temp_files);
756
757         /* hack for now... */
758         if (strstr(argv[0], "pptest") != NULL) {
759                 extern int pptest_main(int argc, char **argv);
760                 return pptest_main(argc, argv);
761         }
762
763         obstack_init(&cppflags_obst);
764         obstack_init(&ldflags_obst);
765         obstack_init(&asflags_obst);
766         obstack_init(&file_obst);
767
768 #define GET_ARG_AFTER(def, args)                                             \
769         def = &arg[sizeof(args)-1];                                              \
770         if (def[0] == '\0') {                                                     \
771                 ++i;                                                                 \
772                 if (i >= argc) {                                                      \
773                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
774                         argument_errors = true;                                          \
775                         break;                                                           \
776                 }                                                                    \
777                 def = argv[i];                                                       \
778                 if (def[0] == '-' && def[1] != '\0') {                                \
779                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
780                         argument_errors = true;                                          \
781                         continue;                                                        \
782                 }                                                                    \
783         }
784
785 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
786
787         /* early options parsing (find out optimisation level and OS) */
788         for (int i = 1; i < argc; ++i) {
789                 const char *arg = argv[i];
790                 if (arg[0] != '-')
791                         continue;
792
793                 const char *option = &arg[1];
794                 if (option[0] == 'O') {
795                         sscanf(&option[1], "%d", &opt_level);
796                 }
797         }
798
799         /* Guess host OS */
800 #if defined(_WIN32) || defined(__CYGWIN__)
801         set_os_support("win32");
802 #elif defined(__APPLE__)
803         set_os_support("darwin");
804 #else
805         set_os_support("linux");
806 #endif
807
808         /* apply optimisation level */
809         switch(opt_level) {
810         case 0:
811                 set_option("no-opt");
812                 break;
813         case 1:
814                 set_option("no-inline");
815                 break;
816         default:
817         case 4:
818                 /* use_builtins = true; */
819                 /* fallthrough */
820         case 3:
821                 set_option("thread-jumps");
822                 set_option("if-conversion");
823                 /* fallthrough */
824         case 2:
825                 set_option("strict-aliasing");
826                 set_option("inline");
827                 set_option("deconv");
828                 set_be_option("omitfp");
829                 break;
830         }
831
832         const char *target = getenv("TARGET");
833         if (target != NULL)
834                 parse_target_triple(target);
835
836         /* parse rest of options */
837         standard                   = STANDARD_DEFAULT;
838         unsigned   features_on     = 0;
839         unsigned   features_off    = 0;
840         filetype_t forced_filetype = FILETYPE_AUTODETECT;
841         bool       help_displayed  = false;
842         bool       argument_errors = false;
843         for (int i = 1; i < argc; ++i) {
844                 const char *arg = argv[i];
845                 if (arg[0] == '-' && arg[1] != '\0') {
846                         /* an option */
847                         const char *option = &arg[1];
848                         if (option[0] == 'o') {
849                                 GET_ARG_AFTER(outname, "-o");
850                         } else if (option[0] == 'g') {
851                                 set_be_option("debuginfo=stabs");
852                                 set_be_option("omitfp=no");
853                                 set_be_option("ia32-nooptcc=yes");
854                         } else if (SINGLE_OPTION('c')) {
855                                 mode = CompileAssemble;
856                         } else if (SINGLE_OPTION('E')) {
857                                 mode = PreprocessOnly;
858                         } else if (SINGLE_OPTION('S')) {
859                                 mode = Compile;
860                         } else if (option[0] == 'O') {
861                                 continue;
862                         } else if (option[0] == 'I') {
863                                 const char *opt;
864                                 GET_ARG_AFTER(opt, "-I");
865                                 add_flag(&cppflags_obst, "-I%s", opt);
866                         } else if (option[0] == 'D') {
867                                 const char *opt;
868                                 GET_ARG_AFTER(opt, "-D");
869                                 add_flag(&cppflags_obst, "-D%s", opt);
870                         } else if (option[0] == 'U') {
871                                 const char *opt;
872                                 GET_ARG_AFTER(opt, "-U");
873                                 add_flag(&cppflags_obst, "-U%s", opt);
874                         } else if (option[0] == 'l') {
875                                 const char *opt;
876                                 GET_ARG_AFTER(opt, "-l");
877                                 add_flag(&ldflags_obst, "-l%s", opt);
878                         } else if (option[0] == 'L') {
879                                 const char *opt;
880                                 GET_ARG_AFTER(opt, "-L");
881                                 add_flag(&ldflags_obst, "-L%s", opt);
882                         } else if (SINGLE_OPTION('v')) {
883                                 verbose = 1;
884                         } else if (SINGLE_OPTION('w')) {
885                                 memset(&warning, 0, sizeof(warning));
886                         } else if (option[0] == 'x') {
887                                 const char *opt;
888                                 GET_ARG_AFTER(opt, "-x");
889                                 forced_filetype = get_filetype_from_string(opt);
890                                 if (forced_filetype == FILETYPE_UNKNOWN) {
891                                         fprintf(stderr, "Unknown language '%s'\n", opt);
892                                         argument_errors = true;
893                                 }
894                         } else if (streq(option, "M")) {
895                                 mode = PreprocessOnly;
896                                 add_flag(&cppflags_obst, "-M");
897                         } else if (streq(option, "MMD") ||
898                                    streq(option, "MD")) {
899                             construct_dep_target = true;
900                                 add_flag(&cppflags_obst, "-%s", option);
901                         } else if (streq(option, "MM")  ||
902                                    streq(option, "MP")) {
903                                 add_flag(&cppflags_obst, "-%s", option);
904                         } else if (streq(option, "MT") ||
905                                    streq(option, "MQ") ||
906                                    streq(option, "MF")) {
907                                 const char *opt;
908                                 GET_ARG_AFTER(opt, "-MT");
909                                 add_flag(&cppflags_obst, "-%s", option);
910                                 add_flag(&cppflags_obst, "%s", opt);
911                         } else if (streq(option, "include")) {
912                                 const char *opt;
913                                 GET_ARG_AFTER(opt, "-include");
914                                 add_flag(&cppflags_obst, "-include");
915                                 add_flag(&cppflags_obst, "%s", opt);
916                         } else if (streq(option, "isystem")) {
917                                 const char *opt;
918                                 GET_ARG_AFTER(opt, "-isystem");
919                                 add_flag(&cppflags_obst, "-isystem");
920                                 add_flag(&cppflags_obst, "%s", opt);
921 #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__CYGWIN__)
922                         } else if (streq(option, "pthread")) {
923                                 /* set flags for the preprocessor */
924                                 add_flag(&cppflags_obst, "-D_REENTRANT");
925                                 /* set flags for the linker */
926                                 add_flag(&ldflags_obst, "-lpthread");
927 #endif
928                         } else if (streq(option, "nostdinc")
929                                         || streq(option, "trigraphs")) {
930                                 /* pass these through to the preprocessor */
931                                 add_flag(&cppflags_obst, "%s", arg);
932                         } else if (streq(option, "pipe")) {
933                                 /* here for gcc compatibility */
934                         } else if (streq(option, "static")) {
935                                 add_flag(&ldflags_obst, "-static");
936                         } else if (streq(option, "shared")) {
937                                 add_flag(&ldflags_obst, "-shared");
938                         } else if (option[0] == 'f') {
939                                 char const *orig_opt;
940                                 GET_ARG_AFTER(orig_opt, "-f");
941
942                                 if (strstart(orig_opt, "input-charset=")) {
943                                         char const* const encoding = strchr(orig_opt, '=') + 1;
944                                         select_input_encoding(encoding);
945                                 } else if (streq(orig_opt, "verbose-asm")) {
946                                         /* ignore: we always print verbose assembler */
947                                 } else {
948                                         char const *opt         = orig_opt;
949                                         bool        truth_value = true;
950                                         if (opt[0] == 'n' && opt[1] == 'o' && opt[2] == '-') {
951                                                 truth_value = false;
952                                                 opt += 3;
953                                         }
954
955                                         if (streq(opt, "builtins")) {
956                                                 use_builtins = truth_value;
957                                         } else if (streq(opt, "dollars-in-identifiers")) {
958                                                 allow_dollar_in_symbol = truth_value;
959                                         } else if (streq(opt, "omit-frame-pointer")) {
960                                                 set_be_option(truth_value ? "omitfp" : "omitfp=no");
961                                         } else if (streq(opt, "short-wchar")) {
962                                                 wchar_atomic_kind = truth_value ? ATOMIC_TYPE_USHORT
963                                                         : ATOMIC_TYPE_INT;
964                                         } else if (streq(opt, "signed-char")) {
965                                                 char_is_signed = truth_value;
966                                         } else if (streq(opt, "strength-reduce")) {
967                                                 firm_option(truth_value ? "strength-red" : "no-strength-red");
968                                         } else if (streq(opt, "syntax-only")) {
969                                                 mode = truth_value ? ParseOnly : CompileAssembleLink;
970                                         } else if (streq(opt, "unsigned-char")) {
971                                                 char_is_signed = !truth_value;
972                                         } else if (streq(opt, "freestanding")) {
973                                                 freestanding = true;
974                                         } else if (streq(opt, "hosted")) {
975                                                 freestanding = false;
976                                         } else if (truth_value == false &&
977                                                    streq(opt, "asynchronous-unwind-tables")) {
978                                             /* nothing todo, a gcc feature which we don't support
979                                              * anyway was deactivated */
980                                         } else if (strstart(orig_opt, "align-loops=") ||
981                                                         strstart(orig_opt, "align-jumps=") ||
982                                                         strstart(orig_opt, "align-functions=")) {
983                                                 fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
984                                         } else if (strstart(orig_opt, "message-length=")) {
985                                                         /* ignore: would only affect error message format */
986                                         } else if (streq(opt, "fast-math")               ||
987                                                    streq(opt, "jump-tables")             ||
988                                                    streq(opt, "expensive-optimizations") ||
989                                                    streq(opt, "common")                  ||
990                                                    streq(opt, "optimize-sibling-calls")  ||
991                                                    streq(opt, "align-loops")             ||
992                                                    streq(opt, "align-jumps")             ||
993                                                    streq(opt, "align-functions")         ||
994                                                    streq(opt, "PIC")) {
995                                                 fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
996                                         } else {
997                                                 int res = firm_option(orig_opt);
998                                                 if (res == 0) {
999                                                         fprintf(stderr, "error: unknown Firm option '-f%s'\n",
1000                                                                 orig_opt);
1001                                                         argument_errors = true;
1002                                                         continue;
1003                                                 } else if (res == -1) {
1004                                                         help_displayed = true;
1005                                                 }
1006                                         }
1007                                 }
1008                         } else if (option[0] == 'b') {
1009                                 const char *opt;
1010                                 GET_ARG_AFTER(opt, "-b");
1011                                 int res = be_parse_arg(opt);
1012                                 if (res == 0) {
1013                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
1014                                                 opt);
1015                                         argument_errors = true;
1016                                 } else if (res == -1) {
1017                                         help_displayed = true;
1018                                 } else if (strstart(opt, "isa=")) {
1019                                         strncpy(cpu_arch, opt, sizeof(cpu_arch));
1020                                 }
1021                         } else if (option[0] == 'W') {
1022                                 if (option[1] == '\0') {
1023                                         /* ignore -W, our defaults are already quite verbose */
1024                                 } else if (strstart(option + 1, "p,")) {
1025                                         // pass options directly to the preprocessor
1026                                         const char *opt;
1027                                         GET_ARG_AFTER(opt, "-Wp,");
1028                                         add_flag(&cppflags_obst, "-Wp,%s", opt);
1029                                 } else if (strstart(option + 1, "l,")) {
1030                                         // pass options directly to the linker
1031                                         const char *opt;
1032                                         GET_ARG_AFTER(opt, "-Wl,");
1033                                         add_flag(&ldflags_obst, "-Wl,%s", opt);
1034                                 } else if (streq(option + 1, "no-trigraphs")
1035                                                         || streq(option + 1, "undef")) {
1036                                         add_flag(&cppflags_obst, "%s", arg);
1037                                 } else {
1038                                         set_warning_opt(&option[1]);
1039                                 }
1040                         } else if (option[0] == 'm') {
1041                                 /* -m options */
1042                                 const char *opt;
1043                                 char arch_opt[64];
1044
1045                                 GET_ARG_AFTER(opt, "-m");
1046                                 if (strstart(opt, "target=")) {
1047                                         GET_ARG_AFTER(opt, "-mtarget=");
1048                                         if (!parse_target_triple(opt))
1049                                                 argument_errors = true;
1050                                 } else if (strstart(opt, "triple=")) {
1051                                         GET_ARG_AFTER(opt, "-mtriple=");
1052                                         if (!parse_target_triple(opt))
1053                                                 argument_errors = true;
1054                                 } else if (strstart(opt, "arch=")) {
1055                                         GET_ARG_AFTER(opt, "-march=");
1056                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
1057                                         int res = be_parse_arg(arch_opt);
1058                                         if (res == 0) {
1059                                                 fprintf(stderr, "Unknown architecture '%s'\n", arch_opt);
1060                                                 argument_errors = true;
1061                                         } else {
1062                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
1063                                                 int res = be_parse_arg(arch_opt);
1064                                                 if (res == 0)
1065                                                         argument_errors = true;
1066                                         }
1067                                 } else if (strstart(opt, "tune=")) {
1068                                         GET_ARG_AFTER(opt, "-mtune=");
1069                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
1070                                         int res = be_parse_arg(arch_opt);
1071                                         if (res == 0)
1072                                                 argument_errors = true;
1073                                 } else if (strstart(opt, "cpu=")) {
1074                                         GET_ARG_AFTER(opt, "-mcpu=");
1075                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
1076                                         int res = be_parse_arg(arch_opt);
1077                                         if (res == 0)
1078                                                 argument_errors = true;
1079                                 } else if (strstart(opt, "fpmath=")) {
1080                                         GET_ARG_AFTER(opt, "-mfpmath=");
1081                                         if (streq(opt, "387"))
1082                                                 opt = "x87";
1083                                         else if (streq(opt, "sse"))
1084                                                 opt = "sse2";
1085                                         else {
1086                                                 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
1087                                                 argument_errors = true;
1088                                         }
1089                                         if (!argument_errors) {
1090                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
1091                                                 int res = be_parse_arg(arch_opt);
1092                                                 if (res == 0)
1093                                                         argument_errors = true;
1094                                         }
1095                                 } else if (strstart(opt, "preferred-stack-boundary=")) {
1096                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
1097                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
1098                                         int res = be_parse_arg(arch_opt);
1099                                         if (res == 0)
1100                                                 argument_errors = true;
1101                                 } else if (streq(opt, "omit-leaf-frame-pointer")) {
1102                                         set_be_option("omitleaffp=1");
1103                                 } else if (streq(opt, "no-omit-leaf-frame-pointer")) {
1104                                         set_be_option("omitleaffp=0");
1105                                 } else if (streq(opt, "rtd")) {
1106                                         default_calling_convention = CC_STDCALL;
1107                                 } else if (strstart(opt, "regparm=")) {
1108                                         fprintf(stderr, "error: regparm convention not supported yet\n");
1109                                         argument_errors = true;
1110                                 } else if (streq(opt, "soft-float")) {
1111                                         fprintf(stderr, "error: software floatingpoint not supported yet\n");
1112                                         argument_errors = true;
1113                                 } else {
1114                                         long int value = strtol(opt, NULL, 10);
1115                                         if (value == 0) {
1116                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
1117                                                 argument_errors = true;
1118                                         } else if (value != 16 && value != 32 && value != 64) {
1119                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
1120                                                 argument_errors = true;
1121                                         } else {
1122                                                 machine_size = (unsigned int)value;
1123                                                 add_flag(&asflags_obst, "--%u", machine_size);
1124                                                 add_flag(&ldflags_obst, "-m%u", machine_size);
1125                                         }
1126                                 }
1127                         } else if (streq(option, "pg")) {
1128                                 set_be_option("gprof");
1129                                 add_flag(&ldflags_obst, "-pg");
1130                         } else if (streq(option, "pedantic") ||
1131                                    streq(option, "ansi")) {
1132                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
1133                         } else if (streq(option, "shared")) {
1134                                 add_flag(&ldflags_obst, "-shared");
1135                         } else if (strstart(option, "std=")) {
1136                                 const char *const o = &option[4];
1137                                 standard =
1138                                         streq(o, "c++")            ? STANDARD_CXX98   :
1139                                         streq(o, "c++98")          ? STANDARD_CXX98   :
1140                                         streq(o, "c89")            ? STANDARD_C89     :
1141                                         streq(o, "c99")            ? STANDARD_C99     :
1142                                         streq(o, "c9x")            ? STANDARD_C99     : // deprecated
1143                                         streq(o, "gnu++98")        ? STANDARD_GNUXX98 :
1144                                         streq(o, "gnu89")          ? STANDARD_GNU89   :
1145                                         streq(o, "gnu99")          ? STANDARD_GNU99   :
1146                                         streq(o, "gnu9x")          ? STANDARD_GNU99   : // deprecated
1147                                         streq(o, "iso9899:1990")   ? STANDARD_C89     :
1148                                         streq(o, "iso9899:199409") ? STANDARD_C90     :
1149                                         streq(o, "iso9899:1999")   ? STANDARD_C99     :
1150                                         streq(o, "iso9899:199x")   ? STANDARD_C99     : // deprecated
1151                                         (fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg), standard);
1152                         } else if (streq(option, "version")) {
1153                                 print_cparser_version();
1154                         } else if (strstart(option, "print-file-name=")) {
1155                                 GET_ARG_AFTER(print_file_name_file, "-print-file-name=");
1156                         } else if (option[0] == '-') {
1157                                 /* double dash option */
1158                                 ++option;
1159                                 if (streq(option, "gcc")) {
1160                                         features_on  |=  _GNUC;
1161                                         features_off &= ~_GNUC;
1162                                 } else if (streq(option, "no-gcc")) {
1163                                         features_on  &= ~_GNUC;
1164                                         features_off |=  _GNUC;
1165                                 } else if (streq(option, "ms")) {
1166                                         features_on  |=  _MS;
1167                                         features_off &= ~_MS;
1168                                 } else if (streq(option, "no-ms")) {
1169                                         features_on  &= ~_MS;
1170                                         features_off |=  _MS;
1171                                 } else if (streq(option, "strict")) {
1172                                         strict_mode = true;
1173                                 } else if (streq(option, "lextest")) {
1174                                         mode = LexTest;
1175                                 } else if (streq(option, "benchmark")) {
1176                                         mode = BenchmarkParser;
1177                                 } else if (streq(option, "print-ast")) {
1178                                         mode = PrintAst;
1179                                 } else if (streq(option, "print-implicit-cast")) {
1180                                         print_implicit_casts = true;
1181                                 } else if (streq(option, "print-parenthesis")) {
1182                                         print_parenthesis = true;
1183                                 } else if (streq(option, "print-fluffy")) {
1184                                         mode = PrintFluffy;
1185                                 } else if (streq(option, "print-caml")) {
1186                                         mode = PrintCaml;
1187                                 } else if (streq(option, "print-jna")) {
1188                                         mode = PrintJna;
1189                                 } else if (streq(option, "jna-limit")) {
1190                                         ++i;
1191                                         if (i >= argc) {
1192                                                 fprintf(stderr, "error: "
1193                                                         "expected argument after '--jna-limit'\n");
1194                                                 argument_errors = true;
1195                                                 break;
1196                                         }
1197                                         jna_limit_output(argv[i]);
1198                                 } else if (streq(option, "jna-libname")) {
1199                                         ++i;
1200                                         if (i >= argc) {
1201                                                 fprintf(stderr, "error: "
1202                                                         "expected argument after '--jna-libname'\n");
1203                                                 argument_errors = true;
1204                                                 break;
1205                                         }
1206                                         jna_set_libname(argv[i]);
1207                                 } else if (streq(option, "time")) {
1208                                         do_timing = true;
1209                                 } else if (streq(option, "version")) {
1210                                         print_cparser_version();
1211                                         return EXIT_SUCCESS;
1212                                 } else if (streq(option, "help")) {
1213                                         print_help(argv[0]);
1214                                         help_displayed = true;
1215                                 } else if (streq(option, "dump-function")) {
1216                                         ++i;
1217                                         if (i >= argc) {
1218                                                 fprintf(stderr, "error: "
1219                                                         "expected argument after '--dump-function'\n");
1220                                                 argument_errors = true;
1221                                                 break;
1222                                         }
1223                                         dumpfunction = argv[i];
1224                                         mode         = CompileDump;
1225                                 } else if (streq(option, "export-ir")) {
1226                                         mode = CompileExportIR;
1227                                 } else {
1228                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
1229                                         argument_errors = true;
1230                                 }
1231                         } else {
1232                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
1233                                 argument_errors = true;
1234                         }
1235                 } else {
1236                         filetype_t type = forced_filetype;
1237                         if (type == FILETYPE_AUTODETECT) {
1238                                 if (streq(arg, "-")) {
1239                                         /* - implicitly means C source file */
1240                                         type = FILETYPE_C;
1241                                 } else {
1242                                         const char *suffix = strrchr(arg, '.');
1243                                         /* Ensure there is at least one char before the suffix */
1244                                         if (suffix != NULL && suffix != arg) {
1245                                                 ++suffix;
1246                                                 type =
1247                                                         streq(suffix, "S")   ? FILETYPE_ASSEMBLER              :
1248                                                         streq(suffix, "a")   ? FILETYPE_OBJECT                 :
1249                                                         streq(suffix, "c")   ? FILETYPE_C                      :
1250                                                         streq(suffix, "C")   ? FILETYPE_CXX                    :
1251                                                         streq(suffix, "cc")  ? FILETYPE_CXX                    :
1252                                                         streq(suffix, "cp")  ? FILETYPE_CXX                    :
1253                                                         streq(suffix, "cpp") ? FILETYPE_CXX                    :
1254                                                         streq(suffix, "CPP") ? FILETYPE_CXX                    :
1255                                                         streq(suffix, "cxx") ? FILETYPE_CXX                    :
1256                                                         streq(suffix, "c++") ? FILETYPE_CXX                    :
1257                                                         streq(suffix, "ii")  ? FILETYPE_CXX                    :
1258                                                         streq(suffix, "h")   ? FILETYPE_C                      :
1259                                                         streq(suffix, "ir")  ? FILETYPE_IR                     :
1260                                                         streq(suffix, "o")   ? FILETYPE_OBJECT                 :
1261                                                         streq(suffix, "s")   ? FILETYPE_PREPROCESSED_ASSEMBLER :
1262                                                         streq(suffix, "so")  ? FILETYPE_OBJECT                 :
1263                                                         FILETYPE_OBJECT; /* gcc behavior: unknown file extension means object file */
1264                                         }
1265                                 }
1266                         }
1267
1268                         file_list_entry_t *entry
1269                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
1270                         memset(entry, 0, sizeof(entry[0]));
1271                         entry->name = arg;
1272                         entry->type = type;
1273
1274                         if (last_file != NULL) {
1275                                 last_file->next = entry;
1276                         } else {
1277                                 files = entry;
1278                         }
1279                         last_file = entry;
1280                 }
1281         }
1282
1283         if (help_displayed) {
1284                 return !argument_errors;
1285         }
1286
1287         if (print_file_name_file != NULL) {
1288                 print_file_name(print_file_name_file);
1289                 return EXIT_SUCCESS;
1290         }
1291         if (files == NULL) {
1292                 fprintf(stderr, "error: no input files specified\n");
1293                 argument_errors = true;
1294         }
1295
1296         if (argument_errors) {
1297                 usage(argv[0]);
1298                 return EXIT_FAILURE;
1299         }
1300
1301         /* we do the lowering in ast2firm */
1302         firm_opt.lower_bitfields = FALSE;
1303
1304         /* set the c_mode here, types depends on it */
1305         c_mode |= features_on;
1306         c_mode &= ~features_off;
1307
1308         gen_firm_init();
1309         byte_order_big_endian = be_get_backend_param()->byte_order_big_endian;
1310         init_symbol_table();
1311         init_types();
1312         init_typehash();
1313         init_basic_types();
1314         init_lexer();
1315         init_ast();
1316         init_parser();
1317         init_ast2firm();
1318         init_mangle();
1319
1320         if (do_timing)
1321                 timer_init();
1322
1323         if (construct_dep_target) {
1324                 if (outname != 0 && strlen(outname) >= 2) {
1325                         get_output_name(dep_target, sizeof(dep_target), outname, ".d");
1326                 } else {
1327                         get_output_name(dep_target, sizeof(dep_target), files->name, ".d");
1328                 }
1329         } else {
1330                 dep_target[0] = '\0';
1331         }
1332
1333         char outnamebuf[4096];
1334         if (outname == NULL) {
1335                 const char *filename = files->name;
1336
1337                 switch(mode) {
1338                 case BenchmarkParser:
1339                 case PrintAst:
1340                 case PrintFluffy:
1341                 case PrintCaml:
1342                 case PrintJna:
1343                 case LexTest:
1344                 case PreprocessOnly:
1345                 case ParseOnly:
1346                         outname = "-";
1347                         break;
1348                 case Compile:
1349                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".s");
1350                         outname = outnamebuf;
1351                         break;
1352                 case CompileAssemble:
1353                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".o");
1354                         outname = outnamebuf;
1355                         break;
1356                 case CompileDump:
1357                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
1358                                         ".vcg");
1359                         outname = outnamebuf;
1360                         break;
1361                 case CompileExportIR:
1362                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".ir");
1363                         outname = outnamebuf;
1364                         break;
1365                 case CompileAssembleLink:
1366 #ifdef _WIN32
1367                         outname = "a.exe";
1368 #else
1369                         outname = "a.out";
1370 #endif
1371                         break;
1372                 }
1373         }
1374
1375         assert(outname != NULL);
1376
1377         FILE *out;
1378         if (streq(outname, "-")) {
1379                 out = stdout;
1380         } else {
1381                 out = fopen(outname, "w");
1382                 if (out == NULL) {
1383                         fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
1384                                         strerror(errno));
1385                         return EXIT_FAILURE;
1386                 }
1387         }
1388
1389         file_list_entry_t *file;
1390         bool               already_constructed_firm = false;
1391         for (file = files; file != NULL; file = file->next) {
1392                 char        asm_tempfile[1024];
1393                 const char *filename = file->name;
1394                 filetype_t  filetype = file->type;
1395
1396                 if (filetype == FILETYPE_OBJECT)
1397                         continue;
1398
1399                 FILE *in = NULL;
1400                 if (mode == LexTest) {
1401                         if (in == NULL)
1402                                 in = open_file(filename);
1403                         lextest(in, filename);
1404                         fclose(in);
1405                         return EXIT_SUCCESS;
1406                 }
1407
1408                 FILE *preprocessed_in = NULL;
1409                 filetype_t next_filetype = filetype;
1410                 switch (filetype) {
1411                         case FILETYPE_C:
1412                                 next_filetype = FILETYPE_PREPROCESSED_C;
1413                                 goto preprocess;
1414                         case FILETYPE_CXX:
1415                                 next_filetype = FILETYPE_PREPROCESSED_CXX;
1416                                 goto preprocess;
1417                         case FILETYPE_ASSEMBLER:
1418                                 next_filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1419                                 goto preprocess;
1420 preprocess:
1421                                 /* no support for input on FILE* yet */
1422                                 if (in != NULL)
1423                                         panic("internal compiler error: in for preprocessor != NULL");
1424
1425                                 preprocessed_in = preprocess(filename, filetype);
1426                                 if (mode == PreprocessOnly) {
1427                                         copy_file(out, preprocessed_in);
1428                                         int result = pclose(preprocessed_in);
1429                                         fclose(out);
1430                                         /* remove output file in case of error */
1431                                         if (out != stdout && result != EXIT_SUCCESS) {
1432                                                 unlink(outname);
1433                                         }
1434                                         return result;
1435                                 }
1436
1437                                 in = preprocessed_in;
1438                                 filetype = next_filetype;
1439                                 break;
1440
1441                         default:
1442                                 break;
1443                 }
1444
1445                 FILE *asm_out;
1446                 if (mode == Compile) {
1447                         asm_out = out;
1448                 } else {
1449                         asm_out = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "ccs");
1450                 }
1451
1452                 if (in == NULL)
1453                         in = open_file(filename);
1454
1455                 /* preprocess and compile */
1456                 if (filetype == FILETYPE_PREPROCESSED_C) {
1457                         char const* invalid_mode;
1458                         switch (standard) {
1459                                 case STANDARD_ANSI:
1460                                 case STANDARD_C89:   c_mode = _C89;                break;
1461                                 /* TODO determine difference between these two */
1462                                 case STANDARD_C90:   c_mode = _C89;                break;
1463                                 case STANDARD_C99:   c_mode = _C89 | _C99;         break;
1464                                 case STANDARD_GNU89: c_mode = _C89 |        _GNUC; break;
1465
1466 default_c_warn:
1467                                         fprintf(stderr,
1468                                                         "warning: command line option \"-std=%s\" is not valid for C\n",
1469                                                         invalid_mode);
1470                                         /* FALLTHROUGH */
1471                                 case STANDARD_DEFAULT:
1472                                 case STANDARD_GNU99:   c_mode = _C89 | _C99 | _GNUC; break;
1473
1474                                 case STANDARD_CXX98:   invalid_mode = "c++98"; goto default_c_warn;
1475                                 case STANDARD_GNUXX98: invalid_mode = "gnu98"; goto default_c_warn;
1476                         }
1477                         goto do_parsing;
1478                 } else if (filetype == FILETYPE_PREPROCESSED_CXX) {
1479                         char const* invalid_mode;
1480                         switch (standard) {
1481                                 case STANDARD_C89:   invalid_mode = "c89";   goto default_cxx_warn;
1482                                 case STANDARD_C90:   invalid_mode = "c90";   goto default_cxx_warn;
1483                                 case STANDARD_C99:   invalid_mode = "c99";   goto default_cxx_warn;
1484                                 case STANDARD_GNU89: invalid_mode = "gnu89"; goto default_cxx_warn;
1485                                 case STANDARD_GNU99: invalid_mode = "gnu99"; goto default_cxx_warn;
1486
1487                                 case STANDARD_ANSI:
1488                                 case STANDARD_CXX98: c_mode = _CXX; break;
1489
1490 default_cxx_warn:
1491                                         fprintf(stderr,
1492                                                         "warning: command line option \"-std=%s\" is not valid for C++\n",
1493                                                         invalid_mode);
1494                                 case STANDARD_DEFAULT:
1495                                 case STANDARD_GNUXX98: c_mode = _CXX | _GNUC; break;
1496                         }
1497
1498 do_parsing:
1499                         c_mode |= features_on;
1500                         c_mode &= ~features_off;
1501
1502                         /* do the actual parsing */
1503                         ir_timer_t *t_parsing = ir_timer_new();
1504                         timer_register(t_parsing, "Frontend: Parsing");
1505                         timer_push(t_parsing);
1506                         init_tokens();
1507                         translation_unit_t *const unit = do_parsing(in, filename);
1508                         timer_pop(t_parsing);
1509
1510                         /* prints the AST even if errors occurred */
1511                         if (mode == PrintAst) {
1512                                 print_to_file(out);
1513                                 print_ast(unit);
1514                         }
1515
1516                         if (error_count > 0) {
1517                                 /* parsing failed because of errors */
1518                                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count,
1519                                         warning_count);
1520                                 result = EXIT_FAILURE;
1521                                 continue;
1522                         } else if (warning_count > 0) {
1523                                 fprintf(stderr, "%u warning(s)\n", warning_count);
1524                         }
1525
1526                         if (in == preprocessed_in) {
1527                                 int pp_result = pclose(preprocessed_in);
1528                                 if (pp_result != EXIT_SUCCESS) {
1529                                         /* remove output file */
1530                                         if (out != stdout)
1531                                                 unlink(outname);
1532                                         return EXIT_FAILURE;
1533                                 }
1534                         }
1535
1536                         if (mode == BenchmarkParser) {
1537                                 return result;
1538                         } else if (mode == PrintFluffy) {
1539                                 write_fluffy_decls(out, unit);
1540                                 continue;
1541                         } else if (mode == PrintCaml) {
1542                                 write_caml_decls(out, unit);
1543                                 continue;
1544                         } else if (mode == PrintJna) {
1545                                 write_jna_decls(out, unit);
1546                                 continue;
1547                         }
1548
1549                         /* build the firm graph */
1550                         ir_timer_t *t_construct = ir_timer_new();
1551                         timer_register(t_construct, "Frontend: Graph construction");
1552                         timer_push(t_construct);
1553                         if (already_constructed_firm) {
1554                                 panic("compiling multiple files/translation units not possible");
1555                         }
1556                         translation_unit_to_firm(unit);
1557                         already_constructed_firm = true;
1558                         timer_pop(t_construct);
1559
1560 graph_built:
1561                         if (mode == ParseOnly) {
1562                                 continue;
1563                         }
1564
1565                         if (mode == CompileDump) {
1566                                 /* find irg */
1567                                 ident    *id     = new_id_from_str(dumpfunction);
1568                                 ir_graph *irg    = NULL;
1569                                 int       n_irgs = get_irp_n_irgs();
1570                                 for (int i = 0; i < n_irgs; ++i) {
1571                                         ir_graph *tirg   = get_irp_irg(i);
1572                                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
1573                                         if (irg_id == id) {
1574                                                 irg = tirg;
1575                                                 break;
1576                                         }
1577                                 }
1578
1579                                 if (irg == NULL) {
1580                                         fprintf(stderr, "No graph for function '%s' found\n",
1581                                                 dumpfunction);
1582                                         return EXIT_FAILURE;
1583                                 }
1584
1585                                 dump_ir_graph_file(out, irg);
1586                                 fclose(out);
1587                                 return EXIT_SUCCESS;
1588                         }
1589
1590                         if (mode == CompileExportIR) {
1591                                 fclose(out);
1592                                 ir_export(outname);
1593                                 return EXIT_SUCCESS;
1594                         }
1595
1596                         gen_firm_finish(asm_out, filename, have_const_functions);
1597                         if (asm_out != out) {
1598                                 fclose(asm_out);
1599                         }
1600                 } else if (filetype == FILETYPE_IR) {
1601                         fclose(in);
1602                         ir_import(filename);
1603                         goto graph_built;
1604                 } else if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1605                         copy_file(asm_out, in);
1606                         if (in == preprocessed_in) {
1607                                 int pp_result = pclose(preprocessed_in);
1608                                 if (pp_result != EXIT_SUCCESS) {
1609                                         /* remove output in error case */
1610                                         if (out != stdout)
1611                                                 unlink(outname);
1612                                         return pp_result;
1613                                 }
1614                         }
1615                         if (asm_out != out) {
1616                                 fclose(asm_out);
1617                         }
1618                 }
1619
1620                 if (mode == Compile)
1621                         continue;
1622
1623                 /* if we're here then we have preprocessed assembly */
1624                 filename = asm_tempfile;
1625                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1626
1627                 /* assemble */
1628                 if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1629                         char        temp[1024];
1630                         const char *filename_o;
1631                         if (mode == CompileAssemble) {
1632                                 fclose(out);
1633                                 filename_o = outname;
1634                         } else {
1635                                 FILE *tempf = make_temp_file(temp, sizeof(temp), "cco");
1636                                 fclose(tempf);
1637                                 filename_o = temp;
1638                         }
1639
1640                         assemble(filename_o, filename);
1641
1642                         size_t len = strlen(filename_o) + 1;
1643                         filename = obstack_copy(&file_obst, filename_o, len);
1644                         filetype = FILETYPE_OBJECT;
1645                 }
1646
1647                 /* ok we're done here, process next file */
1648                 file->name = filename;
1649                 file->type = filetype;
1650         }
1651
1652         if (result != EXIT_SUCCESS) {
1653                 if (out != stdout)
1654                         unlink(outname);
1655                 return result;
1656         }
1657
1658         /* link program file */
1659         if (mode == CompileAssembleLink) {
1660                 obstack_1grow(&ldflags_obst, '\0');
1661                 const char *flags = obstack_finish(&ldflags_obst);
1662
1663                 /* construct commandline */
1664                 const char *linker = getenv("CPARSER_LINK");
1665                 if (linker != NULL) {
1666                         obstack_printf(&file_obst, "%s ", linker);
1667                 } else {
1668                         if (target_triple != NULL)
1669                                 obstack_printf(&file_obst, "%s-", target_triple);
1670                         obstack_printf(&file_obst, "%s ", LINKER);
1671                 }
1672
1673                 for (file_list_entry_t *entry = files; entry != NULL;
1674                                 entry = entry->next) {
1675                         if (entry->type != FILETYPE_OBJECT)
1676                                 continue;
1677
1678                         add_flag(&file_obst, "%s", entry->name);
1679                 }
1680
1681                 add_flag(&file_obst, "-o");
1682                 add_flag(&file_obst, outname);
1683                 obstack_printf(&file_obst, "%s", flags);
1684                 obstack_1grow(&file_obst, '\0');
1685
1686                 char *commandline = obstack_finish(&file_obst);
1687
1688                 if (verbose) {
1689                         puts(commandline);
1690                 }
1691                 int err = system(commandline);
1692                 if (err != EXIT_SUCCESS) {
1693                         fprintf(stderr, "linker reported an error\n");
1694                         return EXIT_FAILURE;
1695                 }
1696         }
1697
1698         if (do_timing)
1699                 timer_term(stderr);
1700
1701         obstack_free(&cppflags_obst, NULL);
1702         obstack_free(&ldflags_obst, NULL);
1703         obstack_free(&asflags_obst, NULL);
1704         obstack_free(&file_obst, NULL);
1705
1706         exit_mangle();
1707         exit_ast2firm();
1708         exit_parser();
1709         exit_ast();
1710         exit_lexer();
1711         exit_typehash();
1712         exit_types();
1713         exit_tokens();
1714         exit_symbol_table();
1715         return EXIT_SUCCESS;
1716 }