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