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