bechordal_draw: Remove the attributes max_color and max_step from struct block_dims.
[libfirm] / ir / be / bemain.c
1 /*
2  * This file is part of libFirm.
3  * Copyright (C) 2012 University of Karlsruhe.
4  */
5
6 /**
7  * @file
8  * @brief       Main Backend driver.
9  * @author      Sebastian Hack
10  * @date        25.11.2004
11  */
12 #include "config.h"
13
14 #include <stdarg.h>
15 #include <stdio.h>
16
17 #include "lc_opts.h"
18 #include "lc_opts_enum.h"
19
20 #include "obst.h"
21 #include "bitset.h"
22 #include "statev.h"
23 #include "irprog.h"
24 #include "irgopt.h"
25 #include "irgraph.h"
26 #include "irdump.h"
27 #include "irdom_t.h"
28 #include "iredges_t.h"
29 #include "irloop_t.h"
30 #include "irtools.h"
31 #include "irverify.h"
32 #include "irprintf.h"
33 #include "iroptimize.h"
34 #include "firmstat.h"
35 #include "execfreq_t.h"
36 #include "irprofile.h"
37 #include "irpass_t.h"
38 #include "ircons.h"
39
40 #include "bearch.h"
41 #include "be_t.h"
42 #include "begnuas.h"
43 #include "bemodule.h"
44 #include "beutil.h"
45 #include "benode.h"
46 #include "beirgmod.h"
47 #include "besched.h"
48 #include "belistsched.h"
49 #include "belive_t.h"
50 #include "bera.h"
51 #include "bechordal_t.h"
52 #include "beifg.h"
53 #include "becopyopt.h"
54 #include "becopystat.h"
55 #include "bessadestr.h"
56 #include "beabi.h"
57 #include "belower.h"
58 #include "bestat.h"
59 #include "beverify.h"
60 #include "beirg.h"
61 #include "bestack.h"
62 #include "beemitter.h"
63
64 #define NEW_ID(s) new_id_from_chars(s, sizeof(s) - 1)
65
66 /* options visible for anyone */
67 be_options_t be_options = {
68         DUMP_NONE,                         /* dump flags */
69         BE_TIME_OFF,                       /* no timing */
70         false,                             /* profile_generate */
71         false,                             /* profile_use */
72         0,                                 /* try to omit frame pointer */
73         0,                                 /* create PIC code */
74         BE_VERIFY_WARN,                    /* verification level: warn */
75         "",                                /* ilp server */
76         "",                                /* ilp solver */
77         0,                                 /* enable statistic event dumping */
78         "",                                /* print stat events */
79         1,                                 /* verbose assembler output */
80 };
81
82 /* back end instruction set architecture to use */
83 static const arch_isa_if_t *isa_if = NULL;
84
85 /* possible dumping options */
86 static const lc_opt_enum_mask_items_t dump_items[] = {
87         { "none",       DUMP_NONE },
88         { "initial",    DUMP_INITIAL },
89         { "abi",        DUMP_ABI    },
90         { "sched",      DUMP_SCHED  },
91         { "prepared",   DUMP_PREPARED },
92         { "regalloc",   DUMP_RA },
93         { "final",      DUMP_FINAL },
94         { "be",         DUMP_BE },
95         { "all",        2 * DUMP_BE - 1 },
96         { NULL,         0 }
97 };
98
99 /* verify options. */
100 static const lc_opt_enum_int_items_t verify_items[] = {
101         { "off",    BE_VERIFY_OFF    },
102         { "warn",   BE_VERIFY_WARN   },
103         { "assert", BE_VERIFY_ASSERT },
104         { NULL,     0 }
105 };
106
107 static lc_opt_enum_mask_var_t dump_var = {
108         &be_options.dump_flags, dump_items
109 };
110
111 static lc_opt_enum_int_var_t verify_var = {
112         &be_options.verify_option, verify_items
113 };
114
115 static const lc_opt_table_entry_t be_main_options[] = {
116         LC_OPT_ENT_ENUM_MASK("dump",       "dump irg on several occasions",                       &dump_var),
117         LC_OPT_ENT_BOOL     ("omitfp",     "omit frame pointer",                                  &be_options.omit_fp),
118         LC_OPT_ENT_BOOL     ("pic",        "create PIC code",                                     &be_options.pic),
119         LC_OPT_ENT_ENUM_INT ("verify",     "verify the backend irg",                              &verify_var),
120         LC_OPT_ENT_BOOL     ("time",       "get backend timing statistics",                       &be_options.timing),
121         LC_OPT_ENT_BOOL     ("profilegenerate", "instrument the code for execution count profiling",   &be_options.opt_profile_generate),
122         LC_OPT_ENT_BOOL     ("profileuse",      "use existing profile data",                           &be_options.opt_profile_use),
123         LC_OPT_ENT_BOOL     ("statev",     "dump statistic events",                               &be_options.statev),
124         LC_OPT_ENT_STR      ("filtev",     "filter for stat events (regex if support is active",  &be_options.filtev),
125         LC_OPT_ENT_BOOL     ("verboseasm", "enable verbose assembler output",                     &be_options.verbose_asm),
126
127         LC_OPT_ENT_STR("ilp.server", "the ilp server name", &be_options.ilp_server),
128         LC_OPT_ENT_STR("ilp.solver", "the ilp solver name", &be_options.ilp_solver),
129         LC_OPT_LAST
130 };
131
132 static be_module_list_entry_t *isa_ifs         = NULL;
133 static bool                    isa_initialized = false;
134
135 asm_constraint_flags_t asm_constraint_flags[256];
136
137 static void initialize_isa(void)
138 {
139         if (isa_initialized)
140                 return;
141         isa_if->init();
142         isa_initialized = true;
143 }
144
145 static void finish_isa(void)
146 {
147         if (isa_initialized) {
148                 isa_if->finish();
149                 isa_initialized = false;
150         }
151 }
152
153 void be_init_default_asm_constraint_flags(void)
154 {
155         asm_constraint_flags['?'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
156         asm_constraint_flags['!'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
157         asm_constraint_flags['&'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT
158                 | ASM_CONSTRAINT_FLAG_MODIFIER_EARLYCLOBBER;
159         asm_constraint_flags['%'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT
160                 | ASM_CONSTRAINT_FLAG_MODIFIER_COMMUTATIVE;
161         asm_constraint_flags['!'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
162
163         asm_constraint_flags['='] = ASM_CONSTRAINT_FLAG_MODIFIER_WRITE
164                 | ASM_CONSTRAINT_FLAG_MODIFIER_NO_READ;
165         asm_constraint_flags['+'] = ASM_CONSTRAINT_FLAG_MODIFIER_READ
166                 | ASM_CONSTRAINT_FLAG_MODIFIER_WRITE;
167
168         asm_constraint_flags['i'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
169         asm_constraint_flags['s'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
170         asm_constraint_flags['E'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
171         asm_constraint_flags['F'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
172         asm_constraint_flags['G'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
173         asm_constraint_flags['H'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
174         asm_constraint_flags['I'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
175         asm_constraint_flags['J'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
176         asm_constraint_flags['K'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
177         asm_constraint_flags['L'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
178         asm_constraint_flags['M'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
179         asm_constraint_flags['N'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
180         asm_constraint_flags['O'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
181         asm_constraint_flags['P'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
182
183         asm_constraint_flags['m'] = ASM_CONSTRAINT_FLAG_SUPPORTS_MEMOP;
184         asm_constraint_flags['o'] = ASM_CONSTRAINT_FLAG_SUPPORTS_MEMOP;
185         asm_constraint_flags['V'] = ASM_CONSTRAINT_FLAG_SUPPORTS_MEMOP;
186         asm_constraint_flags['<'] = ASM_CONSTRAINT_FLAG_SUPPORTS_MEMOP;
187         asm_constraint_flags['>'] = ASM_CONSTRAINT_FLAG_SUPPORTS_MEMOP;
188
189         asm_constraint_flags['p'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
190         asm_constraint_flags['0'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
191         asm_constraint_flags['1'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
192         asm_constraint_flags['2'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
193         asm_constraint_flags['3'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
194         asm_constraint_flags['4'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
195         asm_constraint_flags['5'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
196         asm_constraint_flags['6'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
197         asm_constraint_flags['7'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
198         asm_constraint_flags['8'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
199         asm_constraint_flags['9'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
200
201         asm_constraint_flags['X'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER
202                 | ASM_CONSTRAINT_FLAG_SUPPORTS_MEMOP
203                 | ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
204
205         /* these should have been catched by the parsing code already */
206         asm_constraint_flags['#']  = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
207         asm_constraint_flags['*']  = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
208         asm_constraint_flags[' ']  = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
209         asm_constraint_flags['\t'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
210         asm_constraint_flags['\n'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
211         asm_constraint_flags['\r'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
212 }
213
214 asm_constraint_flags_t be_parse_asm_constraints(const char *constraint)
215 {
216         asm_constraint_flags_t  flags = ASM_CONSTRAINT_FLAG_NONE;
217         const char             *c;
218         asm_constraint_flags_t  tflags;
219
220         initialize_isa();
221
222         for (c = constraint; *c != '\0'; ++c) {
223                 switch (*c) {
224                 case '#':
225                         /* 'comment' stuff */
226                         while (*c != 0 && *c != ',')
227                                 ++c;
228                         break;
229                 case '*':
230                         /* 'comment' character */
231                         ++c;
232                         break;
233                 case ' ':
234                 case '\t':
235                 case '\n':
236                 case '\r':
237                         break;
238                 default:
239                         tflags = asm_constraint_flags[(int) *c];
240                         if (tflags != 0) {
241                                 flags |= tflags;
242                         } else {
243                                 flags |= isa_if->parse_asm_constraint(&c);
244                         }
245                         break;
246                 }
247         }
248
249         if ((
250                 flags & ASM_CONSTRAINT_FLAG_MODIFIER_WRITE &&
251                 flags & ASM_CONSTRAINT_FLAG_MODIFIER_NO_WRITE
252             ) || (
253                 flags & ASM_CONSTRAINT_FLAG_MODIFIER_READ &&
254                 flags & ASM_CONSTRAINT_FLAG_MODIFIER_NO_READ
255             )) {
256                 flags |= ASM_CONSTRAINT_FLAG_INVALID;
257         }
258         if (!(flags & (ASM_CONSTRAINT_FLAG_MODIFIER_READ     |
259                        ASM_CONSTRAINT_FLAG_MODIFIER_WRITE    |
260                        ASM_CONSTRAINT_FLAG_MODIFIER_NO_WRITE |
261                        ASM_CONSTRAINT_FLAG_MODIFIER_NO_READ)
262             )) {
263                 flags |= ASM_CONSTRAINT_FLAG_MODIFIER_READ;
264         }
265
266         return flags;
267 }
268
269 int be_is_valid_clobber(const char *clobber)
270 {
271         initialize_isa();
272
273         /* memory is a valid clobber. (the frontend has to detect this case too,
274          * because it has to add memory edges to the asm) */
275         if (strcmp(clobber, "memory") == 0)
276                 return 1;
277         /* cc (condition code) is always valid */
278         if (strcmp(clobber, "cc") == 0)
279                 return 1;
280
281         return isa_if->is_valid_clobber(clobber);
282 }
283
284 void be_register_isa_if(const char *name, const arch_isa_if_t *isa)
285 {
286         if (isa_if == NULL)
287                 isa_if = isa;
288
289         be_add_module_to_list(&isa_ifs, name, (void*) isa);
290 }
291
292 static void be_opt_register(void)
293 {
294         lc_opt_entry_t *be_grp;
295         static int run_once = 0;
296
297         if (run_once)
298                 return;
299         run_once = 1;
300
301         be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
302         lc_opt_add_table(be_grp, be_main_options);
303
304         be_add_module_list_opt(be_grp, "isa", "the instruction set architecture",
305                                &isa_ifs, (void**) &isa_if);
306
307         be_init_modules();
308 }
309
310 /* Parse one argument. */
311 int be_parse_arg(const char *arg)
312 {
313         lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
314         if (strcmp(arg, "help") == 0 || (arg[0] == '?' && arg[1] == '\0')) {
315                 lc_opt_print_help_for_entry(be_grp, '-', stdout);
316                 return -1;
317         }
318         return lc_opt_from_single_arg(be_grp, NULL, arg, NULL);
319 }
320
321 /* Perform schedule verification if requested. */
322 static void be_sched_verify(ir_graph *irg, int verify_opt)
323 {
324         if (verify_opt == BE_VERIFY_WARN) {
325                 be_verify_schedule(irg);
326         } else if (verify_opt == BE_VERIFY_ASSERT) {
327                 assert(be_verify_schedule(irg) && "Schedule verification failed.");
328         }
329 }
330
331 /* Initialize the Firm backend. Must be run first in init_firm()! */
332 void firm_be_init(void)
333 {
334         be_opt_register();
335         be_init_modules();
336 }
337
338 /* Finalize the Firm backend. */
339 void firm_be_finish(void)
340 {
341         finish_isa();
342         be_quit_modules();
343 }
344
345 /* Returns the backend parameter */
346 const backend_params *be_get_backend_param(void)
347 {
348         initialize_isa();
349         return isa_if->get_params();
350 }
351
352 int be_is_big_endian(void)
353 {
354         return be_get_backend_param()->byte_order_big_endian;
355 }
356
357 unsigned be_get_machine_size(void)
358 {
359         return be_get_backend_param()->machine_size;
360 }
361
362 ir_mode *be_get_mode_float_arithmetic(void)
363 {
364         return be_get_backend_param()->mode_float_arithmetic;
365 }
366
367 ir_type *be_get_type_long_long(void)
368 {
369         return be_get_backend_param()->type_long_long;
370 }
371
372 ir_type *be_get_type_unsigned_long_long(void)
373 {
374         return be_get_backend_param()->type_unsigned_long_long;
375 }
376
377 ir_type *be_get_type_long_double(void)
378 {
379         return be_get_backend_param()->type_long_double;
380 }
381
382 /**
383  * Initializes the main environment for the backend.
384  *
385  * @param env          an empty environment
386  * @param file_handle  the file handle where the output will be written to
387  */
388 static be_main_env_t *be_init_env(be_main_env_t *const env, char const *const compilation_unit_name)
389 {
390         memset(env, 0, sizeof(*env));
391         env->ent_trampoline_map   = pmap_create();
392         env->pic_trampolines_type = new_type_segment(NEW_ID("$PIC_TRAMPOLINE_TYPE"), tf_none);
393         env->ent_pic_symbol_map   = pmap_create();
394         env->pic_symbols_type     = new_type_segment(NEW_ID("$PIC_SYMBOLS_TYPE"), tf_none);
395         env->cup_name             = compilation_unit_name;
396         env->arch_env             = isa_if->begin_codegeneration();
397
398         set_class_final(env->pic_trampolines_type, 1);
399
400         memset(asm_constraint_flags, 0, sizeof(asm_constraint_flags));
401
402         return env;
403 }
404
405 /**
406  * Called when the be_main_env_t can be destroyed.
407  */
408 static void be_done_env(be_main_env_t *env)
409 {
410         pmap_destroy(env->ent_trampoline_map);
411         pmap_destroy(env->ent_pic_symbol_map);
412         free_type(env->pic_trampolines_type);
413         free_type(env->pic_symbols_type);
414 }
415
416 /**
417  * A wrapper around a firm dumper. Dumps only, if
418  * flags are enabled.
419  *
420  * @param mask    a bitmask containing the reason what will be dumped
421  * @param irg     the IR graph to dump
422  * @param suffix  the suffix for the dumper
423  * @param dumper  the dumper to be called
424  */
425 static void dump(int mask, ir_graph *irg, const char *suffix)
426 {
427         if (be_options.dump_flags & mask)
428                 dump_ir_graph(irg, suffix);
429 }
430
431 /**
432  * Prepare a backend graph for code generation and initialize its irg
433  */
434 static void initialize_birg(be_irg_t *birg, ir_graph *irg, be_main_env_t *env)
435 {
436         /* don't duplicate locals in backend when dumping... */
437         ir_remove_dump_flags(ir_dump_flag_consts_local);
438
439         dump(DUMP_INITIAL, irg, "begin");
440
441         irg->be_data = birg;
442
443         memset(birg, 0, sizeof(*birg));
444         birg->main_env = env;
445         obstack_init(&birg->obst);
446         birg->lv = be_liveness_new(irg);
447
448         edges_deactivate(irg);
449         edges_activate(irg);
450
451         /* set the current graph (this is important for several firm functions) */
452         current_ir_graph = irg;
453
454         /* we do this before critical edge split. As this produces less returns,
455            because sometimes (= 164.gzip) multiple returns are slower */
456         normalize_n_returns(irg);
457
458         /* Remove critical edges */
459         remove_critical_cf_edges_ex(irg, /*ignore_exception_edges=*/0);
460
461         /* For code generation all unreachable code and Bad nodes should be gone */
462         remove_unreachable_code(irg);
463         remove_bads(irg);
464
465         /* Ensure, that the ir_edges are computed. */
466         assure_edges(irg);
467
468         be_info_init_irg(irg);
469
470         dump(DUMP_INITIAL, irg, "prepared");
471 }
472
473 int be_timing;
474
475 static const char *get_timer_name(be_timer_id_t id)
476 {
477         switch (id) {
478         case T_ABI:            return "abi";
479         case T_CODEGEN:        return "codegen";
480         case T_RA_PREPARATION: return "ra_preparation";
481         case T_SCHED:          return "sched";
482         case T_CONSTR:         return "constr";
483         case T_FINISH:         return "finish";
484         case T_EMIT:           return "emit";
485         case T_VERIFY:         return "verify";
486         case T_OTHER:          return "other";
487         case T_HEIGHTS:        return "heights";
488         case T_LIVE:           return "live";
489         case T_EXECFREQ:       return "execfreq";
490         case T_SSA_CONSTR:     return "ssa_constr";
491         case T_RA_EPILOG:      return "ra_epilog";
492         case T_RA_CONSTR:      return "ra_constr";
493         case T_RA_SPILL:       return "ra_spill";
494         case T_RA_SPILL_APPLY: return "ra_spill_apply";
495         case T_RA_COLOR:       return "ra_color";
496         case T_RA_IFG:         return "ra_ifg";
497         case T_RA_COPYMIN:     return "ra_copymin";
498         case T_RA_SSA:         return "ra_ssa";
499         case T_RA_OTHER:       return "ra_other";
500         }
501         return "unknown";
502 }
503 ir_timer_t *be_timers[T_LAST+1];
504
505 void be_lower_for_target(void)
506 {
507         size_t i;
508
509         initialize_isa();
510
511         isa_if->lower_for_target();
512         /* set the phase to low */
513         for (i = get_irp_n_irgs(); i > 0;) {
514                 ir_graph *irg = get_irp_irg(--i);
515                 assert(!irg_is_constrained(irg, IR_GRAPH_CONSTRAINT_TARGET_LOWERED));
516                 add_irg_constraints(irg, IR_GRAPH_CONSTRAINT_TARGET_LOWERED);
517         }
518 }
519
520 /**
521  * The Firm backend main loop.
522  * Do architecture specific lowering for all graphs
523  * and call the architecture specific code generator.
524  *
525  * @param file_handle   the file handle the output will be written to
526  * @param cup_name      name of the compilation unit
527  */
528 static void be_main_loop(FILE *file_handle, const char *cup_name)
529 {
530         static const char suffix[] = ".prof";
531
532         size_t        i;
533         size_t        num_irgs;
534         size_t        num_birgs;
535         be_main_env_t env;
536         char          prof_filename[256];
537         be_irg_t      *birgs;
538         arch_env_t    *arch_env;
539
540         be_timing = (be_options.timing == BE_TIME_ON);
541
542         /* perform target lowering if it didn't happen yet */
543         if (get_irp_n_irgs() > 0 && !irg_is_constrained(get_irp_irg(0), IR_GRAPH_CONSTRAINT_TARGET_LOWERED))
544                 be_lower_for_target();
545
546         if (be_timing) {
547                 for (i = 0; i < T_LAST+1; ++i) {
548                         be_timers[i] = ir_timer_new();
549                 }
550         }
551
552         be_init_env(&env, cup_name);
553
554         be_emit_init(file_handle);
555         be_gas_begin_compilation_unit(&env);
556
557         arch_env = env.arch_env;
558
559         /* we might need 1 birg more for instrumentation constructor */
560         num_irgs = get_irp_n_irgs();
561         birgs    = ALLOCAN(be_irg_t, num_irgs + 1);
562
563         be_info_init();
564
565         /* First: initialize all birgs */
566         num_birgs = 0;
567         for (i = 0; i < num_irgs; ++i) {
568                 ir_graph  *irg    = get_irp_irg(i);
569                 ir_entity *entity = get_irg_entity(irg);
570                 if (get_entity_linkage(entity) & IR_LINKAGE_NO_CODEGEN)
571                         continue;
572                 initialize_birg(&birgs[num_birgs++], irg, &env);
573         }
574         arch_env_handle_intrinsics(arch_env);
575
576         /*
577                 Get the filename for the profiling data.
578                 Beware: '\0' is already included in sizeof(suffix)
579         */
580         sprintf(prof_filename, "%.*s%s",
581                 (int)(sizeof(prof_filename) - sizeof(suffix)), cup_name, suffix);
582
583         bool have_profile = false;
584         if (be_options.opt_profile_use) {
585                 bool res = ir_profile_read(prof_filename);
586                 if (!res) {
587                         fprintf(stderr, "Warning: Couldn't read profile data '%s'\n",
588                                 prof_filename);
589                 } else {
590                         ir_create_execfreqs_from_profile();
591                         ir_profile_free();
592                         have_profile = true;
593                 }
594         }
595
596         if (num_birgs > 0 && be_options.opt_profile_generate) {
597                 ir_graph *const prof_init_irg = ir_profile_instrument(prof_filename);
598                 assert(prof_init_irg->be_data == NULL);
599                 initialize_birg(&birgs[num_birgs], prof_init_irg, &env);
600                 num_birgs++;
601                 num_irgs++;
602                 assert(num_irgs == get_irp_n_irgs());
603         }
604
605         for (be_timer_id_t t = T_FIRST; t < T_LAST+1; ++t) {
606                 ir_timer_init_parent(be_timers[t]);
607         }
608         if (!have_profile) {
609                 be_timer_push(T_EXECFREQ);
610                 for (i = 0; i < num_irgs; ++i) {
611                         ir_graph *irg = get_irp_irg(i);
612                         ir_estimate_execfreq(irg);
613                 }
614                 be_timer_pop(T_EXECFREQ);
615         }
616
617         /* For all graphs */
618         for (i = 0; i < num_irgs; ++i) {
619                 ir_graph  *const irg    = get_irp_irg(i);
620                 ir_entity *const entity = get_irg_entity(irg);
621                 if (get_entity_linkage(entity) & IR_LINKAGE_NO_CODEGEN)
622                         continue;
623
624                 /* set the current graph (this is important for several firm functions) */
625                 current_ir_graph = irg;
626
627                 if (stat_ev_enabled) {
628                         stat_ev_ctx_push_fmt("bemain_irg", "%+F", irg);
629                         stat_ev_ull("bemain_insns_start", be_count_insns(irg));
630                         stat_ev_ull("bemain_blocks_start", be_count_blocks(irg));
631                 }
632
633                 /* stop and reset timers */
634                 be_timer_push(T_OTHER);
635
636                 /* Verify the initial graph */
637                 be_timer_push(T_VERIFY);
638                 if (be_options.verify_option == BE_VERIFY_WARN) {
639                         irg_verify(irg, VERIFY_ENFORCE_SSA);
640                 } else if (be_options.verify_option == BE_VERIFY_ASSERT) {
641                         assert(irg_verify(irg, VERIFY_ENFORCE_SSA) && "irg verification failed");
642                 }
643                 be_timer_pop(T_VERIFY);
644
645                 /* get a code generator for this graph. */
646                 if (arch_env->impl->init_graph)
647                         arch_env->impl->init_graph(irg);
648
649                 /* some transformations need to be done before abi introduce */
650                 if (arch_env->impl->before_abi != NULL)
651                         arch_env->impl->before_abi(irg);
652
653                 /* implement the ABI conventions. */
654                 if (!arch_env->custom_abi) {
655                         be_timer_push(T_ABI);
656                         be_abi_introduce(irg);
657                         be_timer_pop(T_ABI);
658                         dump(DUMP_ABI, irg, "abi");
659                 }
660
661                 /* We can't have Bad-blocks or critical edges in the backend.
662                  * Before removing Bads, we remove unreachable code. */
663                 optimize_graph_df(irg);
664                 remove_critical_cf_edges(irg);
665                 remove_bads(irg);
666
667                 /* We often have dead code reachable through out-edges here. So for
668                  * now we rebuild edges (as we need correct user count for code
669                  * selection) */
670                 edges_deactivate(irg);
671                 edges_activate(irg);
672
673                 dump(DUMP_PREPARED, irg, "before-code-selection");
674
675                 /* perform codeselection */
676                 be_timer_push(T_CODEGEN);
677                 if (arch_env->impl->prepare_graph != NULL)
678                         arch_env->impl->prepare_graph(irg);
679                 be_timer_pop(T_CODEGEN);
680
681                 dump(DUMP_PREPARED, irg, "code-selection");
682
683                 /* disabled for now, fails for EmptyFor.c and XXEndless.c */
684                 /* be_live_chk_compare(irg); */
685
686                 /* schedule the irg */
687                 be_timer_push(T_SCHED);
688                 be_schedule_graph(irg);
689                 be_timer_pop(T_SCHED);
690
691                 dump(DUMP_SCHED, irg, "sched");
692
693                 /* check schedule */
694                 be_timer_push(T_VERIFY);
695                 be_sched_verify(irg, be_options.verify_option);
696                 be_timer_pop(T_VERIFY);
697
698                 /* introduce patterns to assure constraints */
699                 be_timer_push(T_CONSTR);
700                 /* we switch off optimizations here, because they might cause trouble */
701                 optimization_state_t state;
702                 save_optimization_state(&state);
703                 set_optimize(0);
704                 set_opt_cse(0);
705
706                 /* add Keeps for should_be_different constrained nodes  */
707                 /* beware: needs schedule due to usage of be_ssa_constr */
708                 assure_constraints(irg);
709                 be_timer_pop(T_CONSTR);
710
711                 dump(DUMP_SCHED, irg, "assured");
712
713                 /* stuff needs to be done after scheduling but before register allocation */
714                 be_timer_push(T_RA_PREPARATION);
715                 if (arch_env->impl->before_ra != NULL)
716                         arch_env->impl->before_ra(irg);
717                 be_timer_pop(T_RA_PREPARATION);
718
719                 /* connect all stack modifying nodes together (see beabi.c) */
720                 be_timer_push(T_ABI);
721                 be_abi_fix_stack_nodes(irg);
722                 be_timer_pop(T_ABI);
723
724                 dump(DUMP_SCHED, irg, "fix_stack");
725
726                 /* check schedule */
727                 be_timer_push(T_VERIFY);
728                 be_sched_verify(irg, be_options.verify_option);
729                 be_timer_pop(T_VERIFY);
730
731                 if (stat_ev_enabled) {
732                         stat_ev_dbl("bemain_costs_before_ra", be_estimate_irg_costs(irg));
733                         stat_ev_ull("bemain_insns_before_ra", be_count_insns(irg));
734                         stat_ev_ull("bemain_blocks_before_ra", be_count_blocks(irg));
735                 }
736
737                 /* Do register allocation */
738                 be_allocate_registers(irg);
739
740                 stat_ev_dbl("bemain_costs_before_ra", be_estimate_irg_costs(irg));
741
742                 dump(DUMP_RA, irg, "ra");
743
744                 be_timer_push(T_FINISH);
745                 if (arch_env->impl->finish_graph != NULL)
746                         arch_env->impl->finish_graph(irg);
747                 be_timer_pop(T_FINISH);
748
749                 dump(DUMP_FINAL, irg, "finish");
750
751                 if (stat_ev_enabled) {
752                         stat_ev_ull("bemain_insns_finish", be_count_insns(irg));
753                         stat_ev_ull("bemain_blocks_finish", be_count_blocks(irg));
754                 }
755
756                 /* check schedule and register allocation */
757                 be_timer_push(T_VERIFY);
758                 if (be_options.verify_option == BE_VERIFY_WARN) {
759                         irg_verify(irg, VERIFY_ENFORCE_SSA);
760                         be_verify_schedule(irg);
761                         be_verify_register_allocation(irg);
762                 } else if (be_options.verify_option == BE_VERIFY_ASSERT) {
763                         assert(irg_verify(irg, VERIFY_ENFORCE_SSA) && "irg verification failed");
764                         assert(be_verify_schedule(irg) && "Schedule verification failed");
765                         assert(be_verify_register_allocation(irg)
766                                && "register allocation verification failed");
767
768                 }
769                 be_timer_pop(T_VERIFY);
770
771                 /* emit assembler code */
772                 be_timer_push(T_EMIT);
773                 if (arch_env->impl->emit != NULL)
774                         arch_env->impl->emit(irg);
775                 be_timer_pop(T_EMIT);
776
777                 dump(DUMP_FINAL, irg, "end");
778
779                 restore_optimization_state(&state);
780
781                 be_timer_pop(T_OTHER);
782
783                 if (be_timing) {
784                         be_timer_id_t t;
785                         if (stat_ev_enabled) {
786                                 for (t = T_FIRST; t < T_LAST+1; ++t) {
787                                         char buf[128];
788                                         snprintf(buf, sizeof(buf), "bemain_time_%s",
789                                                  get_timer_name(t));
790                                         stat_ev_dbl(buf, ir_timer_elapsed_usec(be_timers[i]));
791                                 }
792                         } else {
793                                 printf("==>> IRG %s <<==\n",
794                                        get_entity_name(get_irg_entity(irg)));
795                                 for (t = T_FIRST; t < T_LAST+1; ++t) {
796                                         double val = ir_timer_elapsed_usec(be_timers[t]) / 1000.0;
797                                         printf("%-20s: %10.3f msec\n", get_timer_name(t), val);
798                                 }
799                         }
800                         for (t = T_FIRST; t < T_LAST+1; ++t) {
801                                 ir_timer_reset(be_timers[t]);
802                         }
803                 }
804
805                 be_free_birg(irg);
806                 stat_ev_ctx_pop("bemain_irg");
807         }
808
809         be_gas_end_compilation_unit(&env);
810         be_emit_exit();
811
812         arch_env_end_codegeneration(arch_env);
813
814         be_done_env(&env);
815
816         be_info_free();
817 }
818
819 /* Main interface to the frontend. */
820 void be_main(FILE *file_handle, const char *cup_name)
821 {
822         ir_timer_t *t = NULL;
823
824         if (be_options.timing == BE_TIME_ON) {
825                 t = ir_timer_new();
826
827                 if (ir_timer_enter_high_priority()) {
828                         fprintf(stderr, "Warning: Could not enter high priority mode.\n");
829                 }
830
831                 ir_timer_reset_and_start(t);
832         }
833
834         if (be_options.statev) {
835                 const char *dot = strrchr(cup_name, '.');
836                 const char *pos = dot ? dot : cup_name + strlen(cup_name);
837                 char       *buf = ALLOCAN(char, pos - cup_name + 1);
838                 strncpy(buf, cup_name, pos - cup_name);
839                 buf[pos - cup_name] = '\0';
840
841                 be_options.statev = 1;
842                 stat_ev_begin(buf, be_options.filtev);
843                 stat_ev_ctx_push_str("bemain_compilation_unit", cup_name);
844         }
845
846         be_main_loop(file_handle, cup_name);
847
848         if (be_options.timing == BE_TIME_ON) {
849                 ir_timer_stop(t);
850                 ir_timer_leave_high_priority();
851                 if (stat_ev_enabled) {
852                         stat_ev_dbl("bemain_backend_time", ir_timer_elapsed_msec(t));
853                 } else {
854                         double val = ir_timer_elapsed_usec(t) / 1000.0;
855                         printf("%-20s: %10.3f msec\n", "BEMAINLOOP", val);
856                 }
857         }
858
859         if (be_options.statev) {
860                 stat_ev_ctx_pop("bemain_compilation_unit");
861                 stat_ev_end();
862         }
863 }
864
865 static int do_lower_for_target(ir_prog *irp, void *context)
866 {
867         be_lower_for_target();
868         (void) context;
869         (void) irp;
870         return 0;
871 }
872
873 ir_prog_pass_t *lower_for_target_pass(const char *name)
874 {
875         ir_prog_pass_t *pass = XMALLOCZ(ir_prog_pass_t);
876         return def_prog_pass_constructor(pass,
877                                          name ? name : "lower_for_target",
878                                          do_lower_for_target);
879 }