Commit b8c7b236

b8c7b236f234Merged

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

Description

perf: constant propagation for simple literal constants

When a constant's initializer is a simple literal (integer, float, string, bool, nil, symbol), inline the literal value at each use site instead of emitting cst_NAME runtime lookup.

N = 100 while i < N # was: while (i < cst_N)

now: while (i < 100)

Enables the C compiler to do further optimizations like loop-unrolling, constant folding in conditions, and dead-code elimination of the cst_N global when it becomes unused.

75/75 tests pass, bootstrap stable.

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

Details

Commit
b8c7b236f234
Parent
d4c69492d081

spinel_codegen.rbmodifiedView file

@@ -733,6 +733,46 @@
733733 -1
734734 end
735735
736+ # If the constant's initializer is a simple literal, return the
737+ # corresponding C expression. Otherwise return "" so callers fall
738+ # back to cst_<name> lookup. Enables propagation of:
739+ # N = 10 → 10 at use sites
740+ # PI = 3.14 → 3.14
741+ # GREETING = "hi" → ("\xff" "hi" + 1)
742+ # OK = true → TRUE
743+ def const_literal_c_value(ci)
744+ if ci < 0 || ci >= @const_expr_ids.length
745+ return ""
746+ end
747+ eid = @const_expr_ids[ci]
748+ if eid < 0
749+ return ""
750+ end
751+ et = @nd_type[eid]
752+ if et == "IntegerNode"
753+ return @nd_value[eid].to_s
754+ end
755+ if et == "FloatNode"
756+ return @nd_content[eid]
757+ end
758+ if et == "StringNode"
759+ return c_string_literal(@nd_content[eid])
760+ end
761+ if et == "TrueNode"
762+ return "TRUE"
763+ end
764+ if et == "FalseNode"
765+ return "FALSE"
766+ end
767+ if et == "NilNode"
768+ return "0"
769+ end
770+ if et == "SymbolNode"
771+ return compile_symbol_literal(@nd_content[eid])
772+ end
773+ ""
774+ end
775+
736776 # Find method in class (search parent chain)
737777 def cls_find_method(ci, mname)
738778 names = @cls_meth_names[ci].split(";")
@@ -10578,6 +10618,11 @@
1057810618 end
1057910619 ci = find_const_idx(@nd_name[nid])
1058010620 if ci >= 0
10621+ # Propagate simple literal constants to their use sites.
10622+ lv = const_literal_c_value(ci)
10623+ if lv != ""
10624+ return lv
10625+ end
1058110626 return "cst_" + @nd_name[nid]
1058210627 end
1058310628 # Check if inside a module method and constant belongs to that module