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