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