a42cfe63425849440455b2477377a56333f8b14c
[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
55         dump_consts_local(1);
56         dump_keepalive_edges(1);
57 }
58
59 static void dump(ir_graph *irg, const char *suffix)
60 {
61         if(do_dump) {
62                 dump_ir_block_graph(irg, suffix);
63         }
64 }
65
66 static void get_output_name(char *buf, size_t buflen, const char *inputname,
67                             const char *newext)
68 {
69         size_t last_dot = 0xffffffff;
70         size_t i = 0;
71
72         if(inputname == NULL) {
73                 snprintf(buf, buflen, "a%s", newext);
74                 return;
75         }
76
77         for(const char *c = inputname; *c != 0; ++c) {
78                 if(*c == '.')
79                         last_dot = i;
80                 ++i;
81         }
82         if(last_dot == 0xffffffff)
83                 last_dot = i;
84
85         if(last_dot >= buflen)
86                 panic("filename too long");
87         memcpy(buf, inputname, last_dot);
88
89         size_t extlen = strlen(newext) + 1;
90         if(extlen + last_dot >= buflen)
91                 panic("filename too long");
92         memcpy(buf+last_dot, newext, extlen);
93 }
94
95 static translation_unit_t *do_parsing(FILE *const in, const char *const input)
96 {
97         lexer_open_stream(in, input);
98         translation_unit_t *unit = parse();
99         return unit;
100 }
101
102 static void lextest(FILE *in, const char *fname)
103 {
104         lexer_open_stream(in, fname);
105
106         do {
107                 lexer_next_preprocessing_token();
108                 print_token(stdout, &lexer_token);
109                 puts("");
110         } while(lexer_token.type != T_EOF);
111 }
112
113 static FILE* preprocess(FILE* in, const char *fname)
114 {
115         char buf[4096];
116
117         if(in != stdin) {
118                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s", fname);
119         } else {
120                 /* read from stdin */
121                 snprintf(buf, sizeof(buf), PREPROCESSOR " -");
122         }
123
124         if(verbose) {
125                 puts(buf);
126         }
127         FILE* f = popen(buf, "r");
128         if (f == NULL) {
129                 fprintf(stderr, "invoking preprocessor failed\n");
130                 exit(1);
131         }
132         return f;
133 }
134
135 static void do_link(const char *out, const char *in)
136 {
137         char buf[4096];
138
139         snprintf(buf, sizeof(buf), "%s %s -o %s", LINKER, in, out);
140         if(verbose) {
141                 puts(buf);
142         }
143         int err = system(buf);
144         if(err != 0) {
145                 fprintf(stderr, "linker reported an error\n");
146                 exit(1);
147         }
148 }
149
150 static void assemble(const char *out, const char *in)
151 {
152         char buf[4096];
153
154         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
155         if(verbose) {
156                 puts(buf);
157         }
158
159         int err = system(buf);
160         if(err != 0) {
161                 fprintf(stderr, "assembler reported an error\n");
162                 exit(1);
163         }
164 }
165
166 static const char *try_dir(const char *dir)
167 {
168         if(dir == NULL)
169                 return dir;
170         if(access(dir, R_OK | W_OK | X_OK) == 0)
171                 return dir;
172         return NULL;
173 }
174
175 static const char *get_tempdir(void)
176 {
177         static const char *tmpdir = NULL;
178
179         if(tmpdir != NULL)
180                 return tmpdir;
181
182         if(tmpdir == NULL)
183                 tmpdir = try_dir(getenv("TMPDIR"));
184         if(tmpdir == NULL)
185                 tmpdir = try_dir(getenv("TMP"));
186         if(tmpdir == NULL)
187                 tmpdir = try_dir(getenv("TEMP"));
188
189 #ifdef P_tmpdir
190         if(tmpdir == NULL)
191                 tmpdir = try_dir(P_tmpdir);
192 #endif
193
194         if(tmpdir == NULL)
195                 tmpdir = try_dir("/var/tmp");
196         if(tmpdir == NULL)
197                 tmpdir = try_dir("/usr/tmp");
198         if(tmpdir == NULL)
199                 tmpdir = try_dir("/tmp");
200
201         if(tmpdir == NULL)
202                 tmpdir = ".";
203
204         return tmpdir;
205 }
206
207 /**
208  * an own version of tmpnam, which: writes in a buffer, appends a user specified
209  * suffix, emits no warnings during linking (like glibc/gnu ld do for tmpnam)...
210  */
211 static FILE *make_temp_file(char *buffer, size_t buflen,
212                             const char *prefix, const char *suffix)
213 {
214         const char *tempdir = get_tempdir();
215
216         /* oh well... mkstemp doesn't accept a suffix after XXXXXX... */
217         (void) suffix;
218         suffix = "";
219
220         snprintf(buffer, buflen, "%s/%sXXXXXX%s", tempdir, prefix, suffix);
221
222         int fd = mkstemp(buffer);
223         if(fd == -1) {
224                 fprintf(stderr, "couldn't create temporary file: %s\n",
225                         strerror(errno));
226                 exit(1);
227         }
228         FILE *out = fdopen(fd, "w");
229         if(out == NULL) {
230                 fprintf(stderr, "couldn't create temporary file FILE*\n");
231                 exit(1);
232         }
233
234         return out;
235 }
236
237 /**
238  * Do the necessary lowering for compound parameters.
239  */
240 void lower_compound_params(void)
241 {
242         lower_params_t params;
243
244         params.def_ptr_alignment    = 4;
245         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
246         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
247         params.find_pointer_type    = NULL;
248         params.ret_compound_in_regs = NULL;
249         lower_calls_with_compounds(&params);
250 }
251
252 static void create_firm_prog(translation_unit_t *unit)
253 {
254         translation_unit_to_firm(unit);
255
256         //dump_globals_as_text(dump_verbosity_max, "-globals");
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         Compile,
275         CompileDump,
276         CompileAssemble,
277         CompileAssembleLink,
278         LexTest,
279         PrintAst,
280         PrintFluffy
281 } compile_mode_t;
282
283 static void usage(const char *argv0)
284 {
285         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
286 }
287
288 int main(int argc, char **argv)
289 {
290         initialize_firm();
291
292         init_symbol_table();
293         init_tokens();
294         init_types();
295         init_typehash();
296         init_lexer();
297         init_ast();
298         init_parser();
299         init_ast2firm();
300
301         const char *input        = NULL;
302         const char *outname      = NULL;
303         const char *dumpfunction = NULL;
304         compile_mode_t mode = CompileAssembleLink;
305
306         for(int i = 1; i < argc; ++i) {
307                 const char *arg = argv[i];
308                 if(strncmp(arg, "-o", 2) == 0) {
309                         outname = &arg[2];
310                         if(outname[0] == '\0') {
311                                 ++i;
312                                 if(i >= argc) {
313                                         usage(argv[0]);
314                                         return 1;
315                                 }
316                                 outname = argv[i];
317                         }
318                 } else if(strcmp(arg, "-c") == 0) {
319                         mode = CompileAssemble;
320                 } else if(strcmp(arg, "-S") == 0) {
321                         mode = Compile;
322                 } else if(strcmp(arg, "--lextest") == 0) {
323                         mode = LexTest;
324                 } else if(strcmp(arg, "--print-ast") == 0) {
325                         mode = PrintAst;
326                 } else if(strcmp(arg, "--print-fluffy") == 0) {
327                         mode = PrintFluffy;
328                 } else if(strcmp(arg, "--dump") == 0) {
329                         do_dump = true;
330                 } else if(strcmp(arg, "--dump-function") == 0) {
331                         ++i;
332                         if(i >= argc) {
333                                 usage(argv[0]);
334                                 return 1;
335                         }
336                         dumpfunction = argv[i];
337                         mode         = CompileDump;
338                 } else if(strcmp(arg, "-v") == 0) {
339                         verbose = 1;
340                 } else if(arg[0] == '-' && arg[1] == 'f') {
341                         const char *opt = &arg[2];
342                         if(opt[0] == 0) {
343                                 ++i;
344                                 if(i >= argc) {
345                                         usage(argv[0]);
346                                         return 1;
347                                 }
348                                 opt = argv[i];
349                                 if(opt[0] == '-') {
350                                         usage(argv[0]);
351                                         return 1;
352                                 }
353                         }
354                         int res = firm_option(opt);
355                         if (res == 0) {
356                                 fprintf(stderr, "Error: unknown Firm option %s\n", opt);
357                                 usage(argv[0]);
358                                 return 1;
359                         } else if (res == -1) { /* help option */
360                                 exit(0);
361                         }
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                         }
384                 } else if(arg[0] == '-') {
385                         if (arg[1] == '\0') {
386                                 input = "-";
387                         } else if (arg[1] == 'D' ||
388                                         arg[1] == 'O' ||
389                                         arg[1] == 'f' ||
390                                         arg[1] == 'W' ||
391                                         arg[1] == 'g' ||
392                                         strncmp(arg + 1, "std=", 4) == 0) {
393                                 fprintf(stderr, "Warning: Ignoring option '%s'\n", arg);
394                         } else {
395                                 usage(argv[0]);
396                                 return 1;
397                         }
398                 } else {
399                         if(input != NULL) {
400                                 fprintf(stderr, "Error: multiple input files specified\n");
401                                 usage(argv[0]);
402                                 return 1;
403                         } else {
404                                 input = arg;
405                         }
406                 }
407         }
408
409         FILE *out;
410         char  outnamebuf[4096];
411         if(outname == NULL) {
412                 switch(mode) {
413                 case PrintAst:
414                 case PrintFluffy:
415                 case LexTest:
416                         break;
417                 case Compile:
418                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".s");
419                         outname = outnamebuf;
420                         break;
421                 case CompileAssemble:
422                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".o");
423                         outname = outnamebuf;
424                         break;
425                 case CompileDump:
426                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
427                                         ".vcg");
428                         outname = outnamebuf;
429                         break;
430                 case CompileAssembleLink:
431                         outname = "a.out";
432                         break;
433                 }
434                 assert(outname != NULL);
435         }
436
437         if(strcmp(outname, "-") == 0) {
438                 out = stdout;
439         } else {
440                 out = fopen(outname, "w");
441                 if(out == NULL) {
442                         fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
443                                 strerror(errno));
444                         return 1;
445                 }
446         }
447
448         FILE *in;
449         if(input == NULL) {
450                 fprintf(stderr, "%s: no input files\n", argv[0]);
451                 return 1;
452         } else if(strcmp(input, "-") == 0) {
453                 in    = stdin;
454                 input = "<stdin>";
455         } else {
456                 in = fopen(input, "r");
457                 if(in == NULL) {
458                         fprintf(stderr, "Couldn't open '%s': %s\n", input, strerror(errno));
459                         return 1;
460                 }
461         }
462
463         if(mode == LexTest) {
464                 lextest(in, input);
465                 fclose(in);
466                 return 0;
467         }
468
469         FILE *preprocessed_in = preprocess(in, input);
470         translation_unit_t *const unit = do_parsing(preprocessed_in, input);
471         pclose(preprocessed_in);
472         if(unit == NULL)
473                 return 1;
474
475         if(mode == PrintAst) {
476                 ast_set_output(out);
477                 print_ast(unit);
478                 return 0;
479         }
480         if(mode == PrintFluffy) {
481                 write_fluffy_decls(out, unit);
482         }
483
484         gen_firm_init();
485         create_firm_prog(unit);
486
487         FILE *asm_out;
488         char  asm_tempfile[1024];
489         if(mode == CompileDump) {
490                 asm_out = NULL;
491                 firm_be_opt.selection = BE_NONE;
492         } else if(mode == Compile) {
493                 asm_out = out;
494         } else {
495                 asm_out
496                         = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "cc", ".s");
497         }
498         gen_firm_finish(asm_out, input, /*c_mode=*/1, /*firm_const_exists=*/0);
499
500         if(mode == CompileDump) {
501                 /* find irg */
502                 ident    *id     = new_id_from_str(dumpfunction);
503                 ir_graph *irg    = NULL;
504                 int       n_irgs = get_irp_n_irgs();
505                 for(int i = 0; i < n_irgs; ++i) {
506                         ir_graph *tirg   = get_irp_irg(i);
507                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
508                         if(irg_id == id) {
509                                 irg = tirg;
510                                 break;
511                         }
512                 }
513
514                 if(irg == NULL) {
515                         fprintf(stderr, "No graph for function '%s' found\n", dumpfunction);
516                         return 1;
517                 }
518
519                 dump_ir_block_graph_file(irg, out);
520                 fclose(out);
521                 return 0;
522         }
523
524         fclose(asm_out);
525
526         /* assemble assembler and create object file */
527         char obj_tfile[1024];
528         if(mode == CompileAssemble || mode == CompileAssembleLink) {
529                 const char *obj_outfile;
530                 if(mode == CompileAssemble) {
531                         fclose(out);
532                         obj_outfile = outname;
533                 } else {
534                         FILE *tempf
535                                 = make_temp_file(obj_tfile, sizeof(obj_tfile), "cc", ".o");
536                         fclose(tempf);
537                         obj_outfile = obj_tfile;
538                 }
539
540                 assemble(obj_outfile, asm_tempfile);
541         }
542
543         /* link object file */
544         if(mode == CompileAssembleLink) {
545                 do_link(outname, obj_tfile);
546         }
547
548         exit_ast2firm();
549         exit_parser();
550         exit_ast();
551         exit_lexer();
552         exit_typehash();
553         exit_types();
554         exit_tokens();
555         exit_symbol_table();
556         return 0;
557 }