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