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