Use streq() instead of strcmp() == 0.
[cparser] / driver / firm_opt.c
1 /**
2  *
3  * @file firm_opt.c -- Firm-generating back end optimizations.
4  *
5  * (C) 2005-2010  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_timing.h"
21 #include "ast2firm.h"
22 #include "adt/strutil.h"
23 #include "adt/util.h"
24
25 /* optimization settings */
26 struct a_firm_opt {
27         bool     const_folding;   /**< enable constant folding */
28         bool     cse;             /**< enable common-subexpression elimination */
29         bool     confirm;         /**< enable Confirm optimization */
30         bool     muls;            /**< enable architecture dependent mul optimization */
31         bool     divs;            /**< enable architecture dependent div optimization */
32         bool     mods;            /**< enable architecture dependent mod optimization */
33         bool     alias_analysis;  /**< enable Alias Analysis */
34         bool     strict_alias;    /**< enable strict Alias Analysis (using type based AA) */
35         bool     no_alias;        /**< no aliasing possible. */
36         bool     verify;          /**< Firm verifier setting */
37         bool     check_all;       /**< enable checking all Firm phases */
38         int      clone_threshold; /**< The threshold value for procedure cloning. */
39         unsigned inline_maxsize;  /**< Maximum function size for inlining. */
40         unsigned inline_threshold;/**< Inlining benefice threshold. */
41         bool     verify_edges;    /**< verify edges */
42 };
43
44 /** statistic options */
45 typedef enum a_firmstat_selection_tag {
46         STAT_NONE        = 0x00000000,
47         STAT_BEFORE_OPT  = 0x00000001,
48         STAT_AFTER_OPT   = 0x00000002,
49         STAT_AFTER_LOWER = 0x00000004,
50         STAT_FINAL_IR    = 0x00000008,
51         STAT_FINAL       = 0x00000010,
52 } a_firmstat_selection;
53
54 /* dumping options */
55 struct a_firm_dump {
56         bool debug_print;   /**< enable debug print */
57         bool all_types;     /**< dump the All_types graph */
58         bool no_blocks;     /**< dump non-blocked graph */
59         bool extbb;         /**< dumps extended basic blocks */
60         bool ir_graph;      /**< dump all graphs */
61         bool all_phases;    /**< dump the IR graph after all phases */
62         bool statistic;     /**< Firm statistic setting */
63         bool stat_pattern;  /**< enable Firm statistic pattern */
64         bool stat_dag;      /**< enable Firm DAG statistic */
65 };
66
67 struct a_firm_be_opt {
68         bool selection;
69         bool node_stat;
70 };
71
72 /* optimization settings */
73 static struct a_firm_opt firm_opt = {
74         .const_folding    =  true,
75         .cse              =  true,
76         .confirm          =  true,
77         .muls             =  true,
78         .divs             =  true,
79         .mods             =  true,
80         .alias_analysis   =  true,
81         .strict_alias     =  false,
82         .no_alias         =  false,
83         .verify           =  FIRM_VERIFICATION_ON,
84         .check_all        =  true,
85         .clone_threshold  =  DEFAULT_CLONE_THRESHOLD,
86         .inline_maxsize   =  750,
87         .inline_threshold =  0,
88         .verify_edges     =  false,
89 };
90
91 /* dumping options */
92 static struct a_firm_dump firm_dump = {
93         .debug_print  = false,
94         .all_types    = false,
95         .no_blocks    = false,
96         .extbb        = false,
97         .ir_graph     = false,
98         .all_phases   = false,
99         .statistic    = STAT_NONE,
100         .stat_pattern = 0,
101         .stat_dag     = 0,
102 };
103
104 #define X(a)  a, sizeof(a)-1
105
106 /** Parameter description structure */
107 static const struct params {
108   const char *option;      /**< name of the option */
109   size_t     opt_len;      /**< length of the option string */
110   bool       *flag;        /**< address of variable to set/reset */
111   bool       set;          /**< iff true, variable will be set, else reset */
112   const char *description; /**< description of this option */
113 } firm_options[] = {
114   /* firm optimization options */
115   { X("no-opt"),                 NULL,                       0, "disable all FIRM optimizations" },
116   { X("cse"),                    &firm_opt.cse,              1, "enable common subexpression elimination" },
117   { X("no-cse"),                 &firm_opt.cse,              0, "disable common subexpression elimination" },
118   { X("const-fold"),             &firm_opt.const_folding,    1, "enable constant folding" },
119   { X("no-const-fold"),          &firm_opt.const_folding,    0, "disable constant folding" },
120   { X("inline-max-size=<size>"), NULL,                       0, "set maximum size for function inlining" },
121   { X("inline-threshold=<size>"),NULL,                       0, "set benefice threshold for function inlining" },
122   { X("confirm"),                &firm_opt.confirm,          1, "enable Confirm optimization" },
123   { X("no-confirm"),             &firm_opt.confirm,          0, "disable Confirm optimization" },
124   { X("opt-mul"),                &firm_opt.muls,             0, "enable multiplication optimization" },
125   { X("no-opt-mul"),             &firm_opt.muls,             0, "disable multiplication optimization" },
126   { X("opt-div"),                &firm_opt.divs,             0, "enable division optimization" },
127   { X("no-opt-div"),             &firm_opt.divs,             0, "disable division optimization" },
128   { X("opt-mod"),                &firm_opt.mods,             0, "enable remainder optimization" },
129   { X("no-opt-mod"),             &firm_opt.mods,             0, "disable remainder optimization" },
130   { X("opt-alias"),              &firm_opt.alias_analysis,   1, "enable alias analysis" },
131   { X("no-opt-alias"),           &firm_opt.alias_analysis,   0, "disable alias analysis" },
132   { X("alias"),                  &firm_opt.no_alias,         0, "aliasing occurs" },
133   { X("no-alias"),               &firm_opt.no_alias,         1, "no aliasing occurs" },
134   { X("strict-aliasing"),        &firm_opt.strict_alias,     1, "strict alias rules" },
135   { X("no-strict-aliasing"),     &firm_opt.strict_alias,     0, "strict alias rules" },
136   { X("clone-threshold=<value>"),NULL,                       0, "set clone threshold to <value>" },
137
138   /* other firm regarding options */
139   { X("verify-off"),             &firm_opt.verify,           FIRM_VERIFICATION_OFF,    "disable node verification" },
140   { X("verify-on"),              &firm_opt.verify,           FIRM_VERIFICATION_ON,     "enable node verification" },
141   { X("verify-report"),          &firm_opt.verify,           FIRM_VERIFICATION_REPORT, "node verification, report only" },
142   { X("check-all"),              &firm_opt.check_all,        1, "enable checking all Firm phases" },
143   { X("no-check-all"),           &firm_opt.check_all,        0, "disable checking all Firm phases" },
144   { X("verify-edges-on"),        &firm_opt.verify_edges,     1, "enable out edge verification" },
145   { X("verify-edges-off"),       &firm_opt.verify_edges,     0, "disable out edge verification" },
146
147   /* dumping */
148   { X("dump-ir"),                &firm_dump.ir_graph,        1, "dump IR graph" },
149   { X("dump-all-types"),         &firm_dump.all_types,       1, "dump graph of all types" },
150   { X("dump-no-blocks"),         &firm_dump.no_blocks,       1, "dump non-blocked graph" },
151   { X("dump-extbb"),             &firm_dump.extbb,           1, "dump extended basic blocks" },
152   { X("dump-all-phases"),        &firm_dump.all_phases,      1, "dump graphs for all optimization phases" },
153   { X("dump-filter=<string>"),   NULL,                       0, "set dumper filter" },
154
155   /* misc */
156   { X("stat-before-opt"),        &firm_dump.statistic,       STAT_BEFORE_OPT,  "Firm statistic output before optimizations" },
157   { X("stat-after-opt"),         &firm_dump.statistic,       STAT_AFTER_OPT,   "Firm statistic output after optimizations" },
158   { X("stat-after-lower"),       &firm_dump.statistic,       STAT_AFTER_LOWER, "Firm statistic output after lowering" },
159   { X("stat-final-ir"),          &firm_dump.statistic,       STAT_FINAL_IR,    "Firm statistic after final optimization" },
160   { X("stat-final"),             &firm_dump.statistic,       STAT_FINAL,       "Firm statistic after code generation" },
161   { X("stat-pattern"),           &firm_dump.stat_pattern,    1, "Firm statistic calculates most used pattern" },
162   { X("stat-dag"),               &firm_dump.stat_dag,        1, "Firm calculates DAG statistics" },
163 };
164
165 #undef X
166
167 static ir_timer_t *t_vcg_dump;
168 static ir_timer_t *t_verify;
169 static ir_timer_t *t_all_opt;
170 static bool do_irg_opt(ir_graph *irg, const char *name);
171
172 /** dump all the graphs depending on cond */
173
174 static void dump_all(const char *suffix)
175 {
176         if (!firm_dump.ir_graph)
177                 return;
178
179         timer_push(t_vcg_dump);
180         dump_all_ir_graphs(suffix);
181         timer_pop(t_vcg_dump);
182 }
183
184 /* entities of runtime functions */
185 ir_entity_ptr rts_entities[rts_max];
186
187 /**
188  * Map runtime functions.
189  */
190 static void rts_map(void)
191 {
192         static const struct {
193                 ir_entity_ptr *ent; /**< address of the rts entity */
194                 i_mapper_func func; /**< mapper function. */
195         } mapper[] = {
196                 /* integer */
197                 { &rts_entities[rts_abs],     i_mapper_abs },
198                 { &rts_entities[rts_labs],    i_mapper_abs },
199                 { &rts_entities[rts_llabs],   i_mapper_abs },
200                 { &rts_entities[rts_imaxabs], i_mapper_abs },
201
202                 /* double -> double */
203                 { &rts_entities[rts_fabs],    i_mapper_abs },
204                 { &rts_entities[rts_sqrt],    i_mapper_sqrt },
205                 { &rts_entities[rts_cbrt],    i_mapper_cbrt },
206                 { &rts_entities[rts_pow],     i_mapper_pow },
207                 { &rts_entities[rts_exp],     i_mapper_exp },
208                 { &rts_entities[rts_exp2],    i_mapper_exp },
209                 { &rts_entities[rts_exp10],   i_mapper_exp },
210                 { &rts_entities[rts_log],     i_mapper_log },
211                 { &rts_entities[rts_log2],    i_mapper_log2 },
212                 { &rts_entities[rts_log10],   i_mapper_log10 },
213                 { &rts_entities[rts_sin],     i_mapper_sin },
214                 { &rts_entities[rts_cos],     i_mapper_cos },
215                 { &rts_entities[rts_tan],     i_mapper_tan },
216                 { &rts_entities[rts_asin],    i_mapper_asin },
217                 { &rts_entities[rts_acos],    i_mapper_acos },
218                 { &rts_entities[rts_atan],    i_mapper_atan },
219                 { &rts_entities[rts_sinh],    i_mapper_sinh },
220                 { &rts_entities[rts_cosh],    i_mapper_cosh },
221                 { &rts_entities[rts_tanh],    i_mapper_tanh },
222
223                 /* float -> float */
224                 { &rts_entities[rts_fabsf],   i_mapper_abs },
225                 { &rts_entities[rts_sqrtf],   i_mapper_sqrt },
226                 { &rts_entities[rts_cbrtf],   i_mapper_cbrt },
227                 { &rts_entities[rts_powf],    i_mapper_pow },
228                 { &rts_entities[rts_expf],    i_mapper_exp },
229                 { &rts_entities[rts_exp2f],   i_mapper_exp },
230                 { &rts_entities[rts_exp10f],  i_mapper_exp },
231                 { &rts_entities[rts_logf],    i_mapper_log },
232                 { &rts_entities[rts_log2f],   i_mapper_log2 },
233                 { &rts_entities[rts_log10f],  i_mapper_log10 },
234                 { &rts_entities[rts_sinf],    i_mapper_sin },
235                 { &rts_entities[rts_cosf],    i_mapper_cos },
236                 { &rts_entities[rts_tanf],    i_mapper_tan },
237                 { &rts_entities[rts_asinf],   i_mapper_asin },
238                 { &rts_entities[rts_acosf],   i_mapper_acos },
239                 { &rts_entities[rts_atanf],   i_mapper_atan },
240                 { &rts_entities[rts_sinhf],   i_mapper_sinh },
241                 { &rts_entities[rts_coshf],   i_mapper_cosh },
242                 { &rts_entities[rts_tanhf],   i_mapper_tanh },
243
244                 /* long double -> long double */
245                 { &rts_entities[rts_fabsl],   i_mapper_abs },
246                 { &rts_entities[rts_sqrtl],   i_mapper_sqrt },
247                 { &rts_entities[rts_cbrtl],   i_mapper_cbrt },
248                 { &rts_entities[rts_powl],    i_mapper_pow },
249                 { &rts_entities[rts_expl],    i_mapper_exp },
250                 { &rts_entities[rts_exp2l],   i_mapper_exp },
251                 { &rts_entities[rts_exp10l],  i_mapper_exp },
252                 { &rts_entities[rts_logl],    i_mapper_log },
253                 { &rts_entities[rts_log2l],   i_mapper_log2 },
254                 { &rts_entities[rts_log10l],  i_mapper_log10 },
255                 { &rts_entities[rts_sinl],    i_mapper_sin },
256                 { &rts_entities[rts_cosl],    i_mapper_cos },
257                 { &rts_entities[rts_tanl],    i_mapper_tan },
258                 { &rts_entities[rts_asinl],   i_mapper_asin },
259                 { &rts_entities[rts_acosl],   i_mapper_acos },
260                 { &rts_entities[rts_atanl],   i_mapper_atan },
261                 { &rts_entities[rts_sinhl],   i_mapper_sinh },
262                 { &rts_entities[rts_coshl],   i_mapper_cosh },
263                 { &rts_entities[rts_tanhl],   i_mapper_tanh },
264
265                 /* string */
266                 { &rts_entities[rts_strcmp],  i_mapper_strcmp },
267                 { &rts_entities[rts_strncmp], i_mapper_strncmp },
268                 { &rts_entities[rts_strcpy],  i_mapper_strcpy },
269                 { &rts_entities[rts_strlen],  i_mapper_strlen },
270                 { &rts_entities[rts_memcpy],  i_mapper_memcpy },
271                 { &rts_entities[rts_mempcpy], i_mapper_mempcpy },
272                 { &rts_entities[rts_memmove], i_mapper_memmove },
273                 { &rts_entities[rts_memset],  i_mapper_memset },
274                 { &rts_entities[rts_memcmp],  i_mapper_memcmp }
275         };
276         i_record rec[lengthof(mapper)];
277         size_t   n_map = 0;
278
279         for (size_t i = 0; i != lengthof(mapper); ++i) {
280                 if (*mapper[i].ent != NULL) {
281                         rec[n_map].i_call.kind     = INTRINSIC_CALL;
282                         rec[n_map].i_call.i_ent    = *mapper[i].ent;
283                         rec[n_map].i_call.i_mapper = mapper[i].func;
284                         rec[n_map].i_call.ctx      = NULL;
285                         rec[n_map].i_call.link     = NULL;
286                         ++n_map;
287                 }
288         }
289
290         if (n_map > 0)
291                 lower_intrinsics(rec, n_map, /* part_block_used=*/0);
292 }
293
294 static int *irg_dump_no;
295
296 static void do_stred(ir_graph *irg)
297 {
298         opt_osr(irg, osr_flag_default | osr_flag_keep_reg_pressure | osr_flag_ignore_x86_shift);
299 }
300
301 static void after_inline_opt(ir_graph *irg)
302 {
303         do_irg_opt(irg, "scalar-replace");
304         do_irg_opt(irg, "local");
305         do_irg_opt(irg, "control-flow");
306         do_irg_opt(irg, "combo");
307 }
308
309 static void do_inline(void)
310 {
311         inline_functions(firm_opt.inline_maxsize, firm_opt.inline_threshold,
312                          after_inline_opt);
313 }
314
315 static void do_cloning(void)
316 {
317         proc_cloning((float) firm_opt.clone_threshold);
318 }
319
320 static void do_lower_mux(ir_graph *irg)
321 {
322         lower_mux(irg, NULL);
323 }
324
325 static void do_gcse(ir_graph *irg)
326 {
327         set_opt_global_cse(1);
328         optimize_graph_df(irg);
329         set_opt_global_cse(0);
330 }
331
332 typedef enum opt_target {
333         OPT_TARGET_IRG, /**< optimization function works on a single graph */
334         OPT_TARGET_IRP  /**< optimization function works on the complete program */
335 } opt_target_t;
336
337 typedef enum opt_flags {
338         OPT_FLAG_NONE         = 0,
339         OPT_FLAG_ENABLED      = 1 << 0, /**< enable the optimization */
340         OPT_FLAG_NO_DUMP      = 1 << 1, /**< don't dump after transformation */
341         OPT_FLAG_NO_VERIFY    = 1 << 2, /**< don't verify after transformation */
342         OPT_FLAG_HIDE_OPTIONS = 1 << 3, /**< do not automatically process
343                                              -foptions for this transformation */
344         OPT_FLAG_ESSENTIAL    = 1 << 4, /**< output won't work without this pass
345                                              so we need it even with -O0 */
346 } opt_flags_t;
347
348 typedef void (*transform_irg_func)(ir_graph *irg);
349 typedef void (*transform_irp_func)(void);
350
351 typedef struct {
352         opt_target_t  target;
353         const char   *name;
354         union {
355                 transform_irg_func transform_irg;
356                 transform_irp_func transform_irp;
357         } u;
358         const char   *description;
359         opt_flags_t   flags;
360         ir_timer_t   *timer;
361 } opt_config_t;
362
363 static opt_config_t opts[] = {
364 #define IRG(a, b, c, d) { OPT_TARGET_IRG, a, .u.transform_irg = (transform_irg_func)b, c, d }
365 #define IRP(a, b, c, d) { OPT_TARGET_IRP, a, .u.transform_irp = b,                     c, d }
366         IRG("bool",              opt_bool,                 "bool simplification",                                   OPT_FLAG_NONE),
367         IRG("combo",             combo,                    "combined CCE, UCE and GVN",                             OPT_FLAG_NONE),
368         IRG("confirm",           construct_confirms,       "confirm optimization",                                  OPT_FLAG_HIDE_OPTIONS),
369         IRG("control-flow",      optimize_cf,              "optimization of control-flow",                          OPT_FLAG_HIDE_OPTIONS),
370         IRG("dead",              dead_node_elimination,    "dead node elimination",                                 OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY),
371         IRG("deconv",            conv_opt,                 "conv node elimination",                                 OPT_FLAG_NONE),
372         IRG("fp-vrp",            fixpoint_vrp,             "fixpoint value range propagation",                      OPT_FLAG_NONE),
373         IRG("frame",             opt_frame_irg,            "remove unused frame entities",                          OPT_FLAG_NONE),
374         IRG("gvn-pre",           do_gvn_pre,               "global value numbering partial redundancy elimination", OPT_FLAG_NONE),
375         IRG("if-conversion",     opt_if_conv,              "if-conversion",                                         OPT_FLAG_NONE),
376         IRG("invert-loops",      do_loop_inversion,        "loop inversion",                                        OPT_FLAG_NONE),
377         IRG("ivopts",            do_stred,                 "induction variable strength reduction",                 OPT_FLAG_NONE),
378         IRG("local",             optimize_graph_df,        "local graph optimizations",                             OPT_FLAG_HIDE_OPTIONS),
379         IRG("lower",             lower_highlevel_graph,    "lowering",                                              OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_ESSENTIAL),
380         IRG("lower-mux",         do_lower_mux,             "mux lowering",                                          OPT_FLAG_NONE),
381         IRG("opt-load-store",    optimize_load_store,      "load store optimization",                               OPT_FLAG_NONE),
382         IRG("opt-tail-rec",      opt_tail_rec_irg,         "tail-recursion eliminiation",                           OPT_FLAG_NONE),
383         IRG("parallelize-mem",   opt_parallelize_mem,      "parallelize memory",                                    OPT_FLAG_NONE),
384         IRG("gcse",              do_gcse,                  "global common subexpression eliminiation",              OPT_FLAG_NONE),
385         IRG("place",             place_code,               "code placement",                                        OPT_FLAG_NONE),
386         IRG("reassociation",     optimize_reassociation,   "reassociation",                                         OPT_FLAG_NONE),
387         IRG("remove-confirms",   remove_confirms,          "confirm removal",                                       OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY),
388         IRG("remove-phi-cycles", remove_phi_cycles,        "removal of phi cycles",                                 OPT_FLAG_HIDE_OPTIONS),
389         IRG("scalar-replace",    scalar_replacement_opt,   "scalar replacement",                                    OPT_FLAG_NONE),
390         IRG("shape-blocks",      shape_blocks,             "block shaping",                                         OPT_FLAG_NONE),
391         IRG("thread-jumps",      opt_jumpthreading,        "path-sensitive jumpthreading",                          OPT_FLAG_NONE),
392         IRG("unroll-loops",      do_loop_unrolling,        "loop unrolling",                                        OPT_FLAG_NONE),
393         IRG("vrp",               set_vrp_data,             "value range propagation",                               OPT_FLAG_NONE),
394         IRP("inline",            do_inline,                "inlining",                                              OPT_FLAG_NONE),
395         IRP("lower-const",       lower_const_code,         "lowering of constant code",                             OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY | OPT_FLAG_ESSENTIAL),
396         IRP("target-lowering",   be_lower_for_target,      "lowering necessary for target architecture",            OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_ESSENTIAL),
397         IRP("opt-func-call",     optimize_funccalls,       "function call optimization",                            OPT_FLAG_NONE),
398         IRP("opt-proc-clone",    do_cloning,               "procedure cloning",                                     OPT_FLAG_NONE),
399         IRP("remove-unused",     garbage_collect_entities, "removal of unused functions/variables",                 OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY),
400         IRP("rts",               rts_map,                  "optimization of known library functions",               OPT_FLAG_NONE),
401         IRP("opt-cc",            mark_private_methods,     "calling conventions optimization",                      OPT_FLAG_NONE),
402 #undef IRP
403 #undef IRG
404 };
405
406 #define FOR_EACH_OPT(i) for (opt_config_t *i = opts; i != endof(opts); ++i)
407
408 static opt_config_t *get_opt(const char *name)
409 {
410         FOR_EACH_OPT(config) {
411                 if (streq(config->name, name))
412                         return config;
413         }
414
415         return NULL;
416 }
417
418 static void set_opt_enabled(const char *name, bool enabled)
419 {
420         opt_config_t *config = get_opt(name);
421         config->flags = (config->flags & ~OPT_FLAG_ENABLED)
422                 | (enabled ? OPT_FLAG_ENABLED : 0);
423 }
424
425 static bool get_opt_enabled(const char *name)
426 {
427         opt_config_t *config = get_opt(name);
428         return (config->flags & OPT_FLAG_ENABLED) != 0;
429 }
430
431 /**
432  * perform an optimization on a single graph
433  *
434  * @return  true if something changed, false otherwise
435  */
436 static bool do_irg_opt(ir_graph *irg, const char *name)
437 {
438         opt_config_t *const config = get_opt(name);
439         assert(config != NULL);
440         assert(config->target == OPT_TARGET_IRG);
441         if (! (config->flags & OPT_FLAG_ENABLED))
442                 return false;
443
444         ir_graph *const old_irg = current_ir_graph;
445         current_ir_graph = irg;
446
447         timer_push(config->timer);
448         config->u.transform_irg(irg);
449         timer_pop(config->timer);
450
451         if (firm_dump.all_phases && firm_dump.ir_graph) {
452                 dump_ir_graph(irg, name);
453         }
454
455         if (firm_opt.check_all) {
456                 timer_push(t_verify);
457                 irg_verify(irg, VERIFY_ENFORCE_SSA);
458                 timer_pop(t_verify);
459         }
460
461         current_ir_graph = old_irg;
462         return true;
463 }
464
465 static void do_irp_opt(const char *name)
466 {
467         opt_config_t *const config = get_opt(name);
468         assert(config->target == OPT_TARGET_IRP);
469         if (! (config->flags & OPT_FLAG_ENABLED))
470                 return;
471
472         timer_push(config->timer);
473         config->u.transform_irp();
474         timer_pop(config->timer);
475
476         if (firm_dump.ir_graph && firm_dump.all_phases) {
477                 int i;
478                 for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
479                         ir_graph *irg = get_irp_irg(i);
480                         dump_ir_graph(irg, name);
481                 }
482         }
483
484         if (firm_opt.check_all) {
485                 int i;
486                 timer_push(t_verify);
487                 for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
488                         irg_verify(get_irp_irg(i), VERIFY_ENFORCE_SSA);
489                 }
490                 timer_pop(t_verify);
491         }
492 }
493
494 /**
495  * Enable transformations which should be always safe (and cheap) to perform
496  */
497 static void enable_safe_defaults(void)
498 {
499         set_opt_enabled("remove-unused", true);
500         set_opt_enabled("opt-tail-rec", true);
501         set_opt_enabled("opt-func-call", true);
502         set_opt_enabled("reassociation", true);
503         set_opt_enabled("control-flow", true);
504         set_opt_enabled("local", true);
505         set_opt_enabled("lower-const", true);
506         set_opt_enabled("scalar-replace", true);
507         set_opt_enabled("place", true);
508         set_opt_enabled("gcse", true);
509         set_opt_enabled("confirm", true);
510         set_opt_enabled("opt-load-store", true);
511         set_opt_enabled("lower", true);
512         set_opt_enabled("deconv", true);
513         set_opt_enabled("remove-confirms", true);
514         set_opt_enabled("ivopts", true);
515         set_opt_enabled("dead", true);
516         set_opt_enabled("remove-phi-cycles", true);
517         set_opt_enabled("frame", true);
518         set_opt_enabled("combo", true);
519         set_opt_enabled("invert-loops", true);
520         set_opt_enabled("target-lowering", true);
521         set_opt_enabled("rts", true);
522         set_opt_enabled("parallelize-mem", true);
523         set_opt_enabled("opt-cc", true);
524 }
525
526 /**
527  * run all the Firm optimizations
528  *
529  * @param input_filename     the name of the (main) source file
530  */
531 static void do_firm_optimizations(const char *input_filename)
532 {
533         size_t   i;
534         unsigned aa_opt;
535
536         set_opt_alias_analysis(firm_opt.alias_analysis);
537
538         aa_opt = aa_opt_no_opt;
539         if (firm_opt.strict_alias)
540                 aa_opt |= aa_opt_type_based | aa_opt_byte_type_may_alias;
541         if (firm_opt.no_alias)
542                 aa_opt = aa_opt_no_alias;
543
544         set_irp_memory_disambiguator_options(aa_opt);
545
546         /* parameter passing code should set them directly sometime... */
547         set_opt_enabled("confirm", firm_opt.confirm);
548         set_opt_enabled("remove-confirms", firm_opt.confirm);
549
550         /* osr supersedes remove_phi_cycles */
551         if (get_opt_enabled("ivopts"))
552                 set_opt_enabled("remove-phi-cycles", false);
553
554         timer_start(t_all_opt);
555
556         do_irp_opt("rts");
557
558         /* first step: kill dead code */
559         for (i = 0; i < get_irp_n_irgs(); i++) {
560                 ir_graph *irg = get_irp_irg(i);
561                 do_irg_opt(irg, "combo");
562                 do_irg_opt(irg, "local");
563                 do_irg_opt(irg, "control-flow");
564         }
565
566         do_irp_opt("remove-unused");
567         for (i = 0; i < get_irp_n_irgs(); ++i) {
568                 ir_graph *irg = get_irp_irg(i);
569                 do_irg_opt(irg, "opt-tail-rec");
570         }
571         do_irp_opt("opt-func-call");
572         do_irp_opt("lower-const");
573
574         for (i = 0; i < get_irp_n_irgs(); i++) {
575                 ir_graph *irg = get_irp_irg(i);
576
577                 do_irg_opt(irg, "scalar-replace");
578                 do_irg_opt(irg, "invert-loops");
579                 do_irg_opt(irg, "unroll-loops");
580                 do_irg_opt(irg, "local");
581                 do_irg_opt(irg, "reassociation");
582                 do_irg_opt(irg, "local");
583                 do_irg_opt(irg, "gcse");
584                 do_irg_opt(irg, "place");
585
586                 if (firm_opt.confirm) {
587                         /* Confirm construction currently can only handle blocks with only
588                            one control flow predecessor. Calling optimize_cf here removes
589                            Bad predecessors and help the optimization of switch constructs.
590                          */
591                         do_irg_opt(irg, "control-flow");
592                         do_irg_opt(irg, "confirm");
593                         do_irg_opt(irg, "vrp");
594                         do_irg_opt(irg, "local");
595                 }
596
597                 do_irg_opt(irg, "control-flow");
598                 do_irg_opt(irg, "opt-load-store");
599                 do_irg_opt(irg, "fp-vrp");
600                 do_irg_opt(irg, "lower");
601                 do_irg_opt(irg, "deconv");
602                 do_irg_opt(irg, "thread-jumps");
603                 do_irg_opt(irg, "remove-confirms");
604                 do_irg_opt(irg, "gvn-pre");
605                 do_irg_opt(irg, "gcse");
606                 do_irg_opt(irg, "place");
607                 do_irg_opt(irg, "control-flow");
608
609                 if (do_irg_opt(irg, "if-conversion")) {
610                         do_irg_opt(irg, "local");
611                         do_irg_opt(irg, "control-flow");
612                 }
613                 /* this doesn't make too much sense but tests the mux destruction... */
614                 do_irg_opt(irg, "lower-mux");
615
616                 do_irg_opt(irg, "bool");
617                 do_irg_opt(irg, "shape-blocks");
618                 do_irg_opt(irg, "ivopts");
619                 do_irg_opt(irg, "local");
620                 do_irg_opt(irg, "dead");
621         }
622
623         do_irp_opt("inline");
624         do_irp_opt("opt-proc-clone");
625
626         for (i = 0; i < get_irp_n_irgs(); i++) {
627                 ir_graph *irg = get_irp_irg(i);
628                 do_irg_opt(irg, "local");
629                 do_irg_opt(irg, "control-flow");
630                 do_irg_opt(irg, "thread-jumps");
631                 do_irg_opt(irg, "local");
632                 do_irg_opt(irg, "control-flow");
633
634                 if( do_irg_opt(irg, "vrp") ) { // if vrp is enabled
635                         do_irg_opt(irg, "local");
636                         do_irg_opt(irg, "vrp");
637                         do_irg_opt(irg, "local");
638                         do_irg_opt(irg, "vrp");
639                 }
640         }
641
642         if (firm_dump.ir_graph) {
643                 /* recompute backedges for nicer dumps */
644                 for (i = 0; i < get_irp_n_irgs(); i++)
645                         construct_cf_backedges(get_irp_irg(i));
646         }
647
648         dump_all("opt");
649
650         if (firm_dump.statistic & STAT_AFTER_OPT)
651                 stat_dump_snapshot(input_filename, "opt");
652
653         timer_stop(t_all_opt);
654 }
655
656 /**
657  * do Firm lowering
658  *
659  * @param input_filename  the name of the (main) source file
660  */
661 static void do_firm_lowering(const char *input_filename)
662 {
663         int i;
664
665         /* enable architecture dependent optimizations */
666         arch_dep_set_opts((arch_dep_opts_t)
667                         ((firm_opt.muls ? arch_dep_mul_to_shift : arch_dep_none) |
668                          (firm_opt.divs ? arch_dep_div_by_const : arch_dep_none) |
669                          (firm_opt.mods ? arch_dep_mod_by_const : arch_dep_none) ));
670         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
671                 ir_graph *irg = get_irp_irg(i);
672                 do_irg_opt(irg, "reassociation");
673                 do_irg_opt(irg, "local");
674         }
675
676         do_irp_opt("target-lowering");
677
678         if (firm_dump.statistic & STAT_AFTER_LOWER)
679                 stat_dump_snapshot(input_filename, "low");
680
681         timer_start(t_all_opt);
682
683         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
684                 ir_graph *irg = get_irp_irg(i);
685
686                 do_irg_opt(irg, "local");
687                 do_irg_opt(irg, "deconv");
688                 do_irg_opt(irg, "control-flow");
689                 do_irg_opt(irg, "opt-load-store");
690                 do_irg_opt(irg, "gcse");
691                 do_irg_opt(irg, "place");
692                 do_irg_opt(irg, "control-flow");
693
694                 if (do_irg_opt(irg, "vrp")) {
695                         do_irg_opt(irg, "local");
696                         do_irg_opt(irg, "control-flow");
697                         do_irg_opt(irg, "vrp");
698                         do_irg_opt(irg, "local");
699                         do_irg_opt(irg, "control-flow");
700                 }
701
702                 if (do_irg_opt(irg, "if-conversion")) {
703                         do_irg_opt(irg, "local");
704                         do_irg_opt(irg, "control-flow");
705                 }
706
707                 set_irg_state(irg, IR_GRAPH_STATE_NORMALISATION2);
708                 do_irg_opt(irg, "local");
709
710                 do_irg_opt(irg, "parallelize-mem");
711                 do_irg_opt(irg, "frame");
712         }
713         do_irp_opt("remove-unused");
714         do_irp_opt("opt-cc");
715         timer_stop(t_all_opt);
716         dump_all("low-opt");
717
718         if (firm_dump.statistic & STAT_FINAL) {
719                 stat_dump_snapshot(input_filename, "final");
720         }
721 }
722
723 /**
724  * Initialize for the Firm-generating back end.
725  */
726 void gen_firm_init(void)
727 {
728         unsigned pattern = 0;
729
730         FOR_EACH_OPT(i) {
731                 i->timer = ir_timer_new();
732                 timer_register(i->timer, i->description);
733         }
734         t_verify = ir_timer_new();
735         timer_register(t_verify, "Firm: verify pass");
736         t_vcg_dump = ir_timer_new();
737         timer_register(t_vcg_dump, "Firm: vcg dumping");
738         t_all_opt = ir_timer_new();
739         timer_register(t_all_opt, "Firm: all optimizations");
740
741         if (firm_dump.stat_pattern)
742                 pattern |= FIRMSTAT_PATTERN_ENABLED;
743
744         if (firm_dump.stat_dag)
745                 pattern |= FIRMSTAT_COUNT_DAG;
746
747         ir_init(NULL);
748         firm_init_stat(firm_dump.statistic == STAT_NONE ?
749                         0 : FIRMSTAT_ENABLED | FIRMSTAT_COUNT_STRONG_OP
750                         | FIRMSTAT_COUNT_CONSTS | pattern);
751
752         edges_init_dbg(firm_opt.verify_edges);
753
754         /* Sel node cannot produce NULL pointers */
755         set_opt_sel_based_null_check_elim(1);
756
757         /* dynamic dispatch works currently only if whole world scenarios */
758         set_opt_dyn_meth_dispatch(0);
759
760         /* do not run architecture dependent optimizations in building phase */
761         arch_dep_set_opts(arch_dep_none);
762
763         do_node_verification((firm_verification_t) firm_opt.verify);
764         if (firm_dump.extbb)
765                 ir_add_dump_flags(ir_dump_flag_group_extbb);
766         if (firm_dump.no_blocks)
767                 ir_remove_dump_flags(ir_dump_flag_blocks_as_subgraphs);
768
769         set_optimize(1);
770         set_opt_constant_folding(firm_opt.const_folding);
771         set_opt_algebraic_simplification(firm_opt.const_folding);
772         set_opt_cse(firm_opt.cse);
773         set_opt_global_cse(0);
774         set_opt_unreachable_code(1);
775 }
776
777 /**
778  * Called, after the Firm generation is completed,
779  * do all optimizations and backend call here.
780  *
781  * @param out                a file handle for the output, may be NULL
782  * @param input_filename     the name of the (main) source file
783  * @param c_mode             non-zero if "C" was compiled
784  */
785 void gen_firm_finish(FILE *out, const char *input_filename)
786 {
787         int i;
788
789         /* the general for dumping option must be set, or the others will not work*/
790         firm_dump.ir_graph
791                 = (bool) (firm_dump.ir_graph | firm_dump.all_phases | firm_dump.extbb);
792
793         ir_add_dump_flags(ir_dump_flag_keepalive_edges
794                         | ir_dump_flag_consts_local | ir_dump_flag_dominance);
795         ir_remove_dump_flags(ir_dump_flag_loops | ir_dump_flag_ld_names);
796
797         /* FIXME: cloning might ADD new graphs. */
798         irg_dump_no = calloc(get_irp_last_idx(), sizeof(*irg_dump_no));
799
800         if (firm_dump.all_types) {
801                 dump_ir_prog_ext(dump_typegraph, "types.vcg");
802         }
803
804         /* finalize all graphs */
805         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
806                 ir_graph *irg = get_irp_irg(i);
807                 irg_finalize_cons(irg);
808         }
809         dump_all("");
810
811         timer_push(t_verify);
812         tr_verify();
813         timer_pop(t_verify);
814
815         /* all graphs are finalized, set the irp phase to high */
816         set_irp_phase_state(phase_high);
817
818         /* BEWARE: kill unreachable code before doing compound lowering */
819         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
820                 ir_graph *irg = get_irp_irg(i);
821                 do_irg_opt(irg, "control-flow");
822         }
823
824         if (firm_dump.statistic & STAT_BEFORE_OPT) {
825                 stat_dump_snapshot(input_filename, "noopt");
826         }
827
828         do_firm_optimizations(input_filename);
829         do_firm_lowering(input_filename);
830
831         /* set the phase to low */
832         for (i = get_irp_n_irgs() - 1; i >= 0; --i)
833                 set_irg_phase_state(get_irp_irg(i), phase_low);
834
835         if (firm_dump.statistic & STAT_FINAL_IR)
836                 stat_dump_snapshot(input_filename, "final-ir");
837
838         /* run the code generator */
839         ir_timer_t *timer = ir_timer_new();
840         timer_register(timer, "Firm: backend");
841         timer_start(timer);
842         be_main(out, input_filename);
843         timer_stop(timer);
844
845         if (firm_dump.statistic & STAT_FINAL)
846                 stat_dump_snapshot(input_filename, "final");
847 }
848
849 static void disable_all_opts(void)
850 {
851         firm_opt.cse             = false;
852         firm_opt.confirm         = false;
853         firm_opt.muls            = false;
854         firm_opt.divs            = false;
855         firm_opt.mods            = false;
856         firm_opt.alias_analysis  = false;
857         firm_opt.strict_alias    = false;
858         firm_opt.no_alias        = false;
859
860         FOR_EACH_OPT(config) {
861                 if (config->flags & OPT_FLAG_ESSENTIAL) {
862                         config->flags |= OPT_FLAG_ENABLED;
863                 } else {
864                         config->flags &= ~OPT_FLAG_ENABLED;
865                 }
866         }
867 }
868
869 static bool firm_opt_option(const char *opt)
870 {
871         char const* const rest   = strstart(opt, "no-");
872         bool        const enable = rest ? opt = rest, false : true;
873
874         opt_config_t *config = get_opt(opt);
875         if (config == NULL || (config->flags & OPT_FLAG_HIDE_OPTIONS))
876                 return false;
877
878         config->flags &= ~OPT_FLAG_ENABLED;
879         config->flags |= enable ? OPT_FLAG_ENABLED : 0;
880         return true;
881 }
882
883 void firm_option_help(print_option_help_func print_option_help)
884 {
885         print_option_help(firm_options[0].option, firm_options[0].description);
886
887         FOR_EACH_OPT(config) {
888                 char buf[1024];
889                 char buf2[1024];
890
891                 if (config->flags & OPT_FLAG_HIDE_OPTIONS)
892                         continue;
893
894                 snprintf(buf, sizeof(buf), "-f%s", config->name);
895                 snprintf(buf2, sizeof(buf2), "enable %s", config->description);
896                 print_option_help(buf, buf2);
897                 snprintf(buf, sizeof(buf), "-fno-%s", config->name);
898                 snprintf(buf2, sizeof(buf2), "disable %s", config->description);
899                 print_option_help(buf, buf2);
900         }
901
902         for (size_t k = 0; k != lengthof(firm_options); ++k) {
903                 char buf[1024];
904                 char buf2[1024];
905                 snprintf(buf, sizeof(buf), "-f%s", firm_options[k].option);
906                 snprintf(buf2, sizeof(buf2), "%s", firm_options[k].description);
907                 print_option_help(buf, buf2);
908         }
909 }
910
911 int firm_option(const char *const opt)
912 {
913         char const* val;
914         if ((val = strstart(opt, "dump-filter="))) {
915                 ir_set_dump_filter(val);
916                 return 1;
917         } else if ((val = strstart(opt, "clone-threshold="))) {
918                 sscanf(val, "%d", &firm_opt.clone_threshold);
919                 return 1;
920         } else if ((val = strstart(opt, "inline-max-size="))) {
921                 sscanf(val, "%u", &firm_opt.inline_maxsize);
922                 return 1;
923         } else if ((val = strstart(opt, "inline-threshold="))) {
924                 sscanf(val, "%u", &firm_opt.inline_threshold);
925                 return 1;
926         } else if (streq(opt, "no-opt")) {
927                 disable_all_opts();
928                 return 1;
929         }
930
931         size_t const len = strlen(opt);
932         for (size_t i = lengthof(firm_options); i != 0;) {
933                 struct params const* const o = &firm_options[--i];
934                 if (len == o->opt_len && strncmp(opt, o->option, len) == 0) {
935                         /* statistic options do accumulate */
936                         if (o->flag == &firm_dump.statistic)
937                                 *o->flag = (bool) (*o->flag | o->set);
938                         else
939                                 *o->flag = o->set;
940
941                         return 1;
942                 }
943         }
944
945         /* maybe this enables/disables optimizations */
946         if (firm_opt_option(opt))
947                 return 1;
948
949         return 0;
950 }
951
952 static void set_be_option(const char *arg)
953 {
954         int res = be_parse_arg(arg);
955         (void) res;
956         assert(res);
957 }
958
959 static void set_option(const char *arg)
960 {
961         int res = firm_option(arg);
962         (void) res;
963         assert(res);
964 }
965
966 void choose_optimization_pack(int level)
967 {
968         /* apply optimization level */
969         switch(level) {
970         case 0:
971                 set_option("no-opt");
972                 break;
973         case 1:
974                 set_option("no-inline");
975                 break;
976         default:
977         case 4:
978                 /* use_builtins = true; */
979                 /* fallthrough */
980         case 3:
981                 set_option("thread-jumps");
982                 set_option("if-conversion");
983                 /* fallthrough */
984         case 2:
985                 set_option("strict-aliasing");
986                 set_option("inline");
987                 set_option("fp-vrp");
988                 set_option("deconv");
989                 set_be_option("omitfp");
990                 break;
991         }
992 }
993
994 /**
995  * Do very early initializations
996  */
997 void firm_early_init(void)
998 {
999         /* arg: need this here for command line options */
1000         be_opt_register();
1001
1002         enable_safe_defaults();
1003 }