3f4d6948a94c9fa696209525c07c301729e87948
[cparser] / driver / firm_opt.c
1 /**
2  *
3  * @file firm_opt.c -- Firm-generating back end optimizations.
4  *
5  * (C) 2005-2009  Michael Beck   beck@ipd.info.uni-karlsruhe.de
6  *
7  * $Id$
8  */
9
10 #include <config.h>
11
12 #include <stdbool.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <stdbool.h>
16 #include <assert.h>
17 #include <libfirm/firm.h>
18
19 #include "firm_opt.h"
20 #include "firm_codegen.h"
21 #include "firm_cmdline.h"
22 #include "firm_timing.h"
23 #include "ast2firm.h"
24
25 #if defined(_DEBUG) || defined(FIRM_DEBUG)
26 #define DBG(x)  dbg_printf x
27 #else
28 #define DBG(x) ((void)0)
29 #endif /* _DEBUG || FIRM_DEBUG */
30
31 static ir_timer_t *t_vcg_dump;
32 static ir_timer_t *t_verify;
33 static ir_timer_t *t_all_opt;
34 static bool do_irg_opt(ir_graph *irg, const char *name);
35
36 /** dump all the graphs depending on cond */
37
38 static void dump_all(const char *suffix) {
39         if (firm_dump.ir_graph) {
40                 timer_push(t_vcg_dump);
41                 if (firm_dump.no_blocks)
42                         dump_all_ir_graphs(dump_ir_graph, suffix);
43                 else if (firm_dump.extbb)
44                         dump_all_ir_graphs(dump_ir_extblock_graph, suffix);
45                 else
46                         dump_all_ir_graphs(dump_ir_block_graph, suffix);
47                 timer_pop(t_vcg_dump);
48         }
49 }
50
51 /* set by the backend parameters */
52 static const ir_settings_arch_dep_t *ad_param              = NULL;
53 static create_intrinsic_fkt         *arch_create_intrinsic = NULL;
54 static void                         *create_intrinsic_ctx  = NULL;
55 static const ir_settings_if_conv_t  *if_conv_info          = NULL;
56
57 /* entities of runtime functions */
58 ir_entity_ptr rts_entities[rts_max];
59
60 /**
61  * factory for setting architecture dependent parameters
62  */
63 static const ir_settings_arch_dep_t *arch_factory(void)
64 {
65   static const ir_settings_arch_dep_t param = {
66       1,   /* also use subs */
67       4,   /* maximum shifts */
68      31,   /* maximum shift amount */
69      NULL, /* use default evaluator */
70
71       1, /* allow Mulhs */
72       1, /* allow Mulus */
73      32  /* Mulh allowed up to 32 bit */
74   };
75
76   return ad_param ? ad_param : &param;
77 }
78
79 /**
80  * Map runtime functions.
81  */
82 static void rts_map(void) {
83         static const struct {
84                 ir_entity_ptr *ent; /**< address of the rts entity */
85                 i_mapper_func func; /**< mapper function. */
86         } mapper[] = {
87                 /* integer */
88                 { &rts_entities[rts_abs],     i_mapper_abs },
89                 { &rts_entities[rts_labs],    i_mapper_abs },
90                 { &rts_entities[rts_llabs],   i_mapper_abs },
91                 { &rts_entities[rts_imaxabs], i_mapper_abs },
92
93                 /* double -> double */
94                 { &rts_entities[rts_fabs],    i_mapper_abs },
95                 { &rts_entities[rts_sqrt],    i_mapper_sqrt },
96                 { &rts_entities[rts_cbrt],    i_mapper_cbrt },
97                 { &rts_entities[rts_pow],     i_mapper_pow },
98                 { &rts_entities[rts_exp],     i_mapper_exp },
99                 { &rts_entities[rts_exp2],    i_mapper_exp },
100                 { &rts_entities[rts_exp10],   i_mapper_exp },
101                 { &rts_entities[rts_log],     i_mapper_log },
102                 { &rts_entities[rts_log2],    i_mapper_log2 },
103                 { &rts_entities[rts_log10],   i_mapper_log10 },
104                 { &rts_entities[rts_sin],     i_mapper_sin },
105                 { &rts_entities[rts_cos],     i_mapper_cos },
106                 { &rts_entities[rts_tan],     i_mapper_tan },
107                 { &rts_entities[rts_asin],    i_mapper_asin },
108                 { &rts_entities[rts_acos],    i_mapper_acos },
109                 { &rts_entities[rts_atan],    i_mapper_atan },
110                 { &rts_entities[rts_sinh],    i_mapper_sinh },
111                 { &rts_entities[rts_cosh],    i_mapper_cosh },
112                 { &rts_entities[rts_tanh],    i_mapper_tanh },
113
114                 /* float -> float */
115                 { &rts_entities[rts_fabsf],   i_mapper_abs },
116                 { &rts_entities[rts_sqrtf],   i_mapper_sqrt },
117                 { &rts_entities[rts_cbrtf],   i_mapper_cbrt },
118                 { &rts_entities[rts_powf],    i_mapper_pow },
119                 { &rts_entities[rts_expf],    i_mapper_exp },
120                 { &rts_entities[rts_exp2f],   i_mapper_exp },
121                 { &rts_entities[rts_exp10f],  i_mapper_exp },
122                 { &rts_entities[rts_logf],    i_mapper_log },
123                 { &rts_entities[rts_log2f],   i_mapper_log2 },
124                 { &rts_entities[rts_log10f],  i_mapper_log10 },
125                 { &rts_entities[rts_sinf],    i_mapper_sin },
126                 { &rts_entities[rts_cosf],    i_mapper_cos },
127                 { &rts_entities[rts_tanf],    i_mapper_tan },
128                 { &rts_entities[rts_asinf],   i_mapper_asin },
129                 { &rts_entities[rts_acosf],   i_mapper_acos },
130                 { &rts_entities[rts_atanf],   i_mapper_atan },
131                 { &rts_entities[rts_sinhf],   i_mapper_sinh },
132                 { &rts_entities[rts_coshf],   i_mapper_cosh },
133                 { &rts_entities[rts_tanhf],   i_mapper_tanh },
134
135                 /* long double -> long double */
136                 { &rts_entities[rts_fabsl],   i_mapper_abs },
137                 { &rts_entities[rts_sqrtl],   i_mapper_sqrt },
138                 { &rts_entities[rts_cbrtl],   i_mapper_cbrt },
139                 { &rts_entities[rts_powl],    i_mapper_pow },
140                 { &rts_entities[rts_expl],    i_mapper_exp },
141                 { &rts_entities[rts_exp2l],   i_mapper_exp },
142                 { &rts_entities[rts_exp10l],  i_mapper_exp },
143                 { &rts_entities[rts_logl],    i_mapper_log },
144                 { &rts_entities[rts_log2l],   i_mapper_log2 },
145                 { &rts_entities[rts_log10l],  i_mapper_log10 },
146                 { &rts_entities[rts_sinl],    i_mapper_sin },
147                 { &rts_entities[rts_cosl],    i_mapper_cos },
148                 { &rts_entities[rts_tanl],    i_mapper_tan },
149                 { &rts_entities[rts_asinl],   i_mapper_asin },
150                 { &rts_entities[rts_acosl],   i_mapper_acos },
151                 { &rts_entities[rts_atanl],   i_mapper_atan },
152                 { &rts_entities[rts_sinhl],   i_mapper_sinh },
153                 { &rts_entities[rts_coshl],   i_mapper_cosh },
154                 { &rts_entities[rts_tanhl],   i_mapper_tanh },
155
156                 /* string */
157                 { &rts_entities[rts_strcmp],  i_mapper_strcmp },
158                 { &rts_entities[rts_strncmp], i_mapper_strncmp },
159                 { &rts_entities[rts_strcpy],  i_mapper_strcpy },
160                 { &rts_entities[rts_strlen],  i_mapper_strlen },
161                 { &rts_entities[rts_memcpy],  i_mapper_memcpy },
162                 { &rts_entities[rts_mempcpy], i_mapper_mempcpy },
163                 { &rts_entities[rts_memmove], i_mapper_memmove },
164                 { &rts_entities[rts_memset],  i_mapper_memset },
165                 { &rts_entities[rts_memcmp],  i_mapper_memcmp }
166         };
167         i_record rec[sizeof(mapper)/sizeof(mapper[0])];
168         unsigned i, n_map;
169
170         for (i = n_map = 0; i < sizeof(mapper)/sizeof(mapper[0]); ++i) {
171                 if (*mapper[i].ent != NULL) {
172                         rec[n_map].i_call.kind     = INTRINSIC_CALL;
173                         rec[n_map].i_call.i_ent    = *mapper[i].ent;
174                         rec[n_map].i_call.i_mapper = mapper[i].func;
175                         rec[n_map].i_call.ctx      = NULL;
176                         rec[n_map].i_call.link     = NULL;
177                         ++n_map;
178                 }
179         }
180
181         if (n_map > 0)
182                 lower_intrinsics(rec, n_map, /* part_block_used=*/0);
183 }
184
185 static int *irg_dump_no;
186
187 static void dump_graph_count(ir_graph *const irg, const char *const suffix)
188 {
189         char name[64];
190         snprintf(name, sizeof(name), "-%02d_%s", irg_dump_no[get_irg_idx(irg)]++,
191                  suffix);
192
193         timer_push(t_vcg_dump);
194         if (firm_dump.no_blocks)
195                 dump_ir_graph(irg, name);
196         else if (firm_dump.extbb)
197                 dump_ir_extblock_graph(irg, name);
198         else
199                 dump_ir_block_graph(irg, name);
200         timer_pop(t_vcg_dump);
201 }
202
203 static void remove_unused_functions(void)
204 {
205         ir_entity **keep_methods;
206         int         arr_len;
207
208         /* Analysis that finds the free methods,
209            i.e. methods that are dereferenced.
210            Optimizes polymorphic calls :-). */
211         cgana(&arr_len, &keep_methods);
212
213         /* Remove methods that are never called. */
214         gc_irgs(arr_len, keep_methods);
215         free(keep_methods);
216 }
217
218 static int firm_const_exists;
219
220 static void do_optimize_funccalls(void)
221 {
222         optimize_funccalls(firm_const_exists, NULL);
223 }
224
225 static void do_gcse(ir_graph *irg)
226 {
227         set_opt_global_cse(1);
228         optimize_graph_df(irg);
229         place_code(irg);
230         set_opt_global_cse(0);
231 }
232
233 static void do_lower_highlevel(ir_graph *irg)
234 {
235         lower_highlevel_graph(irg, firm_opt.lower_bitfields);
236 }
237
238 static void do_if_conv(ir_graph *irg)
239 {
240         opt_if_conv(irg, if_conv_info);
241 }
242
243 static void do_stred(ir_graph *irg)
244 {
245         opt_osr(irg, osr_flag_default | osr_flag_keep_reg_pressure | osr_flag_ignore_x86_shift);
246 }
247
248 static void after_inline_opt(ir_graph *irg)
249 {
250         do_irg_opt(irg, "scalar-replace");
251         do_irg_opt(irg, "local");
252         do_irg_opt(irg, "control-flow");
253         do_irg_opt(irg, "combo");
254 }
255
256 static void do_inline(void)
257 {
258         inline_functions(firm_opt.inline_maxsize, firm_opt.inline_threshold,
259                          after_inline_opt);
260 }
261
262 static void do_cloning(void)
263 {
264         proc_cloning((float) firm_opt.clone_threshold);
265 }
266
267 static void do_lower_switch(ir_graph *irg)
268 {
269         lower_switch(irg, firm_opt.spare_size);
270 }
271
272 static void do_lower_dw_ops(void)
273 {
274         lwrdw_param_t init = {
275                 1,
276                 1,
277                 get_atomic_mode(ATOMIC_TYPE_LONGLONG),
278                 get_atomic_mode(ATOMIC_TYPE_ULONGLONG),
279                 get_atomic_mode(ATOMIC_TYPE_INT),
280                 get_atomic_mode(ATOMIC_TYPE_UINT),
281                 def_create_intrinsic_fkt,
282                 NULL
283         };
284
285         if (arch_create_intrinsic) {
286                 init.create_intrinsic = arch_create_intrinsic;
287                 init.ctx              = create_intrinsic_ctx;
288         }
289         lower_dw_ops(&init);
290 }
291
292 typedef enum opt_target {
293         OPT_TARGET_IRG, /**< optimization function works on a single graph */
294         OPT_TARGET_IRP  /**< optimization function works on the complete program */
295 } opt_target_t;
296
297 typedef enum opt_flags {
298         OPT_FLAG_NONE         = 0,
299         OPT_FLAG_ENABLED      = 1 << 0, /**< enable the optimization */
300         OPT_FLAG_NO_DUMP      = 1 << 1, /**< don't dump after transformation */
301         OPT_FLAG_NO_VERIFY    = 1 << 2, /**< don't verify after transformation */
302         OPT_FLAG_HIDE_OPTIONS = 1 << 3, /**< do not automatically process
303                                              -foptions for this transformation */
304 } opt_flags_t;
305
306 typedef void (*transform_irg_func)(ir_graph *irg);
307 typedef void (*transform_irp_func)(void);
308 typedef void (*func_ptr_t)(void);
309
310 typedef struct {
311         opt_target_t  target;
312         const char   *name;
313         func_ptr_t    func;
314         const char   *description;
315         opt_flags_t   flags;
316 } opt_config_t;
317
318 static opt_config_t opts[] = {
319         { OPT_TARGET_IRP, "rts",             (func_ptr_t) rts_map,                 "optimization of known library functions", OPT_FLAG_HIDE_OPTIONS },
320         { OPT_TARGET_IRG, "combo",           (func_ptr_t) combo,                   "combined CCE, UCE and GVN",               OPT_FLAG_NONE},
321         { OPT_TARGET_IRG, "control-flow",    (func_ptr_t) optimize_cf,             "optimization of control-flow",            OPT_FLAG_HIDE_OPTIONS },
322         { OPT_TARGET_IRG, "local",           (func_ptr_t) optimize_graph_df,       "local graph optimizations",               OPT_FLAG_HIDE_OPTIONS },
323         { OPT_TARGET_IRP, "remove-unused",   (func_ptr_t) remove_unused_functions, "removal of unused functions",             OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY },
324         { OPT_TARGET_IRP, "opt-tail-rec",    (func_ptr_t) opt_tail_recursion,      "tail-recursion eliminiation",             OPT_FLAG_NONE },
325         { OPT_TARGET_IRP, "opt-func-call",   (func_ptr_t) do_optimize_funccalls,   "function call optimization",              OPT_FLAG_NONE },
326         { OPT_TARGET_IRG, "lower",           (func_ptr_t) do_lower_highlevel,      "lowering",                                OPT_FLAG_HIDE_OPTIONS },
327         { OPT_TARGET_IRP, "lower-const",     (func_ptr_t) lower_const_code,        "lowering of constant code",               OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY },
328         { OPT_TARGET_IRP, "lower-dw",        (func_ptr_t) do_lower_dw_ops,         "lowering of doubleword operations",       OPT_FLAG_HIDE_OPTIONS },
329         { OPT_TARGET_IRG, "lower-switch",    (func_ptr_t) do_lower_switch,         "switch lowering",                         OPT_FLAG_HIDE_OPTIONS },
330         { OPT_TARGET_IRG, "one-return",      (func_ptr_t) normalize_one_return,    "normalisation to 1 return",               OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY },
331         { OPT_TARGET_IRG, "scalar-replace",  (func_ptr_t) scalar_replacement_opt,  "scalar replacement",                      OPT_FLAG_NONE },
332         { OPT_TARGET_IRG, "reassociation",   (func_ptr_t) optimize_reassociation,  "reassociation",                           OPT_FLAG_NONE },
333         { OPT_TARGET_IRG, "gcse",            (func_ptr_t) do_gcse,                 "global common subexpression elimination", OPT_FLAG_NONE },
334         { OPT_TARGET_IRG, "place",           (func_ptr_t) place_code,              "code placement",                          OPT_FLAG_NONE },
335         { OPT_TARGET_IRG, "confirm",         (func_ptr_t) construct_confirms,      "confirm optimisation",                    OPT_FLAG_HIDE_OPTIONS },
336         { OPT_TARGET_IRG, "opt-load-store",  (func_ptr_t) optimize_load_store,     "load store optimization",                 OPT_FLAG_NONE },
337         { OPT_TARGET_IRG, "parallelize-mem", (func_ptr_t) opt_parallelize_mem,     "parallelize memory",                      OPT_FLAG_NONE },
338         { OPT_TARGET_IRG, "deconv",          (func_ptr_t) conv_opt,                "conv node elimination",                   OPT_FLAG_NONE },
339         { OPT_TARGET_IRG, "thread-jumps",    (func_ptr_t) opt_jumpthreading,       "path-sensitive jumpthreading",            OPT_FLAG_NONE },
340         { OPT_TARGET_IRG, "remove-confirms", (func_ptr_t) remove_confirms,         "confirm removal",                         OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY },
341         { OPT_TARGET_IRG, "gvn-pre",         (func_ptr_t) do_gvn_pre,              "global value numbering partial redundancy elimination", OPT_FLAG_NONE },
342         { OPT_TARGET_IRG, "if-conversion",   (func_ptr_t) do_if_conv,              "if-conversion",                           OPT_FLAG_NONE },
343         { OPT_TARGET_IRG, "bool",            (func_ptr_t) opt_bool,                "bool simplification",                     OPT_FLAG_NONE },
344         { OPT_TARGET_IRG, "shape-blocks",    (func_ptr_t) shape_blocks,            "block shaping",                           OPT_FLAG_NONE },
345         { OPT_TARGET_IRG, "ivopts",          (func_ptr_t) do_stred,                "induction variable strength reduction",   OPT_FLAG_NONE },
346         { OPT_TARGET_IRG, "remove-phi-cycles", (func_ptr_t) remove_phi_cycles,     "removal of phi cycles",                   OPT_FLAG_HIDE_OPTIONS },
347         { OPT_TARGET_IRG, "dead",            (func_ptr_t) dead_node_elimination,   "dead node elimination",                   OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY },
348         { OPT_TARGET_IRP, "inline",          (func_ptr_t) do_inline,               "inlining",                                OPT_FLAG_NONE },
349         { OPT_TARGET_IRP, "opt-proc-clone",  (func_ptr_t) do_cloning,              "procedure cloning",                       OPT_FLAG_NONE },
350         { OPT_TARGET_IRG, "invert-loops",    (func_ptr_t) do_loop_inversion,       "loop inversion",                          OPT_FLAG_NONE },
351         { OPT_TARGET_IRG, "peel-loops",      (func_ptr_t) do_loop_peeling,         "loop peeling",                            OPT_FLAG_NONE },
352 };
353 static const int n_opts = sizeof(opts) / sizeof(opts[0]);
354 ir_timer_t *timers[sizeof(opts)/sizeof(opts[0])];
355
356 static opt_config_t *get_opt(const char *name)
357 {
358         int i;
359         for (i = 0; i < n_opts; ++i) {
360                 opt_config_t *config = &opts[i];
361                 if (strcmp(config->name, name) == 0)
362                         return config;
363         }
364
365         return NULL;
366 }
367
368 static void set_opt_enabled(const char *name, bool enabled)
369 {
370         opt_config_t *config = get_opt(name);
371         config->flags = (config->flags & ~OPT_FLAG_ENABLED)
372                 | (enabled ? OPT_FLAG_ENABLED : 0);
373 }
374
375 static bool get_opt_enabled(const char *name)
376 {
377         opt_config_t *config = get_opt(name);
378         return (config->flags & OPT_FLAG_ENABLED) != 0;
379 }
380
381 /**
382  * perform an optimisation on a single graph
383  *
384  * @return  true if something changed, false otherwise
385  */
386 static bool do_irg_opt(ir_graph *irg, const char *name)
387 {
388         transform_irg_func  func;
389         ir_graph           *old_irg;
390         opt_config_t       *config = get_opt(name);
391         size_t              n      = config - opts;
392         assert(config != NULL);
393         assert(config->target == OPT_TARGET_IRG);
394         if (! (config->flags & OPT_FLAG_ENABLED))
395                 return false;
396
397
398         old_irg          = current_ir_graph;
399         current_ir_graph = irg;
400
401         func = (transform_irg_func) config->func;
402
403         timer_push(timers[n]);
404         func(irg);
405         timer_pop(timers[n]);
406
407         if (firm_dump.all_phases && firm_dump.ir_graph) {
408                 dump_graph_count(irg, name);
409         }
410
411         if (firm_opt.check_all) {
412                 timer_push(t_verify);
413                 irg_verify(irg, VRFY_ENFORCE_SSA);
414                 timer_pop(t_verify);
415         }
416
417         current_ir_graph = old_irg;
418         return true;
419 }
420
421 static void do_irp_opt(const char *name)
422 {
423         transform_irp_func  func;
424         opt_config_t       *config = get_opt(name);
425         size_t              n      = config - opts;
426         assert(config->target == OPT_TARGET_IRP);
427         if (! (config->flags & OPT_FLAG_ENABLED))
428                 return;
429
430         func = (transform_irp_func) config->func;
431
432         timer_push(timers[n]);
433         func();
434         timer_pop(timers[n]);
435
436         if (firm_dump.ir_graph && firm_dump.all_phases) {
437                 int i;
438                 for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
439                         ir_graph *irg = get_irp_irg(i);
440                         dump_graph_count(irg, name);
441                 }
442         }
443
444         if (firm_opt.check_all) {
445                 int i;
446                 timer_push(t_verify);
447                 for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
448                         irg_verify(get_irp_irg(i), VRFY_ENFORCE_SSA);
449                 }
450                 timer_pop(t_verify);
451         }
452 }
453
454 /**
455  * Enable transformations which should be always safe (and cheap) to perform
456  */
457 static void enable_safe_defaults(void)
458 {
459         set_opt_enabled("remove-unused", true);
460         set_opt_enabled("opt-tail-rec", true);
461         set_opt_enabled("opt-func-call", true);
462         set_opt_enabled("reassociation", true);
463         set_opt_enabled("control-flow", true);
464         set_opt_enabled("local", true);
465         set_opt_enabled("lower-const", true);
466         set_opt_enabled("scalar-replace", true);
467         set_opt_enabled("place", true);
468         set_opt_enabled("confirm", true);
469         set_opt_enabled("opt-load-store", true);
470         set_opt_enabled("lower", true);
471         set_opt_enabled("deconv", true);
472         set_opt_enabled("remove-confirms", true);
473         set_opt_enabled("ivopts", true);
474         set_opt_enabled("dead", true);
475         set_opt_enabled("lower-switch", true);
476         set_opt_enabled("remove-phi-cycles", true);
477 }
478
479 /**
480  * run all the Firm optimizations
481  *
482  * @param input_filename     the name of the (main) source file
483  */
484 static void do_firm_optimizations(const char *input_filename)
485 {
486         int      i;
487         unsigned aa_opt;
488
489         set_opt_alias_analysis(firm_opt.alias_analysis);
490
491         aa_opt = aa_opt_no_opt;
492         if (firm_opt.strict_alias)
493                 aa_opt |= aa_opt_type_based | aa_opt_byte_type_may_alias;
494         if (firm_opt.no_alias)
495                 aa_opt = aa_opt_no_alias;
496
497         set_irp_memory_disambiguator_options(aa_opt);
498
499         /* parameter passing code should set them directly sometime... */
500         set_opt_enabled("rts", !firm_opt.freestanding);
501         set_opt_enabled("gcse", firm_opt.gcse);
502         set_opt_enabled("place", !firm_opt.gcse);
503         set_opt_enabled("confirm", firm_opt.confirm);
504         set_opt_enabled("remove-confirms", firm_opt.confirm);
505
506         /* osr supersedes remove_phi_cycles */
507         if (get_opt_enabled("ivopts"))
508                 set_opt_enabled("remove-phi-cycles", false);
509
510         timer_start(t_all_opt);
511
512         do_irp_opt("rts");
513
514         /* first step: kill dead code */
515         for (i = 0; i < get_irp_n_irgs(); i++) {
516                 ir_graph *irg = get_irp_irg(i);
517                 do_irg_opt(irg, "combo");
518                 do_irg_opt(irg, "local");
519                 do_irg_opt(irg, "control-flow");
520         }
521
522         do_irp_opt("remove-unused");
523         do_irp_opt("opt-tail-rec");
524         do_irp_opt("opt-func-call");
525         do_irp_opt("lower-const");
526
527         for (i = 0; i < get_irp_n_irgs(); i++) {
528                 ir_graph *irg = get_irp_irg(i);
529
530                 do_irg_opt(irg, "scalar-replace");
531                 do_irg_opt(irg, "invert-loops");
532                 do_irg_opt(irg, "local");
533                 do_irg_opt(irg, "reassociation");
534                 do_irg_opt(irg, "local");
535                 do_irg_opt(irg, "gcse");
536
537                 if (firm_opt.confirm) {
538                         /* Confirm construction currently can only handle blocks with only
539                            one control flow predecessor. Calling optimize_cf here removes
540                            Bad predecessors and help the optimization of switch constructs.
541                          */
542                         do_irg_opt(irg, "control-flow");
543                         do_irg_opt(irg, "confirm");
544                         do_irg_opt(irg, "local");
545                 }
546
547                 do_irg_opt(irg, "control-flow");
548                 do_irg_opt(irg, "opt-load-store");
549                 do_irg_opt(irg, "lower");
550                 do_irg_opt(irg, "deconv");
551                 do_irg_opt(irg, "thread-jumps");
552                 do_irg_opt(irg, "remove-confirms");
553                 do_irg_opt(irg, "gvn-pre");
554                 do_irg_opt(irg, "place");
555                 do_irg_opt(irg, "control-flow");
556
557                 if (do_irg_opt(irg, "if-conversion")) {
558                         do_irg_opt(irg, "local");
559                         do_irg_opt(irg, "control-flow");
560                 }
561
562                 do_irg_opt(irg, "bool");
563                 do_irg_opt(irg, "shape-blocks");
564                 do_irg_opt(irg, "lower-switch");
565                 do_irg_opt(irg, "ivopts");
566                 do_irg_opt(irg, "local");
567                 do_irg_opt(irg, "dead");
568         }
569
570         do_irp_opt("inline");
571         do_irp_opt("opt-proc-clone");
572
573         for (i = 0; i < get_irp_n_irgs(); i++) {
574                 ir_graph *irg = get_irp_irg(i);
575                 do_irg_opt(irg, "local");
576                 do_irg_opt(irg, "control-flow");
577                 do_irg_opt(irg, "thread-jumps");
578                 do_irg_opt(irg, "local");
579                 do_irg_opt(irg, "control-flow");
580         }
581
582         if (firm_dump.ir_graph) {
583                 /* recompute backedges for nicer dumps */
584                 for (i = 0; i < get_irp_n_irgs(); i++)
585                         construct_cf_backedges(get_irp_irg(i));
586         }
587
588         do_irp_opt("remove-unused");
589
590         dump_all("-opt");
591
592         if (firm_dump.statistic & STAT_AFTER_OPT)
593                 stat_dump_snapshot(input_filename, "opt");
594
595         timer_stop(t_all_opt);
596 }
597
598 /**
599  * compute the size of a type (do implicit lowering)
600  *
601  * @param ty   a Firm type
602  */
603 static int compute_type_size(ir_type *ty)
604 {
605         optimization_state_t state;
606         unsigned             align_all = 1;
607         int                  n, size = 0, set = 0;
608         int                  i, dims, s;
609
610         if (get_type_state(ty) == layout_fixed) {
611                 /* do not layout already layouted types again */
612                 return 1;
613         }
614
615         if (is_Method_type(ty) || ty == get_glob_type()) {
616                 /* no need for size calculation for method types or the global type */
617                 return 1;
618         }
619
620         DBG(("compute type size visiting: %s\n", get_type_name(ty)));
621
622         switch (get_type_tpop_code(ty)) {
623         case tpo_class:
624         case tpo_struct:
625                 for (i = 0, n = get_compound_n_members(ty); i < n; ++i) {
626                         ir_entity *ent  = get_compound_member(ty, i);
627                         ir_type *ent_ty = get_entity_type(ent);
628                         unsigned align, misalign;
629
630                         /* inner functions do not expand the frame */
631                         if (is_Method_type(ent_ty) && is_frame_type(ty))
632                                 continue;
633
634                         /* compute member types */
635                         if (! compute_type_size(ent_ty))
636                                 return 0;
637
638                         align     = get_type_alignment_bytes(ent_ty);
639                         align_all = align > align_all ? align : align_all;
640                         misalign  = (align ? size % align : 0);
641                         size     += (misalign ? align - misalign : 0);
642
643                         set_entity_offset(ent, size);
644                         size += get_type_size_bytes(ent_ty);
645
646                         DBG(("  member %s %s -> (size: %u, align: %u)\n",
647                                                 get_type_name(ent_ty), get_entity_name(ent),
648                                                 get_type_size_bytes(ent_ty), get_type_alignment_bytes(ent_ty)));
649                 }
650                 if (align_all > 0 && size % align_all) {
651                         DBG(("align of the struct member: %u, type size: %d\n", align_all, size));
652                         size += align_all - (size % align_all);
653                         DBG(("correcting type-size to %d\n", size));
654                 }
655                 set_type_alignment_bytes(ty, align_all);
656                 set = 1;
657                 break;
658
659         case tpo_union:
660                 for (i = 0, n = get_union_n_members(ty); i < n; ++i) {
661                         ir_entity *ent = get_union_member(ty, i);
662
663                         if (! compute_type_size(get_entity_type(ent)))
664                                 return 0;
665                         s = get_type_size_bytes(get_entity_type(ent));
666
667                         set_entity_offset(ent, 0);
668                         size = (s > size ? s : size);
669                 }
670                 set = 1;
671                 break;
672
673         case tpo_array:
674                 dims = get_array_n_dimensions(ty);
675
676                 if (! compute_type_size(get_array_element_type(ty)))
677                         return 0;
678
679                 size = 1;
680
681                 save_optimization_state(&state);
682                 set_optimize(1);
683                 set_opt_constant_folding(1);
684                 set_opt_algebraic_simplification(1);
685
686                 for (i = 0; i < dims; ++i) {
687                         ir_node *lower   = get_array_lower_bound(ty, i);
688                         ir_node *upper   = get_array_upper_bound(ty, i);
689                         ir_graph *rem    = current_ir_graph;
690                         tarval  *tv_lower, *tv_upper;
691                         long     val_lower, val_upper;
692
693                         current_ir_graph = get_const_code_irg();
694                         local_optimize_node(lower);
695                         local_optimize_node(upper);
696                         current_ir_graph = rem;
697
698                         tv_lower = computed_value(lower);
699                         tv_upper = computed_value(upper);
700
701                         if (tv_lower == tarval_bad || tv_upper == tarval_bad) {
702                                 /*
703                                  * we cannot calculate the size of this array yet, it
704                                  * even might be unknown until the end, like argv[]
705                                  */
706                                 restore_optimization_state(&state);
707                                 return 0;
708                         }
709
710                         val_upper = get_tarval_long(tv_upper);
711                         val_lower = get_tarval_long(tv_lower);
712                         size     *= val_upper - val_lower;
713                 }
714                 restore_optimization_state(&state);
715
716                 DBG(("array %s -> (elements: %d, element type size: %d)\n",
717                                         get_type_name(ty),
718                                         size, get_type_size_bytes(get_array_element_type(ty))));
719                 size *= get_type_size_bytes(get_array_element_type(ty));
720                 set = 1;
721                 break;
722
723         default:
724                 break;
725         }
726
727         if (set) {
728                 set_type_size_bytes(ty, size);
729                 set_type_state(ty, layout_fixed);
730         }
731
732         DBG(("size: %d\n", get_type_size_bytes(ty)));
733
734         return set;
735 }
736
737 /**
738  * layout all non-frame types of the Firm graph
739  */
740 static void compute_type_sizes(void)
741 {
742         int i;
743         ir_type *tp;
744
745         /* all non-frame other types */
746         for (i = get_irp_n_types() - 1; i >= 0; --i) {
747                 tp = get_irp_type(i);
748                 compute_type_size(tp);
749
750                 if (is_Method_type(tp)) {
751                         tp = get_method_value_res_type(tp);
752
753                         if (tp) {
754                                 /* we have a value result type for this method, lower */
755                                 compute_type_size(tp);
756                         }
757                 }
758         }
759 }
760
761 /**
762  * layout all frame-types of the Firm graph
763  */
764 static void compute_frame_type_sizes(void)
765 {
766         int i;
767         ir_graph *irg;
768
769         /* all frame types */
770         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
771                 irg = get_irp_irg(i);
772                 /* do not optimize away variables in debug mode */
773                 if (firm_opt.debug_mode == DBG_MODE_NONE)
774                         opt_frame_irg(irg);
775                 compute_type_size(get_irg_frame_type(irg));
776         }
777 }
778
779 /**
780  * do Firm lowering
781  *
782  * @param input_filename  the name of the (main) source file
783  */
784 static void do_firm_lowering(const char *input_filename)
785 {
786         int i;
787
788         do_irp_opt("lower-dw");
789
790         if (firm_dump.statistic & STAT_AFTER_LOWER)
791                 stat_dump_snapshot(input_filename, "low");
792
793         dump_all("-low");
794
795         if (firm_opt.enabled) {
796                 timer_start(t_all_opt);
797
798                 /* run reassociation first on all graphs BEFORE the architecture
799                    dependent optimizations are enabled */
800                 for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
801                         ir_graph *irg = get_irp_irg(i);
802                         do_irg_opt(irg, "reassociation");
803                 }
804
805                 /* enable architecture dependent optimizations */
806                 arch_dep_set_opts((arch_dep_opts_t)
807                                 ((firm_opt.muls ? arch_dep_mul_to_shift : arch_dep_none) |
808                                  (firm_opt.divs ? arch_dep_div_by_const : arch_dep_none) |
809                                  (firm_opt.mods ? arch_dep_mod_by_const : arch_dep_none) ));
810
811                 for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
812                         ir_graph *irg = get_irp_irg(i);
813
814                         current_ir_graph = irg;
815
816                         do_irg_opt(irg, "local");
817                         do_irg_opt(irg, "gcse");
818                         do_irg_opt(irg, "opt-load-store");
819                         do_irg_opt(irg, "local");
820                         do_irg_opt(irg, "control-flow");
821
822                         if (do_irg_opt(irg, "if-conversion")) {
823                                 do_irg_opt(irg, "local");
824                                 do_irg_opt(irg, "control-flow");
825                         }
826
827                         do_irg_opt(irg, "parallelize-mem");
828                 }
829                 timer_stop(t_all_opt);
830
831                 dump_all("-low-opt");
832         }
833
834         if (firm_opt.cc_opt)
835                 mark_private_methods();
836
837         /* set the phase to low */
838         for (i = get_irp_n_irgs() - 1; i >= 0; --i)
839                 set_irg_phase_low(get_irp_irg(i));
840
841         /* all graphs are lowered, set the irp phase to low */
842         set_irp_phase_state(phase_low);
843
844         if (firm_dump.statistic & STAT_FINAL) {
845                 stat_dump_snapshot(input_filename, "final");
846         }
847 }
848
849 /**
850  * Initialize for the Firm-generating back end.
851  */
852 void gen_firm_init(void)
853 {
854         firm_parameter_t params;
855         unsigned         pattern = 0;
856         int              i;
857
858         for (i = 0; i < n_opts; ++i) {
859                 timers[i] = ir_timer_new();
860                 timer_register(timers[i], opts[i].description);
861         }
862         t_verify = ir_timer_new();
863         timer_register(t_verify, "Firm: verify pass");
864         t_vcg_dump = ir_timer_new();
865         timer_register(t_vcg_dump, "Firm: vcg dumping");
866         t_all_opt = ir_timer_new();
867         timer_register(t_all_opt, "Firm: all optimizations");
868
869         if (firm_dump.stat_pattern)
870                 pattern |= FIRMSTAT_PATTERN_ENABLED;
871
872         if (firm_dump.stat_dag)
873                 pattern |= FIRMSTAT_COUNT_DAG;
874
875         memset(&params, 0, sizeof(params));
876         params.size                  = sizeof(params);
877         params.enable_statistics     = firm_dump.statistic == STAT_NONE ? 0 :
878                 FIRMSTAT_ENABLED | FIRMSTAT_COUNT_STRONG_OP | FIRMSTAT_COUNT_CONSTS
879                 | pattern;
880         params.initialize_local_func = uninitialized_local_var;
881         params.cc_mask               = 0; /* no regparam, cdecl */
882         params.builtin_dbg           = NULL;
883
884         ir_init(&params);
885
886         if (firm_be_opt.selection == BE_FIRM_BE) {
887                 const backend_params *be_params = be_get_backend_param();
888
889                 if (be_params->do_dw_lowering)
890                         set_opt_enabled("lower-dw", true);
891
892                 arch_create_intrinsic   = be_params->arch_create_intrinsic_fkt;
893                 create_intrinsic_ctx    = be_params->create_intrinsic_ctx;
894
895                 ad_param                = be_params->dep_param;
896                 if_conv_info            = be_params->if_conv_info;
897         }
898
899         edges_init_dbg(firm_opt.vrfy_edges);
900
901         /* Sel node cannot produce NULL pointers */
902         set_opt_sel_based_null_check_elim(1);
903
904         /* dynamic dispatch works currently only if whole world scenarios */
905         set_opt_dyn_meth_dispatch(0);
906
907         arch_dep_init(arch_factory);
908
909         /* do not run architecture dependent optimizations in building phase */
910         arch_dep_set_opts(arch_dep_none);
911
912         do_node_verification((firm_verification_t) firm_opt.vrfy);
913         if (firm_dump.filter)
914                 only_dump_method_with_name(new_id_from_str(firm_dump.filter));
915
916         if (firm_opt.enabled) {
917                 set_optimize(1);
918                 set_opt_constant_folding(firm_opt.const_folding);
919                 set_opt_algebraic_simplification(firm_opt.const_folding);
920                 set_opt_cse(firm_opt.cse);
921                 set_opt_global_cse(0);
922                 set_opt_unreachable_code(1);
923                 set_opt_control_flow(firm_opt.control_flow);
924                 set_opt_control_flow_weak_simplification(1);
925                 set_opt_control_flow_strong_simplification(1);
926         } else {
927                 set_optimize(0);
928         }
929
930         /* do not dump entity ld names */
931         dump_ld_names(0);
932 }
933
934 /**
935  * Called, after the Firm generation is completed,
936  * do all optimizations and backend call here.
937  *
938  * @param out                a file handle for the output, may be NULL
939  * @param input_filename     the name of the (main) source file
940  * @param c_mode             non-zero if "C" was compiled
941  * @param new_firm_const_exists  non-zero, if the const attribute was used on functions
942  */
943 void gen_firm_finish(FILE *out, const char *input_filename, int c_mode,
944                      int new_firm_const_exists)
945 {
946         int i;
947
948 #if 0
949         if (firm_opt.enable_statev) {
950                 char buf[1024];
951                 snprintf(buf, sizeof(buf), "%s.ev", input_filename);
952                 ir_stat_ev_begin(input_filename, firm_opt.statev_filter);
953                 ir_stat_ev_compilation_unit(input_filename);
954         }
955 #endif
956
957         firm_const_exists = new_firm_const_exists;
958
959         /* the general for dumping option must be set, or the others will not work*/
960         firm_dump.ir_graph
961                 = (a_byte) (firm_dump.ir_graph | firm_dump.all_phases | firm_dump.extbb);
962
963         dump_keepalive_edges(1);
964         dump_consts_local(1);
965         dump_dominator_information(1);
966         dump_loop_information(0);
967
968         if (!firm_dump.edge_labels)
969                 turn_off_edge_labels();
970
971         /* FIXME: cloning might ADD new graphs. */
972         irg_dump_no = calloc(get_irp_last_idx(), sizeof(*irg_dump_no));
973
974         if (firm_dump.all_types) {
975                 dump_all_types("");
976                 if (! c_mode) {
977                         dump_class_hierarchy(0, "");
978                         dump_class_hierarchy(1, "-with-entities");
979                 }
980         }
981
982         /* finalize all graphs */
983         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
984                 ir_graph *irg = get_irp_irg(i);
985                 irg_finalize_cons(irg);
986         }
987         dump_all("");
988
989         timer_push(t_verify);
990         tr_vrfy();
991         timer_pop(t_verify);
992
993         /* all graphs are finalized, set the irp phase to high */
994         set_irp_phase_state(phase_high);
995
996         /* BEWARE: kill unreachable code before doing compound lowering */
997         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
998                 ir_graph *irg = get_irp_irg(i);
999                 do_irg_opt(irg, "control-flow");
1000         }
1001
1002         /* lower all compound call return values */
1003         lower_compound_params();
1004
1005         /* computes the sizes of all types that are still not computed */
1006         compute_type_sizes();
1007
1008         /* lower copyb nodes */
1009         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
1010                 ir_graph *irg = get_irp_irg(i);
1011                 lower_CopyB(irg, 128, 4);
1012         }
1013
1014         if (firm_dump.statistic & STAT_BEFORE_OPT) {
1015                 stat_dump_snapshot(input_filename, "noopt");
1016         }
1017
1018         if (firm_opt.enabled)
1019                 do_firm_optimizations(input_filename);
1020
1021         if (firm_opt.lower)
1022                 do_firm_lowering(input_filename);
1023
1024         /* computes the sizes of all frame types */
1025         compute_frame_type_sizes();
1026
1027         /* set the phase to low */
1028         for (i = get_irp_n_irgs() - 1; i >= 0; --i)
1029                 set_irg_phase_low(get_irp_irg(i));
1030
1031         if (firm_dump.statistic & STAT_FINAL_IR)
1032                 stat_dump_snapshot(input_filename, "final-ir");
1033
1034         /* run the code generator */
1035         if (firm_be_opt.selection != BE_NONE)
1036                 do_codegen(out, input_filename);
1037
1038         if (firm_dump.statistic & STAT_FINAL)
1039                 stat_dump_snapshot(input_filename, "final");
1040 }
1041
1042 int firm_opt_option(const char *opt)
1043 {
1044         bool enable = true;
1045         if (strncmp(opt, "no-", 3) == 0) {
1046                 enable = false;
1047                 opt = opt + 3;
1048         }
1049
1050         opt_config_t *config = get_opt(opt);
1051         if (config == NULL || (config->flags & OPT_FLAG_HIDE_OPTIONS))
1052                 return 0;
1053
1054         config->flags &= ~OPT_FLAG_ENABLED;
1055         config->flags |= enable ? OPT_FLAG_ENABLED : 0;
1056         return 1;
1057 }
1058
1059 void firm_opt_option_help(void)
1060 {
1061         int i;
1062
1063         for (i = 0; i < n_opts; ++i) {
1064                 char buf[1024];
1065                 char buf2[1024];
1066
1067                 const opt_config_t *config = &opts[i];
1068                 if (config->flags & OPT_FLAG_HIDE_OPTIONS)
1069                         continue;
1070
1071                 snprintf(buf2, sizeof(buf2), "firm: enable %s", config->description);
1072                 print_option_help(config->name, buf2);
1073                 snprintf(buf, sizeof(buf), "no-%s", config->name);
1074                 snprintf(buf2, sizeof(buf2), "firm: disable %s", config->description);
1075                 print_option_help(buf, buf2);
1076         }
1077 }
1078
1079 /**
1080  * Do very early initializations
1081  */
1082 void firm_early_init(void)
1083 {
1084         /* arg: need this here for command line options */
1085         be_opt_register();
1086
1087         enable_safe_defaults();
1088 }