HeadlinesBriefing HeadlinesBriefing.com

Switch Lowering in GCC: Jump Tables vs Trees

Hacker News •
×

The article explores how GCC lowers switch statements, comparing jump tables and comparison trees. For dense case values, GCC generates a jump table using -O3 optimization. When values are offset by a constant (e.g., 97-101), GCC subtracts the base and still uses a jump table.

Experiments show GCC uses a threshold of roughly eight entries per case label for jump tables. The compact_7 function with cases 0, 7, 14, 21, 34 compiles to a jump table with default branches. However, the sparse_8 function with cases 0, 8, 16, 24, 40 expands into a tree of comparisons.

The comparison tree visualization shows GCC building an efficient decision structure for sparse cases, testing eax against 16, 24, 40, 0, and 8 to route to the correct function call. All optimizations except bitset lowering translate to clang.

The author notes that only equally spaced values have been tested so far, questioning whether GCC can identify profitable transformations on subsets of cases. The code was slightly edited and certain assertions removed for brevity.

Source: Hacker News · Summarized by HeadlinesBriefing