further fixes for MMD handling
[cparser] / main.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2008 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
54 #else
55 #include <unistd.h>
56 #define HAVE_MKSTEMP
57 #endif
58
59 #ifndef WITH_LIBCORE
60 #define WITH_LIBCORE
61 #endif
62
63 #include <libfirm/firm.h>
64 #include <libfirm/be.h>
65
66 #include "lexer.h"
67 #include "token_t.h"
68 #include "types.h"
69 #include "type_hash.h"
70 #include "parser.h"
71 #include "ast2firm.h"
72 #include "diagnostic.h"
73 #include "lang_features.h"
74 #include "driver/firm_opt.h"
75 #include "driver/firm_cmdline.h"
76 #include "adt/error.h"
77 #include "write_fluffy.h"
78 #include "write_caml.h"
79 #include "revision.h"
80 #include "warning.h"
81
82 #ifndef PREPROCESSOR
83 #define PREPROCESSOR "cpp -std=c99 -U__WCHAR_TYPE__ -D__WCHAR_TYPE__=int -U__SIZE_TYPE__ -D__SIZE_TYPE__=__SIZE_TYPE__ -m32 -U__STRICT_ANSI__"
84 #endif
85
86 #ifndef LINKER
87 #define LINKER    "gcc -m32"
88 #endif
89
90 #ifndef ASSEMBLER
91 #define ASSEMBLER "as --32"
92 #endif
93
94 /** The current c mode/dialect. */
95 unsigned int c_mode = _C89|_C99|_GNUC;
96
97 /** The 'machine size', 16, 32 or 64 bit, 32bit is the default. */
98 unsigned int machine_size = 32;
99
100 /** true if the char type is signed. */
101 bool char_is_signed = true;
102
103 /** true for strict language checking. */
104 bool strict_mode = false;
105
106 /** use builtins for some libc functions */
107 bool use_builtins = false;
108
109 /* to switch on printing of implicit casts */
110 extern bool print_implicit_casts;
111
112 /* to switch on printing of parenthesis to indicate operator precedence */
113 extern bool print_parenthesis;
114
115 static int             verbose;
116 static struct obstack  cppflags_obst, ldflags_obst;
117 static char            dep_target[1024];
118 static const char     *outname;
119
120 typedef struct file_list_entry_t file_list_entry_t;
121
122 typedef enum filetype_t {
123         FILETYPE_AUTODETECT,
124         FILETYPE_C,
125         FILETYPE_PREPROCESSED_C,
126         FILETYPE_ASSEMBLER,
127         FILETYPE_PREPROCESSED_ASSEMBLER,
128         FILETYPE_OBJECT,
129         FILETYPE_UNKNOWN
130 } filetype_t;
131
132 struct file_list_entry_t {
133         const char        *name; /**< filename or NULL for stdin */
134         filetype_t         type;
135         file_list_entry_t *next;
136 };
137
138 #if defined(_DEBUG) || defined(FIRM_DEBUG)
139 /**
140  * Debug printf implementation.
141  *
142  * @param fmt  printf style format parameter
143  */
144 void dbg_printf(const char *fmt, ...)
145 {
146         va_list list;
147
148         if (firm_dump.debug_print) {
149                 va_start(list, fmt);
150                 vprintf(fmt, list);
151                 va_end(list);
152         }  /* if */
153 }
154 #endif /* defined(_DEBUG) || defined(FIRM_DEBUG) */
155
156 static void initialize_firm(void)
157 {
158         firm_early_init();
159
160         dump_consts_local(1);
161         dump_keepalive_edges(1);
162 }
163
164 static void get_output_name(char *buf, size_t buflen, const char *inputname,
165                             const char *newext)
166 {
167         size_t last_dot = 0xffffffff;
168         size_t i = 0;
169
170         if(inputname == NULL) {
171                 snprintf(buf, buflen, "a%s", newext);
172                 return;
173         }
174
175         for(const char *c = inputname; *c != 0; ++c) {
176                 if(*c == '.')
177                         last_dot = i;
178                 ++i;
179         }
180         if(last_dot == 0xffffffff)
181                 last_dot = i;
182
183         if(last_dot >= buflen)
184                 panic("filename too long");
185         memcpy(buf, inputname, last_dot);
186
187         size_t extlen = strlen(newext) + 1;
188         if(extlen + last_dot >= buflen)
189                 panic("filename too long");
190         memcpy(buf+last_dot, newext, extlen);
191 }
192
193 #include "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                 puts("");
219         } while(lexer_token.type != T_EOF);
220 }
221
222 static void add_flag(struct obstack *obst, const char *format, ...)
223 {
224         va_list ap;
225         va_start(ap, format);
226
227         char buf[4096];
228         vsnprintf(buf, sizeof(buf), format, ap);
229
230         /* escape stuff... */
231         obstack_1grow(obst, ' ');
232         for (char *c = buf; *c != '\0'; ++c) {
233                 switch(*c) {
234                 case '"':
235                 case '\'':
236                 case '`':
237                 case ' ':
238                 case '\t':
239                 case '\n':
240                 case '\r':
241                 case '\\':
242                 case '$':
243                 case '(':
244                 case ')':
245                         obstack_1grow(obst, '\\');
246                         /* fallthrough */
247                 default:
248                         obstack_1grow(obst, *c);
249                         break;
250                 }
251         }
252
253         va_end(ap);
254 }
255
256 static FILE *preprocess(const char *fname)
257 {
258         obstack_1grow(&cppflags_obst, '\0');
259         const char *flags = obstack_finish(&cppflags_obst);
260
261         obstack_printf(&cppflags_obst, "%s", PREPROCESSOR);
262         if (dep_target[0] != '\0') {
263                 add_flag(&cppflags_obst, "-MF");
264                 add_flag(&cppflags_obst, "%s", dep_target);
265                 if (outname != NULL) {
266                                 add_flag(&cppflags_obst, "-MQ");
267                                 add_flag(&cppflags_obst, "%s", outname);
268                 }
269         }
270         if (flags[0] != '\0') {
271                 obstack_printf(&cppflags_obst, " %s", flags);
272         }
273         add_flag(&cppflags_obst, "%s", fname);
274
275         obstack_1grow(&cppflags_obst, '\0');
276         const char *buf = obstack_finish(&cppflags_obst);
277         if(verbose) {
278                 puts(buf);
279         }
280
281         FILE *f = popen(buf, "r");
282         if(f == NULL) {
283                 fprintf(stderr, "invoking preprocessor failed\n");
284                 exit(1);
285         }
286
287         return f;
288 }
289
290 static void assemble(const char *out, const char *in)
291 {
292         char buf[4096];
293
294         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
295         if(verbose) {
296                 puts(buf);
297         }
298
299         int err = system(buf);
300         if(err != 0) {
301                 fprintf(stderr, "assembler reported an error\n");
302                 exit(1);
303         }
304 }
305
306 static const char *try_dir(const char *dir)
307 {
308         if(dir == NULL)
309                 return dir;
310         if(access(dir, R_OK | W_OK | X_OK) == 0)
311                 return dir;
312         return NULL;
313 }
314
315 static const char *get_tempdir(void)
316 {
317         static const char *tmpdir = NULL;
318
319         if(tmpdir != NULL)
320                 return tmpdir;
321
322         if(tmpdir == NULL)
323                 tmpdir = try_dir(getenv("TMPDIR"));
324         if(tmpdir == NULL)
325                 tmpdir = try_dir(getenv("TMP"));
326         if(tmpdir == NULL)
327                 tmpdir = try_dir(getenv("TEMP"));
328
329 #ifdef P_tmpdir
330         if(tmpdir == NULL)
331                 tmpdir = try_dir(P_tmpdir);
332 #endif
333
334         if(tmpdir == NULL)
335                 tmpdir = try_dir("/var/tmp");
336         if(tmpdir == NULL)
337                 tmpdir = try_dir("/usr/tmp");
338         if(tmpdir == NULL)
339                 tmpdir = try_dir("/tmp");
340
341         if(tmpdir == NULL)
342                 tmpdir = ".";
343
344         return tmpdir;
345 }
346
347 #ifndef HAVE_MKSTEMP
348 /* cheap and nasty mkstemp replacement */
349 static int mkstemp(char *templ)
350 {
351         mktemp(templ);
352         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
353 }
354 #endif
355
356 /**
357  * an own version of tmpnam, which: writes in a buffer, emits no warnings
358  * during linking (like glibc/gnu ld do for tmpnam)...
359  */
360 static FILE *make_temp_file(char *buffer, size_t buflen, const char *prefix)
361 {
362         const char *tempdir = get_tempdir();
363
364         snprintf(buffer, buflen, "%s/%sXXXXXX", tempdir, prefix);
365
366         int fd = mkstemp(buffer);
367         if(fd == -1) {
368                 fprintf(stderr, "couldn't create temporary file: %s\n",
369                         strerror(errno));
370                 exit(1);
371         }
372         FILE *out = fdopen(fd, "w");
373         if(out == NULL) {
374                 fprintf(stderr, "couldn't create temporary file FILE*\n");
375                 exit(1);
376         }
377
378         return out;
379 }
380
381 /**
382  * Do the necessary lowering for compound parameters.
383  */
384 void lower_compound_params(void)
385 {
386         lower_params_t params;
387
388         params.def_ptr_alignment    = 4;
389         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
390         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
391         params.find_pointer_type    = NULL;
392         params.ret_compound_in_regs = NULL;
393         lower_calls_with_compounds(&params);
394 }
395
396 typedef enum compile_mode_t {
397         BenchmarkParser,
398         PreprocessOnly,
399         ParseOnly,
400         Compile,
401         CompileDump,
402         CompileAssemble,
403         CompileAssembleLink,
404         LexTest,
405         PrintAst,
406         PrintFluffy,
407         PrintCaml
408 } compile_mode_t;
409
410 static void usage(const char *argv0)
411 {
412         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
413 }
414
415 static void print_cparser_version(void) {
416         firm_version_t ver;
417         firm_get_version(&ver);
418
419         printf("cparser (%s) using libFirm (%u.%u",
420                 cparser_REVISION, ver.major, ver.minor);
421         if(ver.revision[0] != 0) {
422                 putchar(' ');
423                 fputs(ver.revision, stdout);
424         }
425         if(ver.build[0] != 0) {
426                 putchar(' ');
427                 fputs(ver.build, stdout);
428         }
429         puts(")\n");
430 }
431
432 static void set_be_option(const char *arg)
433 {
434         int res = firm_be_option(arg);
435         (void) res;
436         assert(res);
437 }
438
439 static void set_option(const char *arg)
440 {
441         int res = firm_option(arg);
442         (void) res;
443         assert(res);
444 }
445
446 static void copy_file(FILE *dest, FILE *input)
447 {
448         char buf[16384];
449
450         while (!feof(input) && !ferror(dest)) {
451                 size_t read = fread(buf, 1, sizeof(buf), input);
452                 if(fwrite(buf, 1, read, dest) != read) {
453                         perror("couldn't write output");
454                 }
455         }
456 }
457
458 static inline bool streq(char const* a, char const* b)
459 {
460         return strcmp(a, b) == 0;
461 }
462
463 static inline bool strstart(char const* str, char const* start)
464 {
465         do {
466                 if (*start == '\0')
467                         return true;
468         } while (*str++ == *start++);
469         return false;
470 }
471
472 static FILE *open_file(const char *filename)
473 {
474         if (streq(filename, "-")) {
475                 return stdin;
476         }
477
478         FILE *in = fopen(filename, "r");
479         if(in == NULL) {
480                 fprintf(stderr, "Couldn't open '%s': %s\n", filename,
481                                 strerror(errno));
482                 exit(1);
483         }
484
485         return in;
486 }
487
488 static filetype_t get_filetype_from_string(const char *string)
489 {
490         if (streq(string, "c") || streq(string, "c-header"))
491                 return FILETYPE_C;
492         if (streq(string, "assembler"))
493                 return FILETYPE_PREPROCESSED_ASSEMBLER;
494         if (streq(string, "assembler-with-cpp"))
495                 return FILETYPE_ASSEMBLER;
496         if (streq(string, "none"))
497                 return FILETYPE_AUTODETECT;
498
499         return FILETYPE_UNKNOWN;
500 }
501
502 int main(int argc, char **argv)
503 {
504         initialize_firm();
505
506         const char        *dumpfunction         = NULL;
507         compile_mode_t     mode                 = CompileAssembleLink;
508         int                opt_level            = 1;
509         int                result               = EXIT_SUCCESS;
510         char               cpu_arch[16]         = "ia32";
511         file_list_entry_t *files                = NULL;
512         file_list_entry_t *last_file            = NULL;
513         bool               construct_dep_target = false;
514         struct obstack     file_obst;
515
516         obstack_init(&cppflags_obst);
517         obstack_init(&ldflags_obst);
518         obstack_init(&file_obst);
519
520 #define GET_ARG_AFTER(def, args)                                             \
521         def = &arg[sizeof(args)-1];                                              \
522         if(def[0] == '\0') {                                                     \
523                 ++i;                                                                 \
524                 if(i >= argc) {                                                      \
525                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
526                         argument_errors = true;                                          \
527                         break;                                                           \
528                 }                                                                    \
529                 def = argv[i];                                                       \
530                 if(def[0] == '-' && def[1] != '\0') {                                \
531                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
532                         argument_errors = true;                                          \
533                         continue;                                                        \
534                 }                                                                    \
535         }
536
537 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
538
539         /* early options parsing (find out optimisation level) */
540         for(int i = 1; i < argc; ++i) {
541                 const char *arg = argv[i];
542                 if(arg[0] != '-')
543                         continue;
544
545                 const char *option = &arg[1];
546                 if(option[0] == 'O') {
547                         sscanf(&option[1], "%d", &opt_level);
548                 }
549         }
550
551         /* apply optimisation level */
552         switch(opt_level) {
553         case 0:
554                 set_option("no-opt");
555                 break;
556         case 1:
557                 set_option("no-inline");
558                 break;
559         default:
560         case 4:
561                 set_option("strict-aliasing");
562                 /* fallthrough */
563         case 3:
564                 set_option("cond-eval");
565                 set_option("if-conv");
566                 use_builtins = true;
567                 /* fallthrough */
568         case 2:
569                 set_option("inline");
570                 set_option("deconv");
571                 set_be_option("omitfp");
572                 break;
573         }
574
575         /* parse rest of options */
576         filetype_t  forced_filetype = FILETYPE_AUTODETECT;
577         bool        help_displayed  = false;
578         bool        argument_errors = false;
579         for(int i = 1; i < argc; ++i) {
580                 const char *arg = argv[i];
581                 if(arg[0] == '-' && arg[1] != 0) {
582                         /* an option */
583                         const char *option = &arg[1];
584                         if(option[0] == 'o') {
585                                 GET_ARG_AFTER(outname, "-o");
586                         } else if(option[0] == 'g') {
587                                 set_be_option("debuginfo=stabs");
588                                 set_be_option("omitfp=no");
589                                 set_be_option("ia32-nooptcc=yes");
590                         } else if(SINGLE_OPTION('c')) {
591                                 mode = CompileAssemble;
592                         } else if(SINGLE_OPTION('E')) {
593                                 mode = PreprocessOnly;
594                         } else if(SINGLE_OPTION('S')) {
595                                 mode = Compile;
596                         } else if(option[0] == 'O') {
597                                 continue;
598                         } else if(option[0] == 'I') {
599                                 const char *opt;
600                                 GET_ARG_AFTER(opt, "-I");
601                                 add_flag(&cppflags_obst, "-I%s", opt);
602                         } else if(option[0] == 'D') {
603                                 const char *opt;
604                                 GET_ARG_AFTER(opt, "-D");
605                                 add_flag(&cppflags_obst, "-D%s", opt);
606                         } else if(option[0] == 'U') {
607                                 const char *opt;
608                                 GET_ARG_AFTER(opt, "-U");
609                                 add_flag(&cppflags_obst, "-U%s", opt);
610                         } else if(option[0] == 'l') {
611                                 const char *opt;
612                                 GET_ARG_AFTER(opt, "-l");
613                                 add_flag(&ldflags_obst, "-l%s", opt);
614                         } else if(option[0] == 'L') {
615                                 const char *opt;
616                                 GET_ARG_AFTER(opt, "-L");
617                                 add_flag(&ldflags_obst, "-L%s", opt);
618                         } else if(SINGLE_OPTION('v')) {
619                                 verbose = 1;
620                         } else if(SINGLE_OPTION('w')) {
621                                 inhibit_all_warnings = true;
622                         } else if(option[0] == 'x') {
623                                 const char *opt;
624                                 GET_ARG_AFTER(opt, "-x");
625                                 forced_filetype = get_filetype_from_string(opt);
626                                 if (forced_filetype == FILETYPE_UNKNOWN) {
627                                         fprintf(stderr, "Unknown language '%s'\n", opt);
628                                         argument_errors = true;
629                                 }
630                         } else if (streq(option, "M")) {
631                                 mode = PreprocessOnly;
632                                 add_flag(&cppflags_obst, "-M");
633                         } else if (streq(option, "MMD") ||
634                                    streq(option, "MD")) {
635                             construct_dep_target = true;
636                                 add_flag(&cppflags_obst, "-%s", option);
637                         } else if(streq(option, "MM")  ||
638                                    streq(option, "MP")) {
639                                 add_flag(&cppflags_obst, "-%s", option);
640                         } else if (streq(option, "MT") ||
641                                    streq(option, "MQ") ||
642                                    streq(option, "MF")) {
643                                 const char *opt;
644                                 GET_ARG_AFTER(opt, "-MT");
645                                 add_flag(&cppflags_obst, "-%s", option);
646                                 add_flag(&cppflags_obst, "%s", opt);
647                         } else if (streq(option, "pipe")) {
648                                 /* here for gcc compatibility */
649                         } else if (option[0] == 'f') {
650                                 char const *orig_opt;
651                                 GET_ARG_AFTER(orig_opt, "-f");
652
653                                 if (strstart(orig_opt, "align-loops=") ||
654                                     strstart(orig_opt, "align-jumps=") ||
655                                     strstart(orig_opt, "align-functions=")) {
656                                         fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
657                                 } else {
658                                         char const *opt         = orig_opt;
659                                         bool        truth_value = true;
660                                         if (opt[0] == 'n' && opt[1] == 'o' && opt[2] == '-') {
661                                                 truth_value = false;
662                                                 opt += 3;
663                                         }
664
665                                         if (streq(opt, "dollars-in-identifiers")) {
666                                                 allow_dollar_in_symbol = truth_value;
667                                         } else if (streq(opt, "short-wchar")) {
668                                                 opt_short_wchar_t = truth_value;
669                                         } else if (streq(opt, "syntax-only")) {
670                                                 mode = truth_value ? ParseOnly : CompileAssembleLink;
671                                         } else if (streq(opt, "omit-frame-pointer")) {
672                                                 set_be_option(truth_value ? "omitfp" : "omitfp=no");
673                                         } else if (streq(opt, "strength-reduce")) {
674                                                 firm_option(truth_value ? "strength-red" : "no-strength-red");
675                                         } else if (streq(opt, "fast-math")               ||
676                                                    streq(opt, "jump-tables")             ||
677                                                    streq(opt, "unroll-loops")            ||
678                                                    streq(opt, "expensive-optimizations") ||
679                                                    streq(opt, "common")                  ||
680                                                    streq(opt, "PIC")                     ||
681                                                    streq(opt, "align-loops")             ||
682                                                    streq(opt, "align-jumps")             ||
683                                                    streq(opt, "align-functions")) {
684                                                 fprintf(stderr, "ignoring gcc option '-f%s'\n", orig_opt);
685                                         } else {
686                                                 int res = firm_option(orig_opt);
687                                                 if (res == 0) {
688                                                         fprintf(stderr, "error: unknown Firm option '-f%s'\n",
689                                                                 orig_opt);
690                                                         argument_errors = true;
691                                                         continue;
692                                                 } else if (res == -1) {
693                                                         help_displayed = true;
694                                                 }
695                                         }
696                                 }
697                         } else if (option[0] == 'b') {
698                                 const char *opt;
699                                 GET_ARG_AFTER(opt, "-b");
700                                 int res = firm_be_option(opt);
701                                 if (res == 0) {
702                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
703                                                 opt);
704                                         argument_errors = true;
705                                 } else if (res == -1) {
706                                         help_displayed = true;
707                                 } else if (strstart(opt, "isa=")) {
708                                         strncpy(cpu_arch, opt, sizeof(cpu_arch));
709                                 }
710                         } else if (option[0] == 'W') {
711                                 if (strstart(option + 1, "l,")) // a gcc-style linker option
712                                 {
713                                         const char *opt;
714                                         GET_ARG_AFTER(opt, "-Wl,");
715                                         add_flag(&ldflags_obst, "-Wl,%s", opt);
716                                 }
717                                 else set_warning_opt(&option[1]);
718                         } else if(option[0] == 'm') {
719                                 /* -m options */
720                                 const char *opt;
721                                 char arch_opt[64];
722
723                                 GET_ARG_AFTER(opt, "-m");
724                                 if (strstart(opt, "arch=")) {
725                                         GET_ARG_AFTER(opt, "-march=");
726                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
727                                         int res = firm_be_option(arch_opt);
728                                         if (res == 0)
729                                                 argument_errors = true;
730                                         else {
731                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
732                                                 int res = firm_be_option(arch_opt);
733                                                 if (res == 0)
734                                                         argument_errors = true;
735                                         }
736                                 } else if (strstart(opt, "tune=")) {
737                                         GET_ARG_AFTER(opt, "-mtune=");
738                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
739                                         int res = firm_be_option(arch_opt);
740                                         if (res == 0)
741                                                 argument_errors = true;
742                                 } else if (strstart(opt, "cpu=")) {
743                                         GET_ARG_AFTER(opt, "-mcpu=");
744                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
745                                         int res = firm_be_option(arch_opt);
746                                         if (res == 0)
747                                                 argument_errors = true;
748                                 } else if (strstart(opt, "fpmath=")) {
749                                         GET_ARG_AFTER(opt, "-mfpmath=");
750                                         if (streq(opt, "387"))
751                                                 opt = "x87";
752                                         else if (streq(opt, "sse"))
753                                                 opt = "sse2";
754                                         else {
755                                                 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
756                                                 argument_errors = true;
757                                         }
758                                         if(!argument_errors) {
759                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
760                                                 int res = firm_be_option(arch_opt);
761                                                 if (res == 0)
762                                                         argument_errors = true;
763                                         }
764                                 } else if (strstart(opt, "preferred-stack-boundary=")) {
765                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
766                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
767                                         int res = firm_be_option(arch_opt);
768                                         if (res == 0)
769                                                 argument_errors = true;
770                                 } else if (streq(opt, "omit-leaf-frame-pointer")) {
771                                         set_be_option("omitleaffp=1");
772                                 } else if (streq(opt, "no-omit-leaf-frame-pointer")) {
773                                         set_be_option("omitleaffp=0");
774                                 } else {
775                                         char *endptr;
776                                         long int value = strtol(opt, &endptr, 10);
777                                         if (*endptr != '\0') {
778                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
779                                                 argument_errors = true;
780                                         }
781                                         if (value != 16 && value != 32 && value != 64) {
782                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
783                                                 argument_errors = true;
784                                         } else {
785                                                 machine_size = (unsigned int)value;
786                                         }
787                                 }
788                         } else if (streq(option, "pg")) {
789                                 set_be_option("gprof");
790                                 add_flag(&ldflags_obst, "-pg");
791                         } else if (streq(option, "pedantic") ||
792                                    streq(option, "ansi")) {
793                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
794                         } else if (streq(option, "shared")) {
795                                 add_flag(&ldflags_obst, "-shared");
796                         } else if (strstart(option, "std=")) {
797                                 if (streq(&option[4], "c99")) {
798                                         c_mode = _C89|_C99;
799                                 } else if (streq(&option[4], "c89")) {
800                                         c_mode = _C89;
801                                 } else if (streq(&option[4], "gnu99")) {
802                                         c_mode = _C89|_C99|_GNUC;
803                                 } else if (streq(&option[4], "microsoft")) {
804                                         c_mode = _C89|_C99|_MS;
805                                 } else
806                                         fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
807                         } else if (streq(option, "version")) {
808                                 print_cparser_version();
809                         } else if (option[0] == '-') {
810                                 /* double dash option */
811                                 ++option;
812                                 if (streq(option, "gcc")) {
813                                         c_mode |= _GNUC;
814                                 } else if (streq(option, "no-gcc")) {
815                                         c_mode &= ~_GNUC;
816                                 } else if (streq(option, "ms")) {
817                                         c_mode |= _MS;
818                                 } else if (streq(option, "no-ms")) {
819                                         c_mode &= ~_MS;
820                                 } else if (streq(option, "signed-chars")) {
821                                         char_is_signed = true;
822                                 } else if (streq(option, "unsigned-chars")) {
823                                         char_is_signed = false;
824                                 } else if (streq(option, "strict")) {
825                                         strict_mode = true;
826                                 } else if (streq(option, "lextest")) {
827                                         mode = LexTest;
828                                 } else if (streq(option, "benchmark")) {
829                                         mode = BenchmarkParser;
830                                 } else if (streq(option, "print-ast")) {
831                                         mode = PrintAst;
832                                 } else if (streq(option, "print-implicit-cast")) {
833                                         print_implicit_casts = true;
834                                 } else if (streq(option, "print-parenthesis")) {
835                                         print_parenthesis = true;
836                                 } else if (streq(option, "print-fluffy")) {
837                                         mode = PrintFluffy;
838                                 } else if (streq(option, "print-caml")) {
839                                         mode = PrintCaml;
840                                 } else if (streq(option, "version")) {
841                                         print_cparser_version();
842                                         exit(EXIT_SUCCESS);
843                                 } else if (streq(option, "dump-function")) {
844                                         ++i;
845                                         if(i >= argc) {
846                                                 fprintf(stderr, "error: "
847                                                         "expected argument after '--dump-function'\n");
848                                                 argument_errors = true;
849                                                 break;
850                                         }
851                                         dumpfunction = argv[i];
852                                         mode         = CompileDump;
853                                 } else {
854                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
855                                         argument_errors = true;
856                                 }
857                         } else {
858                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
859                                 argument_errors = true;
860                         }
861                 } else {
862                         filetype_t  type     = forced_filetype;
863                         const char *filename = arg;
864                         if (type == FILETYPE_AUTODETECT) {
865                                 size_t const len = strlen(arg);
866                                 if (len < 2 && arg[0] == '-') {
867                                         /* - implicitly means C source file */
868                                         type     = FILETYPE_C;
869                                         filename = NULL;
870                                 } else if (len > 2 && arg[len - 2] == '.') {
871                                         switch (arg[len - 1]) {
872                                         case 'c': type = FILETYPE_C;                      break;
873                                         case 'h': type = FILETYPE_C;                      break;
874                                         case 's': type = FILETYPE_PREPROCESSED_ASSEMBLER; break;
875                                         case 'S': type = FILETYPE_ASSEMBLER;              break;
876
877                                         case 'a':
878                                         case 'o': type = FILETYPE_OBJECT;                 break;
879                                         }
880                                 } else if (len > 3 && arg[len - 3] == '.') {
881                                         if (streq(arg + len - 2, "so")) {
882                                                 type = FILETYPE_OBJECT;
883                                         }
884                                 }
885
886                                 if (type == FILETYPE_AUTODETECT) {
887                                         fprintf(stderr, "'%s': file format not recognized\n", arg);
888                                         continue;
889                                 }
890                         }
891
892                         file_list_entry_t *entry
893                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
894                         memset(entry, 0, sizeof(entry[0]));
895                         entry->name = arg;
896                         entry->type = type;
897
898                         if (last_file != NULL) {
899                                 last_file->next = entry;
900                         } else {
901                                 files = entry;
902                         }
903                         last_file = entry;
904                 }
905         }
906
907         if (files == NULL) {
908                 fprintf(stderr, "error: no input files specified\n");
909                 argument_errors = true;
910         }
911
912         if (help_displayed) {
913                 return !argument_errors;
914         }
915         if (argument_errors) {
916                 usage(argv[0]);
917                 return 1;
918         }
919
920         /* we do the lowering in ast2firm */
921         firm_opt.lower_bitfields = FALSE;
922
923         gen_firm_init();
924         init_symbol_table();
925         init_tokens();
926         init_types();
927         init_typehash();
928         init_basic_types();
929         init_lexer();
930         init_ast();
931         init_parser();
932         init_ast2firm();
933
934         if (construct_dep_target) {
935                 if (outname != 0 && strlen(outname) >= 2) {
936                         get_output_name(dep_target, sizeof(dep_target), outname, ".d");
937                 } else {
938                         get_output_name(dep_target, sizeof(dep_target), files->name, ".d");
939                 }
940         } else {
941                 dep_target[0] = '\0';
942         }
943
944         char outnamebuf[4096];
945         if (outname == NULL) {
946                 const char *filename = files->name;
947
948                 switch(mode) {
949                 case BenchmarkParser:
950                 case PrintAst:
951                 case PrintFluffy:
952                 case PrintCaml:
953                 case LexTest:
954                 case PreprocessOnly:
955                         outname = "-";
956                         break;
957                 case ParseOnly:
958                         break;
959                 case Compile:
960                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".s");
961                         outname = outnamebuf;
962                         break;
963                 case CompileAssemble:
964                         get_output_name(outnamebuf, sizeof(outnamebuf), filename, ".o");
965                         outname = outnamebuf;
966                         break;
967                 case CompileDump:
968                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
969                                         ".vcg");
970                         outname = outnamebuf;
971                         break;
972                 case CompileAssembleLink:
973 #ifdef _WIN32
974                         outname = "a.exe";
975 #else
976                         outname = "a.out";
977 #endif
978                         break;
979                 }
980         }
981
982         assert(outname != NULL);
983
984         FILE *out;
985         if (streq(outname, "-")) {
986                 out = stdout;
987         } else {
988                 out = fopen(outname, "w");
989                 if(out == NULL) {
990                         fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
991                                         strerror(errno));
992                         return 1;
993                 }
994         }
995
996         file_list_entry_t *file;
997         for (file = files; file != NULL; file = file->next) {
998                 char        asm_tempfile[1024];
999                 const char *filename = file->name;
1000                 filetype_t  filetype = file->type;
1001
1002                 if (file->type == FILETYPE_OBJECT)
1003                         continue;
1004
1005                 FILE *in = NULL;
1006                 if (mode == LexTest) {
1007                         if (in == NULL)
1008                                 in = open_file(filename);
1009                         lextest(in, filename);
1010                         fclose(in);
1011                         exit(EXIT_SUCCESS);
1012                 }
1013
1014                 FILE *preprocessed_in = NULL;
1015                 if (filetype == FILETYPE_C || filetype == FILETYPE_ASSEMBLER) {
1016                         /* no support for input on FILE* yet */
1017                         if (in != NULL)
1018                                 panic("internal compiler error: in for preprocessor != NULL");
1019
1020                         preprocessed_in = preprocess(filename);
1021                         if (mode == PreprocessOnly) {
1022                                 copy_file(out, preprocessed_in);
1023                                 int result = pclose(preprocessed_in);
1024                                 fclose(out);
1025                                 return result;
1026                         }
1027
1028                         if (filetype == FILETYPE_C) {
1029                                 filetype = FILETYPE_PREPROCESSED_C;
1030                         } else if (filetype == FILETYPE_ASSEMBLER) {
1031                                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1032                         } else {
1033                                 panic("internal compiler error: unknown filetype at preproc");
1034                         }
1035
1036                         in = preprocessed_in;
1037                 }
1038
1039                 FILE *asm_out;
1040                 if(mode == Compile) {
1041                         asm_out = out;
1042                 } else {
1043                         asm_out = make_temp_file(asm_tempfile, sizeof(asm_tempfile),
1044                                                  "ccs");
1045                 }
1046
1047                 if (in == NULL)
1048                         in = open_file(filename);
1049
1050                 /* preprocess and compile */
1051                 if (filetype == FILETYPE_PREPROCESSED_C) {
1052                         translation_unit_t *const unit = do_parsing(in, filename);
1053                         if (in == preprocessed_in) {
1054                                 int pp_result = pclose(preprocessed_in);
1055                                 if (pp_result != EXIT_SUCCESS) {
1056                                         exit(EXIT_FAILURE);
1057                                 }
1058                         }
1059
1060                         /* prints the AST even if errors occurred */
1061                         if (mode == PrintAst) {
1062                                 type_set_output(out);
1063                                 ast_set_output(out);
1064                                 print_ast(unit);
1065                         }
1066
1067                         if(error_count > 0) {
1068                                 /* parsing failed because of errors */
1069                                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count,
1070                                         warning_count);
1071                                 result = EXIT_FAILURE;
1072                                 continue;
1073                         } else if(warning_count > 0) {
1074                                 fprintf(stderr, "%u warning(s)\n", warning_count);
1075                         }
1076
1077                         if(mode == BenchmarkParser) {
1078                                 return result;
1079                         } else if(mode == PrintFluffy) {
1080                                 write_fluffy_decls(out, unit);
1081                                 continue;
1082                         } else if (mode == PrintCaml) {
1083                                 write_caml_decls(out, unit);
1084                                 continue;
1085                         }
1086
1087                         translation_unit_to_firm(unit);
1088
1089                         if (mode == ParseOnly) {
1090                                 continue;
1091                         }
1092
1093                         if (mode == CompileDump) {
1094                                 /* find irg */
1095                                 ident    *id     = new_id_from_str(dumpfunction);
1096                                 ir_graph *irg    = NULL;
1097                                 int       n_irgs = get_irp_n_irgs();
1098                                 for(int i = 0; i < n_irgs; ++i) {
1099                                         ir_graph *tirg   = get_irp_irg(i);
1100                                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
1101                                         if(irg_id == id) {
1102                                                 irg = tirg;
1103                                                 break;
1104                                         }
1105                                 }
1106
1107                                 if(irg == NULL) {
1108                                         fprintf(stderr, "No graph for function '%s' found\n",
1109                                                 dumpfunction);
1110                                         exit(1);
1111                                 }
1112
1113                                 dump_ir_block_graph_file(irg, out);
1114                                 fclose(out);
1115                                 exit(0);
1116                         }
1117
1118                         gen_firm_finish(asm_out, filename, /*c_mode=*/1,
1119                                         /*firm_const_exists=*/0);
1120                         if (asm_out != out) {
1121                                 fclose(asm_out);
1122                         }
1123
1124                 } else if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1125                         copy_file(asm_out, in);
1126                         if (in == preprocessed_in) {
1127                                 int pp_result = pclose(preprocessed_in);
1128                                 if (pp_result != EXIT_SUCCESS) {
1129                                         return pp_result;
1130                                 }
1131                         }
1132                         if(asm_out != out) {
1133                                 fclose(asm_out);
1134                         }
1135                 }
1136
1137                 if (mode == Compile)
1138                         continue;
1139
1140                 /* if we're here then we have preprocessed assembly */
1141                 filename = asm_tempfile;
1142                 filetype = FILETYPE_PREPROCESSED_ASSEMBLER;
1143
1144                 /* assemble */
1145                 if (filetype == FILETYPE_PREPROCESSED_ASSEMBLER) {
1146                         char        temp[1024];
1147                         const char *filename_o;
1148                         if(mode == CompileAssemble) {
1149                                 fclose(out);
1150                                 filename_o = outname;
1151                         } else {
1152                                 FILE *tempf = make_temp_file(temp, sizeof(temp), "cco");
1153                                 fclose(tempf);
1154                                 filename_o = temp;
1155                         }
1156
1157                         assemble(filename_o, filename);
1158
1159                         size_t len = strlen(filename_o) + 1;
1160                         filename = obstack_copy(&file_obst, filename_o, len);
1161                         filetype = FILETYPE_OBJECT;
1162                 }
1163
1164                 /* ok we're done here, process next file */
1165                 file->name = filename;
1166                 file->type = filetype;
1167         }
1168
1169         if (result != EXIT_SUCCESS)
1170                 return result;
1171
1172         /* link program file */
1173         if(mode == CompileAssembleLink) {
1174                 obstack_1grow(&ldflags_obst, '\0');
1175                 const char *flags = obstack_finish(&ldflags_obst);
1176
1177                 /* construct commandline */
1178                 obstack_printf(&file_obst, "%s", LINKER);
1179                 for (file_list_entry_t *entry = files; entry != NULL;
1180                                 entry = entry->next) {
1181                         if (entry->type != FILETYPE_OBJECT)
1182                                 continue;
1183
1184                         add_flag(&file_obst, "%s", entry->name);
1185                 }
1186
1187                 add_flag(&file_obst, "-o");
1188                 add_flag(&file_obst, outname);
1189                 obstack_printf(&file_obst, "%s", flags);
1190                 obstack_1grow(&file_obst, '\0');
1191
1192                 char *commandline = obstack_finish(&file_obst);
1193
1194                 if(verbose) {
1195                         puts(commandline);
1196                 }
1197                 int err = system(commandline);
1198                 if(err != EXIT_SUCCESS) {
1199                         fprintf(stderr, "linker reported an error\n");
1200                         exit(1);
1201                 }
1202         }
1203
1204         obstack_free(&cppflags_obst, NULL);
1205         obstack_free(&ldflags_obst, NULL);
1206         obstack_free(&file_obst, NULL);
1207
1208         exit_ast2firm();
1209         exit_parser();
1210         exit_ast();
1211         exit_lexer();
1212         exit_typehash();
1213         exit_types();
1214         exit_tokens();
1215         exit_symbol_table();
1216         return 0;
1217 }