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