57f52b3a9007ed25faeaaa946443473564198510
[cparser] / driver / firm_codegen.c
1 /**
2  * @file firm_codegen.c
3  *
4  * Compile when BACK_END_IS_CP_FIRM_BE is defined
5  *
6  * (C) 2005  Michael Beck  beck@ipd.info.uni-karlsruhe.de
7  *
8  * $Id$
9  */
10 #include <string.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <libfirm/dbginfo.h>
14 #include <libfirm/adt/xmalloc.h>
15 #include <libfirm/be.h>
16
17 #ifdef FIRM2C_BACKEND
18 #include "cbackend.h"
19 #endif
20
21 #include "firm_codegen.h"
22 #include "firm_cmdline.h"
23 #include "firm_opt.h"
24 #include "firm_timing.h"
25
26 extern void be_main(FILE *f, const char *asm_file_name);
27
28 /**
29  * Substitutes '.c' for '.s'.
30  */
31 static char *generate_asm_file_name(const char *file_name) {
32   int len             = strlen(file_name);
33   char *asm_file_name = xmalloc(len + 5);   /* .asm + \0 */
34
35   strcpy(asm_file_name, file_name);
36   if (asm_file_name[len - 2] == '.' && asm_file_name[len - 1] == 'c')
37     asm_file_name[len - 2] = '\0';
38
39   switch (firm_be_opt.selection) {
40 #ifdef FIRM2C_BACKEND
41   case BE_FIRM2C:
42     strncat(asm_file_name, ".s.c", 4);
43     break;
44 #endif
45
46 #ifdef FIRM_BACKEND
47   case BE_FIRM_BE:
48     strncat(asm_file_name, ".s", 4);
49     break;
50 #endif
51   }
52
53   return asm_file_name;
54 }  /* generate_asm_file_name */
55
56 /**
57  * Calls the specified backend.
58  * Code is written to file <file_name> ('.c' is substituted for '.asm')
59  */
60 void do_codegen(FILE *out, const char *file_name) {
61   FILE *close_out = NULL;
62   if (out == NULL) {
63     char *asm_file_name = generate_asm_file_name(file_name);
64
65     if ((out = fopen(asm_file_name, "w")) == NULL) {
66       fprintf(stderr, "Could not open output file %s\n", asm_file_name);
67       exit(1);
68     }
69     free(asm_file_name);
70     close_out = out;
71   }
72
73   switch (firm_be_opt.selection) {
74 #ifdef FIRM2C_BACKEND
75   case BE_FIRM2C:
76     timer_push(TV_FIRM2C_BE);
77       cbackend_set_debug_retrieve(dbg_retrieve);
78       generate_code_file(out);
79     timer_pop();
80     break;
81 #endif
82
83 #ifdef FIRM_BACKEND
84   case BE_FIRM_BE:
85     timer_push(TV_FIRM_BE);
86       ir_set_debug_retrieve(dbg_retrieve);
87       be_main(out, file_name);
88     timer_pop();
89     break;
90 #endif
91
92   default:
93     fprintf(stderr, "Fatal: Unknown backend %d\n", firm_be_opt.selection);
94   } /* switch (firm_be_opt.selection) */
95
96   if (close_out)
97     fclose(close_out);
98 } /* do_codegen() */