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