Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion dev/frontend_source_sets.mk
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions dev/src/wasm/local_cleanup.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "wasm/mir.h"
#include "wasm/local_lifetimes.h"

namespace wasm {

Expand Down Expand Up @@ -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
256 changes: 256 additions & 0 deletions dev/src/wasm/local_lifetimes.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,256 @@
#include "wasm/local_lifetimes.h"

#include <algorithm>
#include <queue>
#include <utility>

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<uint32_t> 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<Edge>& edges)
{
const uint32_t size = static_cast<uint32_t>(function.instructions.size());
std::vector<uint32_t> open(1, size), end(size + 1, size), other(size, none);
std::vector<Edge> 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<Edge> edges;
if (!control_edges(function, edges))
return false;
const uint32_t size = static_cast<uint32_t>(function.instructions.size());
std::vector<uint8_t> 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<uint32_t>(graph.first.size() - 1);
}
const uint32_t count = static_cast<uint32_t>(graph.first.size());
graph.first.push_back(size);
graph.block[size] = count;
graph.predecessor_first.assign(count + 1, 0);
std::vector<Edge> 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<uint32_t> 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<uint32_t> 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<uint32_t> 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<Life>& lives)
{
const Accesses accesses(function);
const uint32_t blocks = static_cast<uint32_t>(graph.first.size() - 1);
std::vector<uint32_t> 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<Life>& 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<uint32_t, uint32_t>;
std::priority_queue<End, std::vector<End>, std::greater<End>> active;
std::vector<uint32_t> mapping(function.locals.size());
std::vector<std::vector<uint32_t>> free(8);
std::vector<ValueType> 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<unsigned>(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<uint32_t>(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<Life> lives;
if (graph_for(function, graph) && lifetimes(function, graph, lives))
place(function, lives);
}

} // namespace wasm
11 changes: 11 additions & 0 deletions dev/src/wasm/local_lifetimes.h
Original file line number Diff line number Diff line change
@@ -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
41 changes: 41 additions & 0 deletions pa37/tests/regression/600-local-storage-lifetimes.t
Original file line number Diff line number Diff line change
@@ -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;
}
Loading
Loading