Commit 9652fc7e

9652fc7e9a96Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified

Description

Lower case/when over int literals to a C switch

A case <int/poly> when <integer literals> compiled to an if/else-if chain of sp_poly_eq (poly subject) or == comparisons. optcarrot's CPU opcode dispatch is a ~256-arm case on the poly @opcode, so sp_poly_eq dominated at ~50% of runtime (perf). Emit a C switch (jump table) over sp_poly_to_i(subj) when every when-condition is an integer literal. optcarrot fps ~99 -> ~429, checksum unchanged (59662).

Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]

Details

Commit
9652fc7e9a96
Parent
669963c7aed7

src/codegen_stmt.cmodifiedView file

@@ -1137,6 +1137,45 @@
11371137 buf_puts(b, ";\n");
11381138 }
11391139
1140+ /* Fast path: `case <int/poly> when <integer literals>` lowers to a C switch
1141+ (jump table) instead of an O(n) sp_poly_eq / int-compare if-chain. This is
1142+ the optcarrot CPU opcode dispatch (~256 whens); the poly if-chain made
1143+ sp_poly_eq ~50% of runtime. */
1144+ if (pred >= 0 && (pt == TY_POLY || pt == TY_INT) && nw > 0) {
1145+ int all_int = 1;
1146+ for (int w = 0; w < nw && all_int; w++) {
1147+ int wc = 0; const int *conds = nt_arr(nt, whens[w], "conditions", &wc);
1148+ if (wc == 0) { all_int = 0; break; }
1149+ for (int j = 0; j < wc; j++) {
1150+ const char *cty = nt_type(nt, conds[j]);
1151+ if (!cty || strcmp(cty, "IntegerNode")) { all_int = 0; break; }
1152+ }
1153+ }
1154+ if (all_int) {
1155+ emit_indent(b, indent);
1156+ if (pt == TY_POLY) buf_printf(b, "switch (sp_poly_to_i(_t%d)) {\n", t);
1157+ else buf_printf(b, "switch (_t%d) {\n", t);
1158+ for (int w = 0; w < nw; w++) {
1159+ int wc = 0; const int *conds = nt_arr(nt, whens[w], "conditions", &wc);
1160+ for (int j = 0; j < wc; j++) {
1161+ emit_indent(b, indent);
1162+ buf_printf(b, "case %lldLL:\n", (long long)nt_int(nt, conds[j], "value", 0));
1163+ }
1164+ emit_indent(b, indent); buf_puts(b, "{\n");
1165+ emit_stmts(c, nt_ref(nt, whens[w], "statements"), b, indent + 1);
1166+ emit_indent(b, indent + 1); buf_puts(b, "break;\n");
1167+ emit_indent(b, indent); buf_puts(b, "}\n");
1168+ }
1169+ if (else_clause >= 0) {
1170+ emit_indent(b, indent); buf_puts(b, "default: {\n");
1171+ emit_stmts(c, nt_ref(nt, else_clause, "statements"), b, indent + 1);
1172+ emit_indent(b, indent); buf_puts(b, "}\n");
1173+ }
1174+ emit_indent(b, indent); buf_puts(b, "}\n");
1175+ return;
1176+ }
1177+ }
1178+
11401179 for (int w = 0; w < nw; w++) {
11411180 int wn = whens[w];
11421181 int wc = 0;