[llvm-commits] [Patch] Replace switches with lookup tables (PR884)

Hans Wennborg hans at chromium.org
Mon Sep 3 04:21:23 PDT 2012


Hi all,

The attached patch adds code to SimplifyCFG so that it attempts to
turn switch instructions into loads from lookup tables. It works on
switches that are only used to initialize one or more phi nodes in a
common successor basic block, for example:

int f(int x) {
  switch (x) {
  case 0: return 5;
  case 1: return 4;
  case 2: return -2;
  case 5: return 7;
  case 6: return 9;
  default: return 42;
}

This speeds up the code by removing the hard-to-predict jump. It also
reduces code size by removing the code for the jump targets.

With the attached micro benchmark, which hits the non-default cases
about half the time, I get 43% speed-up with my patch.

As a bonus, if the lookup table is small enough to fit in a
target-valid integer, we can replace the load with shift and mask
operations. This seems to perform about the same as with the table,
but I imagine it is much faster for cases when the lookup-table isn't
in cache. It also reduces code size in some situations (e.g. 32 bools
would take 32 bytes in a lookup table, but only 4 bytes in an int.)

When I first discussed this on IRC, it was suggested that maybe the
best place to do this is during the lowering to the selection DAG. In
my patch I've done it on the IR level because it seemed to fit in well
in SimplifyCFG, it was easy to do here, and I was hoping that this
could exploit other IR passes as well. For example, it would be nice
if two nested switches could become two table lookups. That currently
doesn't happen, but maybe it could in the future if we moved code
downwards out of switches more aggressively. If you think having this
in the lowering code is better, I can try to move it there instead.

Please take a look.

Thanks,
Hans
-------------- next part --------------
A non-text attachment was scrubbed...
Name: switch_benchmark.c
Type: text/x-csrc
Size: 993 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20120903/eab005d4/attachment.c>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: switch_to_lookup_table.patch
Type: application/octet-stream
Size: 24885 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20120903/eab005d4/attachment.obj>


More information about the llvm-commits mailing list