From 70e5bcf4e773869787acf0cb5fe9e7f59ccd84f9 Mon Sep 17 00:00:00 2001 From: Vishvananda Abrams Date: Sun, 15 Nov 2026 23:43:53 +0000 Subject: [PATCH 1/2] Reuse Wasm locals with disjoint live ranges --- dev/frontend_source_sets.mk | 2 +- dev/src/wasm/local_cleanup.cpp | 3 + dev/src/wasm/local_lifetimes.cpp | 256 ++++++++++++++++++ dev/src/wasm/local_lifetimes.h | 11 + .../regression/600-local-storage-lifetimes.t | 41 +++ .../600-local-storage-lifetimes.wasm-expect | 89 ++++++ 6 files changed, 401 insertions(+), 1 deletion(-) create mode 100644 dev/src/wasm/local_lifetimes.cpp create mode 100644 dev/src/wasm/local_lifetimes.h create mode 100644 pa37/tests/regression/600-local-storage-lifetimes.t create mode 100644 pa37/tests/regression/600-local-storage-lifetimes.wasm-expect diff --git a/dev/frontend_source_sets.mk b/dev/frontend_source_sets.mk index c10b4a89d..932836ff9 100644 --- a/dev/frontend_source_sets.mk +++ b/dev/frontend_source_sets.mk @@ -77,7 +77,7 @@ FRONTEND_OBJ_BASENAMES_cppgm += lowir/text_lexer lowir/text_parser lowir/text_pa FRONTEND_OBJ_BASENAMES_cppgm += asm/registers # Shared target dispatch and the wasm32 backend (PA37). -FRONTEND_PHASE_BASENAMES_wasm := wasm/bytes wasm/abi wasm/encoder wasm/mir_facts wasm/mir_writer wasm/local_cleanup wasm/validation wasm/module wasm/exception_runtime wasm/exception_payload wasm/exception_plan wasm/select_exceptions wasm/selector wasm/object_places wasm/frame wasm/select_objects wasm/select_calls wasm/nonlocal_jumps wasm/select_varargs wasm/select_builtins wasm/control wasm/control_regions wasm/control_emission wasm/select_instructions wasm/select_atomics wasm/select_switch wasm/select_arithmetic wasm/select_vectors wasm/vector_permute wasm/vector_float wasm/vector_shift wasm/vector_compare wasm/vector_convert wasm/vector_horizontal wasm/vector_integer_math wasm/vector_reciprocal wasm/vector_reductions wasm/vector_carryless wasm/wide_helpers wasm/select_wide wasm/wide_locals wasm/select_wide_arithmetic wasm/select_wide_shift wasm/object_lowering wasm/object_aliases wasm/object_startup wasm/finalization wasm/runtime_inputs wasm/object_writer wasm/object_reader wasm/object_constants wasm/object_customs wasm/object_elements wasm/object_expression_validation wasm/object_features wasm/archive wasm/object_metadata wasm/object_validation wasm/object_code wasm/linker wasm/link_relocations wasm/link_globals wasm/link_data_exports wasm/link_output wasm/backend wasm/assembly_tokens wasm/assembly_parser wasm/assembly_instructions wasm/assembly_object +FRONTEND_PHASE_BASENAMES_wasm := wasm/bytes wasm/abi wasm/encoder wasm/mir_facts wasm/mir_writer wasm/local_cleanup wasm/local_lifetimes wasm/validation wasm/module wasm/exception_runtime wasm/exception_payload wasm/exception_plan wasm/select_exceptions wasm/selector wasm/object_places wasm/frame wasm/select_objects wasm/select_calls wasm/nonlocal_jumps wasm/select_varargs wasm/select_builtins wasm/control wasm/control_regions wasm/control_emission wasm/select_instructions wasm/select_atomics wasm/select_switch wasm/select_arithmetic wasm/select_vectors wasm/vector_permute wasm/vector_float wasm/vector_shift wasm/vector_compare wasm/vector_convert wasm/vector_horizontal wasm/vector_integer_math wasm/vector_reciprocal wasm/vector_reductions wasm/vector_carryless wasm/wide_helpers wasm/select_wide wasm/wide_locals wasm/select_wide_arithmetic wasm/select_wide_shift wasm/object_lowering wasm/object_aliases wasm/object_startup wasm/finalization wasm/runtime_inputs wasm/object_writer wasm/object_reader wasm/object_constants wasm/object_customs wasm/object_elements wasm/object_expression_validation wasm/object_features wasm/archive wasm/object_metadata wasm/object_validation wasm/object_code wasm/linker wasm/link_relocations wasm/link_globals wasm/link_data_exports wasm/link_output wasm/backend wasm/assembly_tokens wasm/assembly_parser wasm/assembly_instructions wasm/assembly_object FRONTEND_OBJ_BASENAMES_lowir2native += lowir/text_writer lowir/assembly_writer lowir/local_names backend/compile $(FRONTEND_PHASE_BASENAMES_wasm) $(FRONTEND_PHASE_BASENAMES_opt) # Object names use the shared UTF-8 decoder without the source lexer. FRONTEND_OBJ_BASENAMES_lowir2native += support/unicode/utf8 diff --git a/dev/src/wasm/local_cleanup.cpp b/dev/src/wasm/local_cleanup.cpp index 508a53ad7..fcea638dd 100644 --- a/dev/src/wasm/local_cleanup.cpp +++ b/dev/src/wasm/local_cleanup.cpp @@ -1,4 +1,5 @@ #include "wasm/mir.h" +#include "wasm/local_lifetimes.h" namespace wasm { @@ -249,6 +250,8 @@ void cleanup_locals(Function& function, bool optimize) auto& operand = function.operands[inst.operands.first]; operand = uses[operand]; } + if (optimize) + reuse_locals(function); } } // namespace wasm diff --git a/dev/src/wasm/local_lifetimes.cpp b/dev/src/wasm/local_lifetimes.cpp new file mode 100644 index 000000000..a6c757df4 --- /dev/null +++ b/dev/src/wasm/local_lifetimes.cpp @@ -0,0 +1,256 @@ +#include "wasm/local_lifetimes.h" + +#include +#include +#include + +namespace wasm { +namespace { + +const uint32_t none = ~uint32_t(0); + +bool local_op(Op op) +{ + return op == Op::LocalGet || op == Op::LocalSet || op == Op::LocalTee; +} + +bool stops(Op op) +{ + return op == Op::Br || op == Op::BrTable || op == Op::Else || op == Op::Return || op == Op::Unreachable || + op == Op::Throw || op == Op::ThrowRef; +} + +struct Edge +{ + uint32_t from, to; +}; + +struct Graph +{ + std::vector block, first, predecessor_first, predecessors; +}; + +// Branch operands name enclosing labels, including the function's label. +// Resolve those typed labels before partitioning the selected instruction stream. +bool control_edges(const Function& function, std::vector& edges) +{ + const uint32_t size = static_cast(function.instructions.size()); + std::vector open(1, size), end(size + 1, size), other(size, none); + std::vector branches; + for (uint32_t i = 0; i < size; ++i) + { + const Instruction& inst = function.instructions[i]; + if (inst.op == Op::TryTable) + return false; // Landing edges need exceptional liveness too. + if (inst.op == Op::Block || inst.op == Op::Loop || inst.op == Op::If) + open.push_back(i); + else if (inst.op == Op::End && open.size() > 1) + { + end[open.back()] = i + 1; + open.pop_back(); + } + else if (inst.op == Op::Else) + { + other[open.back()] = i + 1; + branches.push_back(Edge{ i, open.back() }); + } + else if (inst.op == Op::Br || inst.op == Op::BrIf || inst.op == Op::BrTable) + for (uint32_t k = 0; k < inst.operands.count; ++k) + branches.push_back(Edge{ i, open[open.size() - 1 - function.operands[inst.operands.first + k]] }); + } + for (const Edge& edge : branches) + edges.push_back(Edge{ + edge.from, edge.to < size && function.instructions[edge.to].op == Op::Loop ? edge.to + 1 : end[edge.to] }); + for (uint32_t i = 0; i < size; ++i) + { + const Op op = function.instructions[i].op; + if (op == Op::If) + edges.push_back(Edge{ i, other[i] == none ? end[i] : other[i] }); + if (stops(op) && op != Op::Br && op != Op::BrTable && op != Op::Else) + edges.push_back(Edge{ i, size }); + } + return true; +} + +bool graph_for(const Function& function, Graph& graph) +{ + std::vector edges; + if (!control_edges(function, edges)) + return false; + const uint32_t size = static_cast(function.instructions.size()); + std::vector leader(size + 1, 0); + leader[0] = leader[size] = 1; + for (const Edge& edge : edges) + leader[edge.to] = leader[edge.from + 1] = 1; + graph.block.resize(size + 1); + for (uint32_t i = 0; i < size; ++i) + { + if (leader[i]) + graph.first.push_back(i); + graph.block[i] = static_cast(graph.first.size() - 1); + } + const uint32_t count = static_cast(graph.first.size()); + graph.first.push_back(size); + graph.block[size] = count; + graph.predecessor_first.assign(count + 1, 0); + std::vector links; + for (uint32_t b = 0; b + 1 < count; ++b) + if (!stops(function.instructions[graph.first[b + 1] - 1].op)) + edges.push_back(Edge{ graph.first[b + 1] - 1, graph.first[b + 1] }); + for (const Edge& edge : edges) + if (edge.to != size) + { + links.push_back(Edge{ graph.block[edge.from], graph.block[edge.to] }); + ++graph.predecessor_first[links.back().to + 1]; + } + for (uint32_t i = 0; i < count; ++i) + graph.predecessor_first[i + 1] += graph.predecessor_first[i]; + graph.predecessors.resize(links.size()); + std::vector fill = graph.predecessor_first; + for (const Edge& link : links) + graph.predecessors[fill[link.to]++] = link.from; + return true; +} + +struct Life +{ + uint32_t local, first = none, last = 0; + explicit Life(uint32_t index) : local(index) {} +}; + +struct Accesses +{ + std::vector first, positions; + + explicit Accesses(const Function& function) : first(function.locals.size() + 1, 0) + { + for (const Instruction& inst : function.instructions) + if (local_op(inst.op)) + ++first[function.operands[inst.operands.first] + 1]; + for (uint32_t i = 1; i < first.size(); ++i) + first[i] += first[i - 1]; + positions.resize(first.back()); + std::vector fill = first; + for (uint32_t i = 0; i < function.instructions.size(); ++i) + if (local_op(function.instructions[i].op)) + positions[fill[function.operands[function.instructions[i].operands.first]]++] = i; + } +}; + +// Walk backward only where a block reads before writing. Reaching entry +// extends the hull to zero: an implicitly zero-initialized local cannot share +// storage with an earlier value. Stores stop propagation, including loop edges. +bool lifetimes(const Function& function, const Graph& graph, std::vector& lives) +{ + const Accesses accesses(function); + const uint32_t blocks = static_cast(graph.first.size() - 1); + std::vector seen(blocks, none), written(blocks, none), definition(blocks), work; + uint64_t steps = 0; + const uint64_t budget = 32ull * (function.instructions.size() + graph.predecessors.size()) + 1024; + for (uint32_t local = function.parameter_count; local < function.locals.size(); ++local) + { + lives.emplace_back(local); + Life& life = lives.back(); + uint32_t last_block = none; + for (uint32_t k = accesses.first[local]; k < accesses.first[local + 1]; ++k) + { + const uint32_t position = accesses.positions[k], block = graph.block[position]; + life.first = std::min(life.first, position); + life.last = position; + if (last_block != block && function.instructions[position].op == Op::LocalGet) + { + work.push_back(block); + seen[block] = local; + } + last_block = block; + if (function.instructions[position].op != Op::LocalGet && written[block] != local) + { + written[block] = local; + definition[block] = position; + } + } + while (!work.empty()) + { + const uint32_t block = work.back(); + work.pop_back(); + life.first = std::min(life.first, graph.first[block]); + for (uint32_t p = graph.predecessor_first[block]; p < graph.predecessor_first[block + 1]; ++p) + { + if (++steps > budget) + return false; + const uint32_t pred = graph.predecessors[p]; + life.last = std::max(life.last, graph.first[pred + 1] - 1); + life.first = std::min(life.first, written[pred] == local ? definition[pred] : graph.first[pred]); + if (written[pred] != local && seen[pred] != local) + { + seen[pred] = local; + work.push_back(pred); + } + } + } + } + return true; +} + +void place(Function& function, std::vector& lives) +{ + std::sort(lives.begin(), lives.end(), + [](const Life& a, const Life& b) { return a.first < b.first || (a.first == b.first && a.local < b.local); }); + using End = std::pair; + std::priority_queue, std::greater> active; + std::vector mapping(function.locals.size()); + std::vector> free(8); + std::vector placed(function.locals.begin(), function.locals.begin() + function.parameter_count); + for (uint32_t i = 0; i < function.parameter_count; ++i) + mapping[i] = i; + auto group = [](ValueType type) { + return is_reference(type) ? (type == ValueType::FuncRef ? 5 + : type == ValueType::ExternRef ? 6 + : 7) + : 0x7f - static_cast(type); + }; + for (const Life& life : lives) + { + while (!active.empty() && active.top().first < life.first) + { + const uint32_t id = active.top().second; + active.pop(); + free[group(placed[id])].push_back(id); + } + auto& available = free[group(function.locals[life.local])]; + uint32_t id; + if (available.empty()) + { + id = static_cast(placed.size()); + placed.push_back(function.locals[life.local]); + } + else + { + id = available.back(); + available.pop_back(); + } + mapping[life.local] = id; + active.push(End{ life.last, id }); + } + for (const Instruction& inst : function.instructions) + if (local_op(inst.op)) + { + auto& operand = function.operands[inst.operands.first]; + operand = mapping[operand]; + } + function.locals.swap(placed); +} + +} // namespace + +void reuse_locals(Function& function) +{ + if (function.locals.size() < function.parameter_count + 2 || function.instructions.empty()) + return; + Graph graph; + std::vector lives; + if (graph_for(function, graph) && lifetimes(function, graph, lives)) + place(function, lives); +} + +} // namespace wasm diff --git a/dev/src/wasm/local_lifetimes.h b/dev/src/wasm/local_lifetimes.h new file mode 100644 index 000000000..7ba46223d --- /dev/null +++ b/dev/src/wasm/local_lifetimes.h @@ -0,0 +1,11 @@ +#pragma once + +#include "wasm/mir.h" + +namespace wasm { + +// Reuse typed locals with disjoint live hulls. The sparse CFG walk has a +// linear work budget; exhausted budgets leave the selected function intact. +void reuse_locals(Function& function); + +} // namespace wasm diff --git a/pa37/tests/regression/600-local-storage-lifetimes.t b/pa37/tests/regression/600-local-storage-lifetimes.t new file mode 100644 index 000000000..03c607c99 --- /dev/null +++ b/pa37/tests/regression/600-local-storage-lifetimes.t @@ -0,0 +1,41 @@ +// A recursive visitor's mutually exclusive cases need a bounded set of locals. +// Keeping every SSA result in a new Wasm local exhausts Safari's worker stack. +extern "C" __attribute__((noinline)) unsigned visit(unsigned value, unsigned depth) { + if (!depth) return value; + switch (value & 31u) { +#define CASE(n) case n: { unsigned a = (value ^ (n + 11u)) + depth * 3u; unsigned b = visit(a, depth - 1); return b + a * (n + 5u); } + CASE(0) CASE(1) CASE(2) CASE(3) CASE(4) CASE(5) CASE(6) CASE(7) + CASE(8) CASE(9) CASE(10) CASE(11) CASE(12) CASE(13) CASE(14) CASE(15) + CASE(16) CASE(17) CASE(18) CASE(19) CASE(20) CASE(21) CASE(22) CASE(23) + CASE(24) CASE(25) CASE(26) CASE(27) CASE(28) CASE(29) CASE(30) CASE(31) +#undef CASE + } + return 0; +} + +extern "C" unsigned observe(unsigned value, unsigned depth) { + if (depth > 128) return 1; + unsigned add[128]; + unsigned cursor = value; + for (unsigned i = 0; i < depth; ++i) { + unsigned n = cursor & 31u; + cursor = (cursor ^ (n + 11u)) + (depth - i) * 3u; + add[i] = cursor * (n + 5u); + } + for (unsigned i = depth; i; --i) cursor += add[i - 1]; + return cursor == visit(value, depth) ? 17 : 1; +} + +// Loop-carried values and conditional writes must retain their live ranges. +extern "C" __attribute__((noinline)) unsigned cycle(unsigned count) { + unsigned a = 3, b = 5, result = 0; + for (unsigned i = 0; i < count; ++i) { + if (i & 1) a += b ^ i; + else b += a * 3 + i; + if (i % 7 == 0) result ^= visit(a, 3); + unsigned previous = a; + a = b + result; + b = previous ^ (i * 11); + } + return a ^ b ^ result; +} diff --git a/pa37/tests/regression/600-local-storage-lifetimes.wasm-expect b/pa37/tests/regression/600-local-storage-lifetimes.wasm-expect new file mode 100644 index 000000000..e842d42e5 --- /dev/null +++ b/pa37/tests/regression/600-local-storage-lifetimes.wasm-expect @@ -0,0 +1,89 @@ +{ + "source": true, + "llvm_interop": true, + "exports": [ + "visit" + ], + "calls": [ + { + "export": "observe", + "args": [ + "0", + "0" + ], + "result": "17" + }, + { + "export": "observe", + "args": [ + "3", + "1" + ], + "result": "17" + }, + { + "export": "observe", + "args": [ + "11", + "32" + ], + "result": "17" + }, + { + "export": "observe", + "args": [ + "2147483647", + "100" + ], + "result": "17" + }, + { + "export": "observe", + "args": [ + "-1", + "128" + ], + "result": "17" + }, + { + "export": "cycle", + "args": [ + "0" + ], + "result": "6" + }, + { + "export": "cycle", + "args": [ + "1" + ], + "result": "17" + }, + { + "export": "cycle", + "args": [ + "7" + ], + "result": "70006" + }, + { + "export": "cycle", + "args": [ + "80" + ], + "result": "-95668216" + } + ], + "quality": { + "levels": [ + 1, + 2, + 3 + ], + "functions": { + "visit": { + "locals": 40 + } + } + } +} From 6493d029a707909685454a9031056d306978b0b2 Mon Sep 17 00:00:00 2001 From: Vishvananda Abrams Date: Mon, 16 Nov 2026 00:17:47 +0000 Subject: [PATCH 2/2] Raise the release to 0.9.3 --- dev/src/support/version.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev/src/support/version.h b/dev/src/support/version.h index d81ee0ba6..36530fdd0 100644 --- a/dev/src/support/version.h +++ b/dev/src/support/version.h @@ -4,4 +4,4 @@ // v. `cppgm --version` and cppgm_lowir_version() report it. // Set it in the change that prepares a release; // scripts/package_release.py refuses a release tag that differs. -#define CPPGM_VERSION "0.9.2" +#define CPPGM_VERSION "0.9.3"