← Articles Indie Development · Essay

switch Is Not if: GCC Splits One switch into Three Machines

The same switch may be compiled by GCC into a jump table, a bit test, or a comparison tree. The thresholds for the three strategies are written in the source code: 8× growth ratio, 3 exits, 64-bit range. Knowing them is what lets you explain those "why was it compiled this way?" surprises.

switch is the most human-language-like thing in the C family: list the cases, handle each one. It looks like all the compiler has to do is copy it into if-else. In reality it doesn’t, and it has more than one approach.

Xoranth wrote an article dissecting GCC switch lowering in January 2024, and it showed up on Hacker News today. This isn’t new research; it’s a guided tour that reads gcc/tree-switch-conversion.cc out loud for people. The reason it’s worth reading is simple: it explains why the five cases you wrote sometimes become a single indirect jump, sometimes become a few cmps, and sometimes become one bt instruction paired with a magic number you never wrote.

I checked the article against GCC’s current master source. The mechanisms line up and the threshold numbers line up too, but details like these drift with versions, so keep the year in mind while reading.

Three machines, chosen in order

The pass that handles GIMPLE_SWITCH in GCC is called pass_lower_switch, and its entry point is switch_decision_tree::analyze_switch_statement. What it does is not “pick one strategy” but a three-step filter:

  1. First try bit testing: compress multiple cases into a single integer bitmask and ask them all at once with bt or a shift plus AND.
  2. For the remaining contiguous runs, try a jump table: compute the index, range-check, and jump through the table.
  3. Whatever remains gets built into a binary comparison tree, and the first two structures can serve as its leaves.

In other words, the final tree is the skeleton, and the jump table and bit test are accelerators hung on its nodes. This also explains why the same switch looks nothing alike in assembly under -O0 and -O2: it’s not that optimization “incidentally” changed it, but that a dedicated pass is deciding its shape.

Jump table: subtract first, then look up

The most intuitive kind. Five cases each call f0 through f4, with values starting at 0:

cmp eax, 4
ja  .L2
jmp [QWORD PTR .L4[0+rax*8]]

A table of function pointers, indexed by the value itself. It’s fine if the values don’t start at 0; GCC first does lea eax, [rdi-97] to shift the base. That’s why writing case 'a' doesn’t defeat the jump table.

The key is the bounds check. The ja line is necessary: if the index is out of range it falls through to default, otherwise any input could make the program jump to an address outside the table. This isn’t a performance decoration; it’s a safety precondition.

A jump table isn’t free. The table itself occupies .rodata, and indirect jumps pay a branch-prediction penalty on modern CPUs. So GCC only uses one when it’s worthwhile.

Bit test: one constant remembers nine cases

There’s a piece of code where case '0' '2' '4' '5' '7' '9' 'A' 'C' 'E' all return the same value. GCC compiles it to:

lea eax, [rdi-48]
cmp eax, 21
ja  .L1
mov edx, 2753205
bt  rdx, rax
jc  .L7

That constant in the middle isn’t random. Written in binary, 2753205 has bits set at exactly 0, 2, 4, 5, 7, 9, 17, 19, 21 — that is, the positions of each character after subtracting 48. Nine cases become one integer, one shift, one bit test. No memory access, no indirect jump, and only one branch.

This is my favorite passage, because it makes “the compiler is smarter than you think” very concrete: you thought you were writing nine branches; it saw a set.

Comparison tree: split the rest by probability

When neither of the above is worthwhile, GCC builds a binary tree, but the split point isn’t the median — it’s a probability-based halving: balance_case_nodes accumulates each case’s execution probability and finds the node that gives the left and right subtrees equal probability as the root.

Where does the probability come from? With PGO it uses the real profile; without it, a uniform distribution. You can also tell it directly with __builtin_expect_with_probability. Few people use this in practice, but it means “which case happens most often” is something the compiler can treat as fact — provided you actually supplied it.

The thresholds are written in the source code

The real substance is the heuristics. I pulled master’s tree-switch-conversion.cc and params.opt and checked them:

Bit testing requires two conditions at once. can_be_handled requires that the span of the whole case value range not exceed one word (64 on a 64-bit machine), and that there be no more than 3 distinct exits (m_max_case_bit_tests = 3). is_beneficial additionally requires the case count to reach a threshold:

(uniq == 1 && count >= 3)
|| (uniq == 2 && count >= 5)
|| (uniq == 3 && count >= 6)

Three cases going to the same place is worth it; three cases going to three different places needs six to be worthwhile. The reason is concrete: the more exits there are, the more conditional branches have to follow the bt, and the saved comparisons get cancelled out.

Jump tables are judged by the last line of can_be_handled:

return lhs <= max_ratio * comparison_count;

Here lhs = 100 * range, range is the span of the value range, and comparison_count is “how many comparisons would be needed if we used a comparison tree instead.” max_ratio comes from -param, defaulting to 800 for speed-first and 300 for size-first (-Os). So the actual rule under -O2/-O3 is:

A jump table is only worthwhile if the value range span ≤ 8 × the number of comparisons.

Under -Os this multiplier becomes 3. That’s why the same code suddenly falls back from a jump table to a comparison tree under -Os — not a bug, but someone tightening the threshold in exchange for a smaller binary.

There’s one more small threshold: case_values_threshold(), whose parameter defaults to 0, meaning “ask the target machine.” So there’s no single answer to “below how many cases should we avoid a jump table” — x86 and ARM give different numbers.

A counterintuitive example

The article has a nice case: 20 cases with values in 0 to 87, where every four consecutive values share one exit. An intuitive calculation: span 88, comparison count 20, 88 < 20 × 8 = 160, so it should use a jump table, right?

GCC doesn’t. The reason is that comparison_count isn’t 20. Consecutive case 0..3 needs only two comparisons to decide (x >= 0 && x <= 3), so the whole thing really needs 10 comparisons. The condition then becomes 88 ≤ 80, which doesn’t hold, so it falls back to a comparison tree.

The point worth remembering from this example isn’t the numbers but this: GCC uses the “honest comparison cost” as the denominator, not the “number of case labels.” If you rewrite case 0: case 1: case 2: case 3: as case 0 ... case 3:, the semantics are the same, but in costing it’s recognized earlier as “one range,” and the result may differ.

When to care

Honestly, most of the time you shouldn’t. This is a heuristic that compiler teams have tuned for twenty years; hand-shaping a switch to cater to it usually just trades readability for an imaginary performance gain.

But there are three situations where knowing these thresholds is worth it:

One, the performance regression from -Os. Going from 8× to 3× turns a batch of switches that used jump tables into comparison trees. If you see “it got 30% slower after only changing compiler flags” on embedded or WASM, this is a reasonable suspect, and it’s worth looking at the -S output instead of guessing.

Two, the memory cost of jump tables. Sparse cases with a large span produce a table that is mostly default. GCC already blocks some of this with the growth ratio, but what it blocks is the cost relative to a comparison tree, not the absolute size. If .rodata suddenly balloons in a hot-path function, it’s worth checking whether some switch got jump-tabled.

Three, security review. That ja range check is the precondition for jump table safety. If you’re reading assembly and see an indirect jump with no bounds check, that’s a real problem, not an optimization choice.

Beyond that, “GCC compiles switch into a jump table” is itself not news, and it constitutes no performance promise. I haven’t run any benchmarks, and I don’t intend to use this article to claim some style is faster. The article gives mechanisms and thresholds; whether to act depends on whether you’ve measured.

Tail end

The article also incidentally exposes a more general fact: the compiler has a whole economics of its own for “control flow you think is mundane.” switch is just the most visible layer; behind it there are if-conversion, loop unrolling, and branch layout, each with its own cost model and threshold parameters.

Knowing these won’t make you write faster programs. But when you see “why was it compiled this way?”, it will save you one blind guess and give you one more effort to spend on -fdump-tree-switchconv or Compiler Explorer. For me, that’s enough.

References