From reverse_condition() from jump.c
reverse_condition (enum rtx_code code)
All the cases except the last one returns a value, so the compiler
should be able to convert this switch statement to something like
code -= LOWER_BOUND;
if ((unsigned) code > UPPER_BOUND)
tem = cases[code];
if (tem == DEFAULT_CASE)
I think this is a win for both code size and speed on most, if not
This kind of switch should be fairly common, and people may not like
to use an array themselves if the switch condition is an enum, just
like reverse_condition() in jump.c.
tree-ssa may be a good place to detect this. I don't know if the
implementation should be done in tree-ssa or at expand time. One
thing we can do is that just like CALL_EXPR_TAILCALL, we could flag
this kind of switch statement in tree-ssa and then emit an optimized
switch statement at the expand time.
Confirmed, one thing that needs to be done to do this optimization is combine all the return
statements into one block for the switch statement, I think I can add that to tree-ssa-return.
Some hope of getting this fixed:
Kazu, is this still not optimized properly?
This was fixed by:
2008-07-01 Martin Jambor <email@example.com>
* Makefile.in (tree-switch-conversion.o): Add.
(OBJS-common): Add tree-swtch-conversion.o.
* passes.c (init_optimization_passes): Add pass_convert_switch.
* tree-pass.h: (pass_convert_switch): Add.
* tree-switch-conversion.c: New file.
* gcc.dg/tree-ssa/cswtch.c: New testcase.
* common.opt (ftree-cswtch): New option.
* params.h (PARAM_SWITCH_CONVERSION_BRANCH_RATIO): New parameter.
* params.def (PARAM_SWITCH_CONVERSION_BRANCH_RATIO): New parameter.
* opts.c (decode_options): Set flag_tree_switch_conversion when
optimization level is >= 2.
* doc/invoke.texi (Optimize Options): Added description of
-ftree-swtch-conversion and switch-conversion-max-branch-ratio.