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