accept -ofilename instead of just -o filename
[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
51 static void initialize_firm(void)
52 {
53         firm_early_init();
54         gen_firm_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
118         if(in != stdin) {
119                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s", fname);
120         } else {
121                 /* read from stdin */
122                 snprintf(buf, sizeof(buf), PREPROCESSOR " -");
123         }
124
125         if(verbose) {
126                 puts(buf);
127         }
128         FILE* f = popen(buf, "r");
129         if (f == NULL) {
130                 fprintf(stderr, "invoking preprocessor failed\n");
131                 exit(1);
132         }
133         return f;
134 }
135
136 static void do_link(const char *out, const char *in)
137 {
138         char buf[4096];
139
140         snprintf(buf, sizeof(buf), "%s %s -o %s", LINKER, in, out);
141         if(verbose) {
142                 puts(buf);
143         }
144         int err = system(buf);
145         if(err != 0) {
146                 fprintf(stderr, "linker reported an error\n");
147                 exit(1);
148         }
149 }
150
151 static void assemble(const char *out, const char *in)
152 {
153         char buf[4096];
154
155         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
156         if(verbose) {
157                 puts(buf);
158         }
159
160         int err = system(buf);
161         if(err != 0) {
162                 fprintf(stderr, "assembler reported an error\n");
163                 exit(1);
164         }
165 }
166
167 static const char *try_dir(const char *dir)
168 {
169         if(dir == NULL)
170                 return dir;
171         if(access(dir, R_OK | W_OK | X_OK) == 0)
172                 return dir;
173         return NULL;
174 }
175
176 static const char *get_tempdir(void)
177 {
178         static const char *tmpdir = NULL;
179
180         if(tmpdir != NULL)
181                 return tmpdir;
182
183         if(tmpdir == NULL)
184                 tmpdir = try_dir(getenv("TMPDIR"));
185         if(tmpdir == NULL)
186                 tmpdir = try_dir(getenv("TMP"));
187         if(tmpdir == NULL)
188                 tmpdir = try_dir(getenv("TEMP"));
189
190 #ifdef P_tmpdir
191         if(tmpdir == NULL)
192                 tmpdir = try_dir(P_tmpdir);
193 #endif
194
195         if(tmpdir == NULL)
196                 tmpdir = try_dir("/var/tmp");
197         if(tmpdir == NULL)
198                 tmpdir = try_dir("/usr/tmp");
199         if(tmpdir == NULL)
200                 tmpdir = try_dir("/tmp");
201
202         if(tmpdir == NULL)
203                 tmpdir = ".";
204
205         return tmpdir;
206 }
207
208 /**
209  * an own version of tmpnam, which: writes in a buffer, appends a user specified
210  * suffix, emits no warnings during linking (like glibc/gnu ld do for tmpnam)...
211  */
212 static FILE *make_temp_file(char *buffer, size_t buflen,
213                             const char *prefix, const char *suffix)
214 {
215         const char *tempdir = get_tempdir();
216
217         /* oh well... mkstemp doesn't accept a suffix after XXXXXX... */
218         (void) suffix;
219         suffix = "";
220
221         snprintf(buffer, buflen, "%s/%sXXXXXX%s", tempdir, prefix, suffix);
222
223         int fd = mkstemp(buffer);
224         if(fd == -1) {
225                 fprintf(stderr, "couldn't create temporary file: %s\n",
226                         strerror(errno));
227                 exit(1);
228         }
229         FILE *out = fdopen(fd, "w");
230         if(out == NULL) {
231                 fprintf(stderr, "couldn't create temporary file FILE*\n");
232                 exit(1);
233         }
234
235         return out;
236 }
237
238 /**
239  * Do the necessary lowering for compound parameters.
240  */
241 void lower_compound_params(void)
242 {
243         lower_params_t params;
244
245         params.def_ptr_alignment    = 4;
246         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
247         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
248         params.find_pointer_type    = NULL;
249         params.ret_compound_in_regs = NULL;
250         lower_calls_with_compounds(&params);
251 }
252
253 static void create_firm_prog(translation_unit_t *unit)
254 {
255         translation_unit_to_firm(unit);
256
257         //dump_globals_as_text(dump_verbosity_max, "-globals");
258
259         int n_irgs = get_irp_n_irgs();
260         for(int i = 0; i < n_irgs; ++i) {
261                 ir_graph *const irg = get_irp_irg(i);
262                 dump(irg, "-start");
263         }
264
265         lower_compound_params();
266         lower_highlevel();
267
268         for(int i = 0; i < n_irgs; ++i) {
269                 ir_graph *const irg = get_irp_irg(i);
270                 dump(irg, "-lower");
271         }
272 }
273
274 typedef enum compile_mode_t {
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         for(int i = 1; i < argc; ++i) {
308                 const char *arg = argv[i];
309                 if(strncmp(arg, "-o", 2) == 0) {
310                         outname = &arg[2];
311                         if(outname[0] == '\0') {
312                                 ++i;
313                                 if(i >= argc) {
314                                         usage(argv[0]);
315                                         return 1;
316                                 }
317                                 outname = argv[i];
318                         }
319                 } else if(strcmp(arg, "-c") == 0) {
320                         mode = CompileAssemble;
321                 } else if(strcmp(arg, "-S") == 0) {
322                         mode = Compile;
323                 } else if(strcmp(arg, "--lextest") == 0) {
324                         mode = LexTest;
325                 } else if(strcmp(arg, "--print-ast") == 0) {
326                         mode = PrintAst;
327                 } else if(strcmp(arg, "--print-fluffy") == 0) {
328                         mode = PrintFluffy;
329                 } else if(strcmp(arg, "--dump") == 0) {
330                         do_dump = true;
331                 } else if(strcmp(arg, "--dump-function") == 0) {
332                         ++i;
333                         if(i >= argc) {
334                                 usage(argv[0]);
335                                 return 1;
336                         }
337                         dumpfunction = argv[i];
338                         mode         = CompileDump;
339                 } else if(strcmp(arg, "-v") == 0) {
340                         verbose = 1;
341                 } else if(arg[0] == '-' && arg[1] == 'f') {
342                         const char *opt = &arg[2];
343                         if(opt[0] == 0) {
344                                 ++i;
345                                 if(i >= argc) {
346                                         usage(argv[0]);
347                                         return 1;
348                                 }
349                                 opt = argv[i];
350                                 if(opt[0] == '-') {
351                                         usage(argv[0]);
352                                         return 1;
353                                 }
354                         }
355                         int res = firm_option(opt);
356                         if (res == 0) {
357                                 fprintf(stderr, "Error: unknown Firm option %s\n", opt);
358                                 usage(argv[0]);
359                                 return 1;
360                         } else if (res == -1) /* help option */
361                                 exit(0);
362                 } else if(arg[0] == '-' && arg[1] == 'b') {
363                         const char *opt = &arg[2];
364                         if(opt[0] == 0) {
365                                 ++i;
366                                 if(i >= argc) {
367                                         usage(argv[0]);
368                                         return 1;
369                                 }
370                                 opt = argv[i];
371                                 if(opt[0] == '-') {
372                                         usage(argv[0]);
373                                         return 1;
374                                 }
375                         }
376                         int res = firm_be_option(opt);
377                         if (res == 0) {
378                                 fprintf(stderr, "Error: unknown Firm backend option %s\n", opt);
379                                 usage(argv[0]);
380                                 return 1;
381                         } else if (res == -1) /* help option */
382                                 exit(0);
383                 } else if(arg[0] == '-') {
384                         if (arg[1] == '\0') {
385                                 input = "-";
386                         } else if (arg[1] == 'D' ||
387                                         arg[1] == 'O' ||
388                                         arg[1] == 'f' ||
389                                         arg[1] == 'W' ||
390                                         arg[1] == 'g' ||
391                                         strncmp(arg + 1, "std=", 4) == 0) {
392                                 fprintf(stderr, "Warning: Ignoring option '%s'\n", arg);
393                         } else {
394                                 usage(argv[0]);
395                                 return 1;
396                         }
397                 } else {
398                         if(input != NULL) {
399                                 fprintf(stderr, "Error: multiple input files specified\n");
400                                 usage(argv[0]);
401                                 return 1;
402                         } else {
403                                 input = arg;
404                         }
405                 }
406         }
407
408         FILE *out;
409         char  outnamebuf[4096];
410         if(outname == NULL) {
411                 switch(mode) {
412                 case PrintAst:
413                 case PrintFluffy:
414                 case LexTest:
415                         break;
416                 case Compile:
417                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".s");
418                         outname = outnamebuf;
419                         break;
420                 case CompileAssemble:
421                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".o");
422                         outname = outnamebuf;
423                         break;
424                 case CompileDump:
425                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
426                                         ".vcg");
427                         outname = outnamebuf;
428                         break;
429                 case CompileAssembleLink:
430                         outname = "a.out";
431                         break;
432                 }
433                 assert(outname != NULL);
434         }
435
436         if(strcmp(outname, "-") == 0) {
437                 out = stdout;
438         } else {
439                 out = fopen(outname, "w");
440                 if(out == NULL) {
441                         fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
442                                 strerror(errno));
443                         return 1;
444                 }
445         }
446
447         FILE *in;
448         if(input == NULL) {
449                 fprintf(stderr, "%s: no input files\n", argv[0]);
450                 return 1;
451         } else if(strcmp(input, "-") == 0) {
452                 in    = stdin;
453                 input = "<stdin>";
454         } else {
455                 in = fopen(input, "r");
456                 if(in == NULL) {
457                         fprintf(stderr, "Couldn't open '%s': %s\n", input, strerror(errno));
458                         return 1;
459                 }
460         }
461
462         if(mode == LexTest) {
463                 lextest(in, input);
464                 fclose(in);
465                 return 0;
466         }
467
468         FILE *preprocessed_in = preprocess(in, input);
469         translation_unit_t *const unit = do_parsing(preprocessed_in, input);
470         pclose(preprocessed_in);
471         if(unit == NULL)
472                 return 1;
473
474         if(mode == PrintAst) {
475                 ast_set_output(out);
476                 print_ast(unit);
477                 return 0;
478         }
479         if(mode == PrintFluffy) {
480                 write_fluffy_decls(out, unit);
481         }
482
483         create_firm_prog(unit);
484
485         FILE *asm_out;
486         char  asm_tempfile[1024];
487         if(mode == CompileDump) {
488                 asm_out = NULL;
489                 firm_be_opt.selection = BE_NONE;
490         } else if(mode == Compile) {
491                 asm_out = out;
492         } else {
493                 asm_out
494                         = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "cc", ".s");
495         }
496         gen_firm_finish(asm_out, input, /*c_mode=*/1, /*firm_const_exists=*/0);
497
498         if(mode == CompileDump) {
499                 /* find irg */
500                 ident    *id     = new_id_from_str(dumpfunction);
501                 ir_graph *irg    = NULL;
502                 int       n_irgs = get_irp_n_irgs();
503                 for(int i = 0; i < n_irgs; ++i) {
504                         ir_graph *tirg   = get_irp_irg(i);
505                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
506                         if(irg_id == id) {
507                                 irg = tirg;
508                                 break;
509                         }
510                 }
511
512                 if(irg == NULL) {
513                         fprintf(stderr, "No graph for function '%s' found\n", dumpfunction);
514                         return 1;
515                 }
516
517                 dump_ir_block_graph_file(irg, out);
518                 fclose(out);
519                 return 0;
520         }
521
522         fclose(asm_out);
523
524         /* assemble assembler and create object file */
525         char obj_tfile[1024];
526         if(mode == CompileAssemble || mode == CompileAssembleLink) {
527                 const char *obj_outfile;
528                 if(mode == CompileAssemble) {
529                         fclose(out);
530                         obj_outfile = outname;
531                 } else {
532                         FILE *tempf
533                                 = make_temp_file(obj_tfile, sizeof(obj_tfile), "cc", ".o");
534                         fclose(tempf);
535                         obj_outfile = obj_tfile;
536                 }
537
538                 assemble(obj_outfile, asm_tempfile);
539         }
540
541         /* link object file */
542         if(mode == CompileAssembleLink) {
543                 do_link(outname, obj_tfile);
544         }
545
546         exit_ast2firm();
547         exit_parser();
548         exit_ast();
549         exit_lexer();
550         exit_typehash();
551         exit_types();
552         exit_tokens();
553         exit_symbol_table();
554         return 0;
555 }