Added support for (one) .s/.S input file
[cparser] / main.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18  * 02111-1307, USA.
19  */
20 #include <config.h>
21
22 #define _GNU_SOURCE
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <stdbool.h>
27 #include <errno.h>
28 #include <string.h>
29 #include <assert.h>
30
31 #ifdef _WIN32
32
33 #include <fcntl.h>
34 #include <io.h>
35
36 /* no eXecute on Win32 */
37 #define X_OK 0
38 #define W_OK 2
39 #define R_OK 4
40
41 #define O_RDWR          _O_RDWR
42 #define O_CREAT         _O_CREAT
43 #define O_EXCL          _O_EXCL
44 #define O_BINARY        _O_BINARY
45
46 /* remap some names, we are not in the POSIX world */
47 #define access(fname, mode)      _access(fname, mode)
48 #define mktemp(tmpl)             _mktemp(tmpl)
49 #define open(fname, oflag, mode) _open(fname, oflag, mode)
50 #define fdopen(fd, mode)         _fdopen(fd, mode)
51 #define popen(cmd, mode)         _popen(cmd, mode)
52 #define pclose(file)             _pclose(file)
53
54 #else
55 #include <unistd.h>
56 #define HAVE_MKSTEMP
57 #endif
58
59 #ifndef WITH_LIBCORE
60 #define WITH_LIBCORE
61 #endif
62
63 #include <libfirm/firm.h>
64 #include <libfirm/be.h>
65
66 #include "lexer.h"
67 #include "token_t.h"
68 #include "types.h"
69 #include "type_hash.h"
70 #include "parser.h"
71 #include "ast2firm.h"
72 #include "diagnostic.h"
73 #include "lang_features.h"
74 #include "driver/firm_opt.h"
75 #include "driver/firm_cmdline.h"
76 #include "adt/error.h"
77 #include "write_fluffy.h"
78 #include "write_caml.h"
79 #include "revision.h"
80 #include "warning.h"
81
82 #ifndef PREPROCESSOR
83 #define PREPROCESSOR "cpp -std=c99 -U__WCHAR_TYPE__ -D__WCHAR_TYPE__=int -U__SIZE_TYPE__ -D__SIZE_TYPE__=__SIZE_TYPE__ -m32"
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         Assemble,
410         AssemblePreprocessed,
411 } compile_mode_t;
412
413 static void usage(const char *argv0)
414 {
415         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
416 }
417
418 static void print_cparser_version(void) {
419         firm_version_t ver;
420         firm_get_version(&ver);
421
422         printf("cparser (%s) using libFirm (%u.%u",
423                 cparser_REVISION, ver.major, ver.minor);
424         if(ver.revision[0] != 0) {
425                 putchar(' ');
426                 fputs(ver.revision, stdout);
427         }
428         if(ver.build[0] != 0) {
429                 putchar(' ');
430                 fputs(ver.build, stdout);
431         }
432         puts(")\n");
433 }
434
435 static void set_be_option(const char *arg)
436 {
437         int res = firm_be_option(arg);
438         (void) res;
439         assert(res);
440 }
441
442 static void set_option(const char *arg)
443 {
444         int res = firm_option(arg);
445         (void) res;
446         assert(res);
447 }
448
449 static void copy_file(FILE *dest, FILE *input)
450 {
451         char buf[16384];
452
453         while (!feof(input) && !ferror(dest)) {
454                 size_t read = fread(buf, 1, sizeof(buf), input);
455                 if(fwrite(buf, 1, read, dest) != read) {
456                         perror("couldn't write output");
457                 }
458         }
459 }
460
461 int main(int argc, char **argv)
462 {
463         initialize_firm();
464
465         const char        *input        = NULL;
466         const char        *outname      = NULL;
467         const char        *dumpfunction = NULL;
468         compile_mode_t     mode         = CompileAssembleLink;
469         int                opt_level    = 1;
470         int                result       = EXIT_SUCCESS;
471         char               cpu_arch[16] = "ia32";
472         file_list_entry_t *c_files      = NULL;
473         file_list_entry_t *s_files      = NULL;
474         file_list_entry_t *o_files      = NULL;
475         struct obstack     file_obst;
476
477         obstack_init(&cppflags_obst);
478         obstack_init(&ldflags_obst);
479         obstack_init(&file_obst);
480
481 #define GET_ARG_AFTER(def, args)                                             \
482         def = &arg[sizeof(args)-1];                                              \
483         if(def[0] == '\0') {                                                     \
484                 ++i;                                                                 \
485                 if(i >= argc) {                                                      \
486                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
487                         argument_errors = true;                                          \
488                         break;                                                           \
489                 }                                                                    \
490                 def = argv[i];                                                       \
491                 if(def[0] == '-' && def[1] != '\0') {                                \
492                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
493                         argument_errors = true;                                          \
494                         continue;                                                        \
495                 }                                                                    \
496         }
497
498 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
499
500         /* early options parsing (find out optimisation level) */
501         for(int i = 1; i < argc; ++i) {
502                 const char *arg = argv[i];
503                 if(arg[0] != '-')
504                         continue;
505
506                 const char *option = &arg[1];
507                 if(option[0] == 'O') {
508                         sscanf(&option[1], "%d", &opt_level);
509                 }
510         }
511
512         /* apply optimisation level */
513         switch(opt_level) {
514         case 0:
515                 set_option("no-opt");
516                 break;
517         case 1:
518                 set_option("no-inline");
519                 break;
520         default:
521         case 4:
522                 set_option("strict-aliasing");
523                 /* fallthrough */
524         case 3:
525                 set_option("cond-eval");
526                 set_option("if-conv");
527                 use_builtins = true;
528                 /* fallthrough */
529         case 2:
530                 set_option("inline");
531                 set_option("deconv");
532                 set_be_option("omitfp");
533                 break;
534         }
535
536         /* parse rest of options */
537         bool help_displayed  = false;
538         bool argument_errors = false;
539         for(int i = 1; i < argc; ++i) {
540                 const char *arg = argv[i];
541                 if(arg[0] == '-' && arg[1] != 0) {
542                         /* an option */
543                         const char *option = &arg[1];
544                         if(option[0] == 'o') {
545                                 GET_ARG_AFTER(outname, "-o");
546                         } else if(option[0] == 'g') {
547                                 set_be_option("debuginfo=stabs");
548                                 set_be_option("omitfp=no");
549                                 set_be_option("ia32-nooptcc=yes");
550                         } else if(SINGLE_OPTION('c')) {
551                                 mode = CompileAssemble;
552                         } else if(SINGLE_OPTION('E')) {
553                                 mode = PreprocessOnly;
554                         } else if(SINGLE_OPTION('S')) {
555                                 mode = Compile;
556                         } else if(option[0] == 'O') {
557                                 continue;
558                         } else if(option[0] == 'I') {
559                                 const char *opt;
560                                 GET_ARG_AFTER(opt, "-I");
561                                 add_flag(&cppflags_obst, "-I%s", opt);
562                         } else if(option[0] == 'D') {
563                                 const char *opt;
564                                 GET_ARG_AFTER(opt, "-D");
565                                 add_flag(&cppflags_obst, "-D%s", opt);
566                         } else if(option[0] == 'U') {
567                                 const char *opt;
568                                 GET_ARG_AFTER(opt, "-U");
569                                 add_flag(&cppflags_obst, "-U%s", opt);
570                         } else if(option[0] == 'l') {
571                                 const char *opt;
572                                 GET_ARG_AFTER(opt, "-l");
573                                 add_flag(&ldflags_obst, "-l%s", opt);
574                         } else if(option[0] == 'L') {
575                                 const char *opt;
576                                 GET_ARG_AFTER(opt, "-L");
577                                 add_flag(&ldflags_obst, "-L%s", opt);
578                         } else if(SINGLE_OPTION('v')) {
579                                 verbose = 1;
580                         } else if(SINGLE_OPTION('w')) {
581                                 inhibit_all_warnings = true;
582                         } else if(strcmp(option, "M") == 0) {
583                                 mode = PreprocessOnly;
584                                 add_flag(&cppflags_obst, "-M");
585                         } else if(strcmp(option, "MMD") == 0
586                                         || strcmp(option, "MD") == 0
587                                         || strcmp(option, "MM") == 0) {
588                                 add_flag(&cppflags_obst, "-%s", option);
589                         } else if(strcmp(option, "MT") == 0
590                                         || strcmp(option, "MQ") == 0
591                                         || strcmp(option, "MF") == 0) {
592                                 const char *opt;
593                                 GET_ARG_AFTER(opt, "-MT");
594                                 add_flag(&cppflags_obst, "-%s", option);
595                                 add_flag(&cppflags_obst, "%s", opt);
596                         } else if(strcmp(option, "pipe") == 0) {
597                                 /* here for gcc compatibility */
598                         } else if(option[0] == 'f') {
599                                 const char *opt;
600                                 GET_ARG_AFTER(opt, "-f");
601
602                                 if(strcmp(opt, "syntax-only") == 0) {
603                                         mode = ParseOnly;
604                                 } else if(strcmp(opt, "omit-frame-pointer") == 0) {
605                                         set_be_option("omitfp");
606                                 } else if(strcmp(opt, "no-omit-frame-pointer") == 0) {
607                                         set_be_option("omitfp=no");
608                                 } else if(strcmp(opt, "strength-reduce") == 0) {
609                                         firm_option("strength-red");
610                                 } else if(strcmp(opt, "fast-math") == 0
611                                                 || strcmp(opt, "unroll-loops") == 0
612                                                 || strcmp(opt, "expensive-optimizations") == 0
613                                                 || strcmp(opt, "no-common") == 0
614                                                 || strncmp(opt, "align-loops=", sizeof("align-loops=")-1) == 0
615                                                 || strncmp(opt, "align-jumps=", sizeof("align-jumps=")-1) == 0
616                                                 || strncmp(opt, "align-functions=", sizeof("align-functions=")-1) == 0) {
617                                         fprintf(stderr, "ignoring gcc option '-f %s'\n", opt);
618                                 } else {
619                                         int res = firm_option(opt);
620                                         if (res == 0) {
621                                                 fprintf(stderr, "error: unknown Firm option '-f %s'\n",
622                                                         opt);
623                                                 argument_errors = true;
624                                                 continue;
625                                         } else if (res == -1) {
626                                                 help_displayed = true;
627                                         }
628                                 }
629                         } else if(option[0] == 'b') {
630                                 const char *opt;
631                                 GET_ARG_AFTER(opt, "-b");
632                                 int res = firm_be_option(opt);
633                                 if (res == 0) {
634                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
635                                                 opt);
636                                         argument_errors = true;
637                                 } else if (res == -1) {
638                                         help_displayed = true;
639                                 } else {
640                                         if (strncmp(opt, "isa=", 4) == 0)
641                                                 strncpy(cpu_arch, opt, sizeof(cpu_arch));
642                                 }
643                         } else if(option[0] == 'W') {
644                                 set_warning_opt(&option[1]);
645                         } else if(option[0] == 'm') {
646                                 /* -m options */
647                                 const char *opt;
648                                 char arch_opt[64];
649
650                                 GET_ARG_AFTER(opt, "-m");
651                                 if(strncmp(opt, "arch=", 5) == 0) {
652                                         GET_ARG_AFTER(opt, "-march=");
653                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
654                                         int res = firm_be_option(arch_opt);
655                                         if (res == 0)
656                                                 argument_errors = true;
657                                         else {
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                                         }
663                                 } else if(strncmp(opt, "tune=", 5) == 0) {
664                                         GET_ARG_AFTER(opt, "-mtune=");
665                                         snprintf(arch_opt, sizeof(arch_opt), "%s-opt=%s", cpu_arch, opt);
666                                         int res = firm_be_option(arch_opt);
667                                         if (res == 0)
668                                                 argument_errors = true;
669                                 } else if(strncmp(opt, "cpu=", 4) == 0) {
670                                         GET_ARG_AFTER(opt, "-mcpu=");
671                                         snprintf(arch_opt, sizeof(arch_opt), "%s-arch=%s", cpu_arch, opt);
672                                         int res = firm_be_option(arch_opt);
673                                         if (res == 0)
674                                                 argument_errors = true;
675                                 } else if(strncmp(opt, "fpmath=", 7) == 0) {
676                                         GET_ARG_AFTER(opt, "-mfpmath=");
677                                         if(strcmp(opt, "387") == 0)
678                                                 opt = "x87";
679                                         else if(strcmp(opt, "sse") == 0)
680                                                 opt = "sse2";
681                                         else {
682                                                 fprintf(stderr, "error: option -mfpumath supports only 387 or sse\n");
683                                                 argument_errors = true;
684                                         }
685                                         if(!argument_errors) {
686                                                 snprintf(arch_opt, sizeof(arch_opt), "%s-fpunit=%s", cpu_arch, opt);
687                                                 int res = firm_be_option(arch_opt);
688                                                 if (res == 0)
689                                                         argument_errors = true;
690                                         }
691                                 } else if(strncmp(opt, "preferred-stack-boundary=", 25) == 0) {
692                                         GET_ARG_AFTER(opt, "-mpreferred-stack-boundary=");
693                                         snprintf(arch_opt, sizeof(arch_opt), "%s-stackalign=%s", cpu_arch, opt);
694                                         int res = firm_be_option(arch_opt);
695                                         if (res == 0)
696                                                 argument_errors = true;
697                                 } else if(strcmp(opt, "omit-leaf-frame-pointer") == 0) {
698                                         set_be_option("omitleaffp=1");
699                                 } else if(strcmp(opt, "no-omit-leaf-frame-pointer") == 0) {
700                                         set_be_option("omitleaffp=0");
701                                 } else {
702                                         char *endptr;
703                                         long int value = strtol(opt, &endptr, 10);
704                                         if (*endptr != '\0') {
705                                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
706                                                 argument_errors = true;
707                                         }
708                                         if (value != 16 && value != 32 && value != 64) {
709                                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
710                                                 argument_errors = true;
711                                         } else {
712                                                 machine_size = (unsigned int)value;
713                                         }
714                                 }
715                         } else if (option[0] == '\0') {
716                                 if(input != NULL) {
717                                         fprintf(stderr, "error: multiple input files specified\n");
718                                         argument_errors = true;
719                                 } else {
720                                         input = arg;
721                                 }
722                         } else if(strcmp(option, "pg") == 0) {
723                                 set_be_option("gprof");
724                                 add_flag(&ldflags_obst, "-pg");
725                         } else if(strcmp(option, "pedantic") == 0) {
726                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
727                         } else if(strncmp(option, "std=", 4) == 0) {
728                                 if(strcmp(&option[4], "c99") == 0) {
729                                         c_mode = _C89|_C99;
730                                 } else if(strcmp(&option[4], "c89") == 0) {
731                                         c_mode = _C89;
732                                 } else if(strcmp(&option[4], "gnu99") == 0) {
733                                         c_mode = _C89|_C99|_GNUC;
734                                 } else if(strcmp(&option[4], "microsoft") == 0) {
735                                         c_mode = _C89|_C99|_MS;
736                                 } else
737                                         fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
738                         } else if(strcmp(option, "version") == 0) {
739                                 print_cparser_version();
740                         } else if (option[0] == '-') {
741                                 /* double dash option */
742                                 ++option;
743                                 if(strcmp(option, "gcc") == 0) {
744                                         c_mode |= _GNUC;
745                                 } else if(strcmp(option, "no-gcc") == 0) {
746                                         c_mode &= ~_GNUC;
747                                 } else if(strcmp(option, "ms") == 0) {
748                                         c_mode |= _MS;
749                                 } else if(strcmp(option, "no-ms") == 0) {
750                                         c_mode &= ~_MS;
751                                 } else if(strcmp(option, "signed-chars") == 0) {
752                                         char_is_signed = true;
753                                 } else if(strcmp(option, "unsigned-chars") == 0) {
754                                         char_is_signed = false;
755                                 } else if(strcmp(option, "strict") == 0) {
756                                         strict_mode = true;
757                                 } else if(strcmp(option, "lextest") == 0) {
758                                         mode = LexTest;
759                                 } else if(strcmp(option, "benchmark") == 0) {
760                                         mode = BenchmarkParser;
761                                 } else if(strcmp(option, "print-ast") == 0) {
762                                         mode = PrintAst;
763                                 } else if(strcmp(option, "print-implicit-cast") == 0) {
764                                         print_implicit_casts = true;
765                                 } else if(strcmp(option, "print-parenthesis") == 0) {
766                                         print_parenthesis = true;
767                                 } else if(strcmp(option, "print-fluffy") == 0) {
768                                         mode = PrintFluffy;
769                                 } else if(strcmp(option, "print-caml") == 0) {
770                                         mode = PrintCaml;
771                                 } else if(strcmp(option, "version") == 0) {
772                                         print_cparser_version();
773                                         exit(EXIT_SUCCESS);
774                                 } else if(strcmp(option, "dump-function") == 0) {
775                                         ++i;
776                                         if(i >= argc) {
777                                                 fprintf(stderr, "error: "
778                                                         "expected argument after '--dump-function'\n");
779                                                 argument_errors = true;
780                                                 break;
781                                         }
782                                         dumpfunction = argv[i];
783                                         mode         = CompileDump;
784                                 } else {
785                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
786                                         argument_errors = true;
787                                 }
788                         } else {
789                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
790                                 argument_errors = true;
791                         }
792                 } else {
793
794                         file_list_entry_t *entry
795                                 = obstack_alloc(&file_obst, sizeof(entry[0]));
796                         entry->filename = arg;
797
798                         size_t len = strlen(arg);
799                         if (len < 2) {
800                                 if (arg[0] == '-') {
801                                         /* exception: '-' as name reads C from stdin */
802                                         entry->next = c_files;
803                                         c_files     = entry;
804                                         continue;
805                                 }
806                                 fprintf(stderr, "'%s': file format not recognized\n", input);
807                                 continue;
808                         }
809
810                         if (strcmp(arg+len-2, ".c") == 0
811                                         || strcmp(arg+len-2, ".h") == 0) {
812                                 entry->next = c_files;
813                                 c_files     = entry;
814                         } else if (strcmp(arg+len-2, ".s") == 0 || strcmp(arg+len-2, ".S") == 0) {
815                                 entry->next = s_files;
816                                 s_files     = entry;
817                         } else if (strcmp(arg+len-2, ".o") == 0) {
818                                 entry->next = o_files;
819                                 o_files     = entry;
820                         } else {
821                                 fprintf(stderr, "'%s': file format not recognized\n", input);
822                         }
823                 }
824         }
825
826         if (c_files == NULL && s_files == NULL && o_files != NULL) {
827                 mode = Link;
828         } else if (c_files != NULL && c_files->next == NULL) {
829                 input = c_files->filename;
830         } else if (s_files != NULL && s_files->next == NULL) {
831                 input = s_files->filename;
832                 if(!strcmp(input + strlen(input) - 2, ".S"))
833                         mode = AssemblePreprocessed;
834                 else
835                         mode = Assemble;
836         } else {
837                 if (c_files == NULL && s_files == NULL) {
838                         fprintf(stderr, "error: no input files specified\n");
839                 } else {
840                         fprintf(stderr, "error: multiple input files specified\n");
841                 }
842                 argument_errors = true;
843         }
844
845         /* we do the lowering in ast2firm */
846         firm_opt.lower_bitfields = FALSE;
847
848         if (help_displayed) {
849                 return !argument_errors;
850         }
851         if (argument_errors) {
852                 usage(argv[0]);
853                 return 1;
854         }
855
856         gen_firm_init();
857         init_symbol_table();
858         init_tokens();
859         init_types();
860         init_typehash();
861         init_basic_types();
862         init_lexer();
863         init_ast();
864         init_parser();
865         init_ast2firm();
866
867         FILE *out = NULL;
868         char  outnamebuf[4096];
869         if(outname == NULL) {
870                 switch(mode) {
871                 case BenchmarkParser:
872                 case PrintAst:
873                 case PrintFluffy:
874                 case PrintCaml:
875                 case LexTest:
876                 case PreprocessOnly:
877                         outname = "-";
878                         break;
879                 case ParseOnly:
880                         break;
881                 case Compile:
882                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".s");
883                         outname = outnamebuf;
884                         break;
885                 case CompileAssemble:
886                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".o");
887                         outname = outnamebuf;
888                         break;
889                 case CompileDump:
890                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
891                                         ".vcg");
892                         outname = outnamebuf;
893                         break;
894                 case Link:
895                 case CompileAssembleLink:
896 #ifdef _WIN32
897                         /* Windows compiler typically derive the output name from
898                            the first source file */
899                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".exe");
900                         outname = outnamebuf;
901 #else
902                         outname = "a.out";
903 #endif
904                         break;
905                 }
906         }
907
908         if (mode == Assemble) {
909                 assemble(outname, input);
910                 return 0;
911         }
912
913         if (mode == Link) {
914                 obstack_1grow(&ldflags_obst, '\0');
915                 const char *flags = obstack_finish(&ldflags_obst);
916
917                 obstack_printf(&file_obst, "%s", LINKER);
918
919                 for (file_list_entry_t *entry = o_files; entry != NULL;
920                                 entry = entry->next) {
921                         obstack_printf(&file_obst, " %s", entry->filename);
922                 }
923
924                 obstack_printf(&file_obst, " -o %s %s", outname, flags);
925
926                 char *buf = obstack_finish(&file_obst);
927
928                 if(verbose) {
929                         puts(buf);
930                 }
931                 int err = system(buf);
932                 if(err != 0) {
933                         fprintf(stderr, "linker reported an error\n");
934                         exit(1);
935                 }
936                 return 0;
937         }
938
939         if(outname != NULL) {
940                 if(strcmp(outname, "-") == 0) {
941                         out = stdout;
942                 } else {
943                         out = fopen(outname, "w");
944                         if(out == NULL) {
945                                 fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
946                                         strerror(errno));
947                                 return 1;
948                         }
949                 }
950         }
951
952         FILE *in;
953         if(input == NULL) {
954                 fprintf(stderr, "%s: no input files\n", argv[0]);
955                 return 1;
956         } else if(strcmp(input, "-") == 0) {
957                 in    = stdin;
958                 input = "<stdin>";
959         } else {
960                 in = fopen(input, "r");
961                 if(in == NULL) {
962                         fprintf(stderr, "Couldn't open '%s': %s\n", input, strerror(errno));
963                         return 1;
964                 }
965         }
966
967         if(mode == LexTest) {
968                 lextest(in, input);
969                 fclose(in);
970                 return 0;
971         }
972
973         FILE *preprocessed_in = preprocess(in, input);
974         if (mode == PreprocessOnly) {
975                 copy_file(out, preprocessed_in);
976                 return pclose(preprocessed_in);
977         }
978
979         if (mode == AssemblePreprocessed) {
980                 FILE *asm_pp;
981                 char  asm_tempfile[1024];
982
983                 /* write preprocessed assembler to a temporary file */
984                 asm_pp = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "cc", ".s");
985                 copy_file(asm_pp, preprocessed_in);
986                 fclose(asm_pp);
987                 int res = pclose(preprocessed_in);
988                 if (res != 0)
989                         return res;
990
991                 /* and assemble it */
992                 assemble(outname, asm_tempfile);
993                 return 0;
994         }
995
996         translation_unit_t *const unit = do_parsing(preprocessed_in, input);
997         int res = pclose(preprocessed_in);
998         if (res != 0) {
999                 return res;
1000         }
1001
1002         if(error_count > 0) {
1003                 /* parsing failed because of errors */
1004                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count, warning_count);
1005                 result = EXIT_FAILURE;
1006         } else if(warning_count > 0) {
1007                 fprintf(stderr, "%u warning(s)\n", warning_count);
1008         }
1009
1010         if(mode == BenchmarkParser) {
1011                 return result;
1012         }
1013
1014         /* prints the AST even if errors occurred */
1015         if(mode == PrintAst) {
1016                 type_set_output(out);
1017                 ast_set_output(out);
1018                 print_ast(unit);
1019                 return result;
1020         }
1021
1022         /* cannot handle other modes with errors */
1023         if(result != EXIT_SUCCESS)
1024                 return result;
1025
1026         if(mode == PrintFluffy) {
1027                 write_fluffy_decls(out, unit);
1028         }
1029         if (mode == PrintCaml) {
1030                 write_caml_decls(out, unit);
1031         }
1032
1033         translation_unit_to_firm(unit);
1034
1035         if(mode == ParseOnly) {
1036                 return 0;
1037         }
1038
1039         FILE *asm_out;
1040         char  asm_tempfile[1024];
1041         if(mode == CompileDump) {
1042                 asm_out = NULL;
1043                 firm_be_opt.selection = BE_NONE;
1044         } else if(mode == Compile) {
1045                 asm_out = out;
1046         } else {
1047                 asm_out
1048                         = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "cc", ".s");
1049         }
1050         gen_firm_finish(asm_out, input, /*c_mode=*/1, /*firm_const_exists=*/0);
1051
1052         if(mode == CompileDump) {
1053                 /* find irg */
1054                 ident    *id     = new_id_from_str(dumpfunction);
1055                 ir_graph *irg    = NULL;
1056                 int       n_irgs = get_irp_n_irgs();
1057                 for(int i = 0; i < n_irgs; ++i) {
1058                         ir_graph *tirg   = get_irp_irg(i);
1059                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
1060                         if(irg_id == id) {
1061                                 irg = tirg;
1062                                 break;
1063                         }
1064                 }
1065
1066                 if(irg == NULL) {
1067                         fprintf(stderr, "No graph for function '%s' found\n", dumpfunction);
1068                         return 1;
1069                 }
1070
1071                 dump_ir_block_graph_file(irg, out);
1072                 fclose(out);
1073                 return 0;
1074         }
1075
1076         fclose(asm_out);
1077
1078         /* assemble assembler and create object file */
1079         char obj_tfile[1024];
1080         if(mode == CompileAssemble || mode == CompileAssembleLink) {
1081                 const char *obj_outfile;
1082                 if(mode == CompileAssemble) {
1083                         fclose(out);
1084                         obj_outfile = outname;
1085                 } else {
1086                         FILE *tempf
1087                                 = make_temp_file(obj_tfile, sizeof(obj_tfile), "cc", ".o");
1088                         fclose(tempf);
1089                         obj_outfile = obj_tfile;
1090                 }
1091
1092                 assemble(obj_outfile, asm_tempfile);
1093         }
1094
1095         /* link object file */
1096         if(mode == CompileAssembleLink) {
1097                 do_link(outname, obj_tfile);
1098         }
1099
1100         obstack_free(&cppflags_obst, NULL);
1101         obstack_free(&ldflags_obst, NULL);
1102         obstack_free(&file_obst, NULL);
1103
1104         exit_ast2firm();
1105         exit_parser();
1106         exit_ast();
1107         exit_lexer();
1108         exit_typehash();
1109         exit_types();
1110         exit_tokens();
1111         exit_symbol_table();
1112         return 0;
1113 }