e760cc9295753d38fd6c4d91554eca943e13a97a
[cparser] / main.c
1 #include <config.h>
2
3 #define _GNU_SOURCE
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdbool.h>
8 #include <errno.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <assert.h>
12
13 #ifndef WITH_LIBCORE
14 #define WITH_LIBCORE
15 #endif
16
17 #include <libfirm/firm.h>
18 #include <libfirm/be.h>
19
20 #include "lexer.h"
21 #include "token_t.h"
22 #include "type_hash.h"
23 #include "parser.h"
24 #include "ast2firm.h"
25 #include "driver/firm_cmdline.h"
26 #include "adt/error.h"
27 #include "write_fluffy.h"
28 #include "driver/firm_opt.h"
29
30 #ifndef PREPROCESSOR
31 #define PREPROCESSOR "cpp -std=c99 -U__WCHAR_TYPE__ -D__WCHAR_TYPE__=int"
32 #endif
33
34 #ifndef LINKER
35 #define LINKER       "gcc"
36 #endif
37
38 #ifndef ASSEMBLER
39 #define ASSEMBLER "as"
40 #endif
41
42 #ifdef _WIN32
43 /* remap some names */
44 #define popen(cmd, mode)  _popen(cmd, mode)
45 #define pclose(file)      _pclose(file)
46 #endif /* _WIN32 */
47
48 static int            verbose;
49 static bool           do_dump;
50 static struct obstack cppflags_obst;
51
52 static void initialize_firm(void)
53 {
54         firm_early_init();
55
56         dump_consts_local(1);
57         dump_keepalive_edges(1);
58 }
59
60 static void dump(ir_graph *irg, const char *suffix)
61 {
62         if(do_dump) {
63                 dump_ir_block_graph(irg, suffix);
64         }
65 }
66
67 static void get_output_name(char *buf, size_t buflen, const char *inputname,
68                             const char *newext)
69 {
70         size_t last_dot = 0xffffffff;
71         size_t i = 0;
72
73         if(inputname == NULL) {
74                 snprintf(buf, buflen, "a%s", newext);
75                 return;
76         }
77
78         for(const char *c = inputname; *c != 0; ++c) {
79                 if(*c == '.')
80                         last_dot = i;
81                 ++i;
82         }
83         if(last_dot == 0xffffffff)
84                 last_dot = i;
85
86         if(last_dot >= buflen)
87                 panic("filename too long");
88         memcpy(buf, inputname, last_dot);
89
90         size_t extlen = strlen(newext) + 1;
91         if(extlen + last_dot >= buflen)
92                 panic("filename too long");
93         memcpy(buf+last_dot, newext, extlen);
94 }
95
96 static translation_unit_t *do_parsing(FILE *const in, const char *const input)
97 {
98         lexer_open_stream(in, input);
99         translation_unit_t *unit = parse();
100         return unit;
101 }
102
103 static void lextest(FILE *in, const char *fname)
104 {
105         lexer_open_stream(in, fname);
106
107         do {
108                 lexer_next_preprocessing_token();
109                 print_token(stdout, &lexer_token);
110                 puts("");
111         } while(lexer_token.type != T_EOF);
112 }
113
114 static FILE* preprocess(FILE* in, const char *fname)
115 {
116         char buf[4096];
117         const char *flags = obstack_finish(&cppflags_obst);
118
119         if(in != stdin) {
120                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s %s", flags, fname);
121         } else {
122                 /* read from stdin */
123                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s -", flags);
124         }
125
126         if(verbose) {
127                 puts(buf);
128         }
129         FILE* f = popen(buf, "r");
130         if (f == NULL) {
131                 fprintf(stderr, "invoking preprocessor failed\n");
132                 exit(1);
133         }
134         return f;
135 }
136
137 static void do_link(const char *out, const char *in)
138 {
139         char buf[4096];
140
141         snprintf(buf, sizeof(buf), "%s %s -o %s", LINKER, in, out);
142         if(verbose) {
143                 puts(buf);
144         }
145         int err = system(buf);
146         if(err != 0) {
147                 fprintf(stderr, "linker reported an error\n");
148                 exit(1);
149         }
150 }
151
152 static void assemble(const char *out, const char *in)
153 {
154         char buf[4096];
155
156         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
157         if(verbose) {
158                 puts(buf);
159         }
160
161         int err = system(buf);
162         if(err != 0) {
163                 fprintf(stderr, "assembler reported an error\n");
164                 exit(1);
165         }
166 }
167
168 static const char *try_dir(const char *dir)
169 {
170         if(dir == NULL)
171                 return dir;
172         if(access(dir, R_OK | W_OK | X_OK) == 0)
173                 return dir;
174         return NULL;
175 }
176
177 static const char *get_tempdir(void)
178 {
179         static const char *tmpdir = NULL;
180
181         if(tmpdir != NULL)
182                 return tmpdir;
183
184         if(tmpdir == NULL)
185                 tmpdir = try_dir(getenv("TMPDIR"));
186         if(tmpdir == NULL)
187                 tmpdir = try_dir(getenv("TMP"));
188         if(tmpdir == NULL)
189                 tmpdir = try_dir(getenv("TEMP"));
190
191 #ifdef P_tmpdir
192         if(tmpdir == NULL)
193                 tmpdir = try_dir(P_tmpdir);
194 #endif
195
196         if(tmpdir == NULL)
197                 tmpdir = try_dir("/var/tmp");
198         if(tmpdir == NULL)
199                 tmpdir = try_dir("/usr/tmp");
200         if(tmpdir == NULL)
201                 tmpdir = try_dir("/tmp");
202
203         if(tmpdir == NULL)
204                 tmpdir = ".";
205
206         return tmpdir;
207 }
208
209 /**
210  * an own version of tmpnam, which: writes in a buffer, appends a user specified
211  * suffix, emits no warnings during linking (like glibc/gnu ld do for tmpnam)...
212  */
213 static FILE *make_temp_file(char *buffer, size_t buflen,
214                             const char *prefix, const char *suffix)
215 {
216         const char *tempdir = get_tempdir();
217
218         /* oh well... mkstemp doesn't accept a suffix after XXXXXX... */
219         (void) suffix;
220         suffix = "";
221
222         snprintf(buffer, buflen, "%s/%sXXXXXX%s", tempdir, prefix, suffix);
223
224         int fd = mkstemp(buffer);
225         if(fd == -1) {
226                 fprintf(stderr, "couldn't create temporary file: %s\n",
227                         strerror(errno));
228                 exit(1);
229         }
230         FILE *out = fdopen(fd, "w");
231         if(out == NULL) {
232                 fprintf(stderr, "couldn't create temporary file FILE*\n");
233                 exit(1);
234         }
235
236         return out;
237 }
238
239 /**
240  * Do the necessary lowering for compound parameters.
241  */
242 void lower_compound_params(void)
243 {
244         lower_params_t params;
245
246         params.def_ptr_alignment    = 4;
247         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
248         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
249         params.find_pointer_type    = NULL;
250         params.ret_compound_in_regs = NULL;
251         lower_calls_with_compounds(&params);
252 }
253
254 static void create_firm_prog(translation_unit_t *unit)
255 {
256         translation_unit_to_firm(unit);
257
258         int n_irgs = get_irp_n_irgs();
259         for(int i = 0; i < n_irgs; ++i) {
260                 ir_graph *const irg = get_irp_irg(i);
261                 dump(irg, "-start");
262         }
263
264         lower_compound_params();
265         lower_highlevel();
266
267         for(int i = 0; i < n_irgs; ++i) {
268                 ir_graph *const irg = get_irp_irg(i);
269                 dump(irg, "-lower");
270         }
271 }
272
273 typedef enum compile_mode_t {
274         ParseOnly,
275         Compile,
276         CompileDump,
277         CompileAssemble,
278         CompileAssembleLink,
279         LexTest,
280         PrintAst,
281         PrintFluffy
282 } compile_mode_t;
283
284 static void usage(const char *argv0)
285 {
286         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
287 }
288
289 int main(int argc, char **argv)
290 {
291         initialize_firm();
292
293         init_symbol_table();
294         init_tokens();
295         init_types();
296         init_typehash();
297         init_lexer();
298         init_ast();
299         init_parser();
300         init_ast2firm();
301
302         const char     *input        = NULL;
303         const char     *outname      = NULL;
304         const char     *dumpfunction = NULL;
305         compile_mode_t  mode         = CompileAssembleLink;
306
307         obstack_init(&cppflags_obst);
308
309 #define GET_ARG_AFTER(def, args)                                             \
310         def = &arg[sizeof(args)-1];                                              \
311         if(def[0] == '\0') {                                                     \
312                 ++i;                                                                 \
313                 if(i >= argc) {                                                      \
314                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
315                         argument_errors = true;                                          \
316                         break;                                                           \
317                 }                                                                    \
318                 def = argv[i];                                                       \
319                 if(def[0] == '-' && def[1] != '\0') {                                \
320                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
321                         argument_errors = true;                                          \
322                         continue;                                                        \
323                 }                                                                    \
324         }
325
326         bool help_displayed  = false;
327         bool argument_errors = false;
328         for(int i = 1; i < argc; ++i) {
329                 const char *arg = argv[i];
330                 if(strncmp(arg, "-o", 2) == 0) {
331                         GET_ARG_AFTER(outname, "-o");
332                 } else if(strcmp(arg, "-c") == 0) {
333                         mode = CompileAssemble;
334                 } else if(strcmp(arg, "-S") == 0) {
335                         mode = Compile;
336                 } else if(strcmp(arg, "--lextest") == 0) {
337                         mode = LexTest;
338                 } else if(strcmp(arg, "--print-ast") == 0) {
339                         mode = PrintAst;
340                 } else if(strcmp(arg, "--print-fluffy") == 0) {
341                         mode = PrintFluffy;
342                 } else if(strcmp(arg, "-fsyntax-only") == 0) {
343                         mode = ParseOnly;
344                 } else if(strncmp(arg, "-I", 2) == 0) {
345                         const char *opt;
346                         GET_ARG_AFTER(opt, "-I");
347                         obstack_printf(&cppflags_obst, " -I%s", opt);
348                 } else if(strncmp(arg, "-D", 2) == 0) {
349                         const char *opt;
350                         GET_ARG_AFTER(opt, "-D");
351                         obstack_printf(&cppflags_obst, " -D%s", opt);
352                 } else if(strcmp(arg, "--dump") == 0) {
353                         do_dump = true;
354                 } else if(strcmp(arg, "--dump-function") == 0) {
355                         ++i;
356                         if(i >= argc) {
357                                 fprintf(stderr, "error: "
358                                         "expected argument after '--dump-function'\n");
359                                 argument_errors = true;
360                                 break;
361                         }
362                         dumpfunction = argv[i];
363                         mode         = CompileDump;
364                 } else if(strcmp(arg, "-v") == 0) {
365                         verbose = 1;
366                 } else if(arg[0] == '-' && arg[1] == 'f') {
367                         const char *opt;
368                         GET_ARG_AFTER(opt, "-f");
369                         int res = firm_option(opt);
370                         if (res == 0) {
371                                 fprintf(stderr, "error: unknown Firm option '-f %s'\n", opt);
372                                 argument_errors = true;
373                                 continue;
374                         } else if (res == -1) {
375                                 help_displayed = true;
376                         }
377                 } else if(arg[0] == '-' && arg[1] == 'b') {
378                         const char *opt;
379                         GET_ARG_AFTER(opt, "-b");
380                         int res = firm_be_option(opt);
381                         if (res == 0) {
382                                 fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
383                                         opt);
384                                 argument_errors = true;
385                         } else if (res == -1) {
386                                 help_displayed = true;
387                         }
388                 } else if(arg[0] == '-') {
389                         if (arg[1] == '\0') {
390                                 if(input != NULL) {
391                                         fprintf(stderr, "error: multiple input files specified\n");
392                                         argument_errors = true;
393                                 } else {
394                                         input = arg;
395                                 }
396                         } else if (arg[1] == 'O' ||
397                                         arg[1] == 'f' ||
398                                         arg[1] == 'W' ||
399                                         arg[1] == 'g' ||
400                                         strncmp(arg + 1, "std=", 4) == 0) {
401                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
402                         } else {
403                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
404                                 argument_errors = true;
405                         }
406                 } else {
407                         if(input != NULL) {
408                                 fprintf(stderr, "error: multiple input files specified\n");
409                                 argument_errors = true;
410                         } else {
411                                 input = arg;
412                         }
413                 }
414         }
415
416         if(help_displayed) {
417                 return !argument_errors;
418         }
419         if(argument_errors) {
420                 usage(argv[0]);
421                 return 1;
422         }
423
424         FILE *out;
425         char  outnamebuf[4096];
426         if(outname == NULL) {
427                 switch(mode) {
428                 case PrintAst:
429                 case PrintFluffy:
430                 case LexTest:
431                 case ParseOnly:
432                         break;
433                 case Compile:
434                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".s");
435                         outname = outnamebuf;
436                         break;
437                 case CompileAssemble:
438                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".o");
439                         outname = outnamebuf;
440                         break;
441                 case CompileDump:
442                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
443                                         ".vcg");
444                         outname = outnamebuf;
445                         break;
446                 case CompileAssembleLink:
447                         outname = "a.out";
448                         break;
449                 }
450         }
451
452         if(outname != NULL) {
453                 if(strcmp(outname, "-") == 0) {
454                         out = stdout;
455                 } else {
456                         out = fopen(outname, "w");
457                         if(out == NULL) {
458                                 fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
459                                         strerror(errno));
460                                 return 1;
461                         }
462                 }
463         }
464
465         FILE *in;
466         if(input == NULL) {
467                 fprintf(stderr, "%s: no input files\n", argv[0]);
468                 return 1;
469         } else if(strcmp(input, "-") == 0) {
470                 in    = stdin;
471                 input = "<stdin>";
472         } else {
473                 in = fopen(input, "r");
474                 if(in == NULL) {
475                         fprintf(stderr, "Couldn't open '%s': %s\n", input, strerror(errno));
476                         return 1;
477                 }
478         }
479
480         if(mode == LexTest) {
481                 lextest(in, input);
482                 fclose(in);
483                 return 0;
484         }
485
486         FILE *preprocessed_in = preprocess(in, input);
487         translation_unit_t *const unit = do_parsing(preprocessed_in, input);
488         pclose(preprocessed_in);
489         if(unit == NULL)
490                 return 1;
491
492         if(mode == PrintAst) {
493                 ast_set_output(out);
494                 print_ast(unit);
495                 return 0;
496         }
497         if(mode == PrintFluffy) {
498                 write_fluffy_decls(out, unit);
499         }
500
501         gen_firm_init();
502         create_firm_prog(unit);
503
504         if(mode == ParseOnly) {
505                 return 0;
506         }
507
508         FILE *asm_out;
509         char  asm_tempfile[1024];
510         if(mode == CompileDump) {
511                 asm_out = NULL;
512                 firm_be_opt.selection = BE_NONE;
513         } else if(mode == Compile) {
514                 asm_out = out;
515         } else {
516                 asm_out
517                         = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "cc", ".s");
518         }
519         gen_firm_finish(asm_out, input, /*c_mode=*/1, /*firm_const_exists=*/0);
520
521         if(mode == CompileDump) {
522                 /* find irg */
523                 ident    *id     = new_id_from_str(dumpfunction);
524                 ir_graph *irg    = NULL;
525                 int       n_irgs = get_irp_n_irgs();
526                 for(int i = 0; i < n_irgs; ++i) {
527                         ir_graph *tirg   = get_irp_irg(i);
528                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
529                         if(irg_id == id) {
530                                 irg = tirg;
531                                 break;
532                         }
533                 }
534
535                 if(irg == NULL) {
536                         fprintf(stderr, "No graph for function '%s' found\n", dumpfunction);
537                         return 1;
538                 }
539
540                 dump_ir_block_graph_file(irg, out);
541                 fclose(out);
542                 return 0;
543         }
544
545         fclose(asm_out);
546
547         /* assemble assembler and create object file */
548         char obj_tfile[1024];
549         if(mode == CompileAssemble || mode == CompileAssembleLink) {
550                 const char *obj_outfile;
551                 if(mode == CompileAssemble) {
552                         fclose(out);
553                         obj_outfile = outname;
554                 } else {
555                         FILE *tempf
556                                 = make_temp_file(obj_tfile, sizeof(obj_tfile), "cc", ".o");
557                         fclose(tempf);
558                         obj_outfile = obj_tfile;
559                 }
560
561                 assemble(obj_outfile, asm_tempfile);
562         }
563
564         /* link object file */
565         if(mode == CompileAssembleLink) {
566                 do_link(outname, obj_tfile);
567         }
568
569         obstack_free(&cppflags_obst, NULL);
570
571         exit_ast2firm();
572         exit_parser();
573         exit_ast();
574         exit_lexer();
575         exit_typehash();
576         exit_types();
577         exit_tokens();
578         exit_symbol_table();
579         return 0;
580 }