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