') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); Compile-time stack flattening (promote stack slots to SSA/registers) · Issue #61 · tetsuo-cpp/warpforth · GitHub
Skip to content

Compile-time stack flattening (promote stack slots to SSA/registers) #61

Description

@tetsuo-cpp

Summary

Promote the abstract Forth data stack from a runtime memref<256xi64> buffer into SSA values (and ultimately GPU registers) wherever stack depth and slot identities are statically known.

Motivation

Today, convert-forth-to-memref materializes !forth.stack as a fixed memref<256xi64> plus an index stack pointer. Almost every stack word becomes load/store + SP arithmetic. That is a large tax on every kernel, including ones that would otherwise be competitive after warp ops (#10), atomics (#43), MMA (#11), or unrolling (#12).

Local variables already show the preferred model: they are bound with forth.pop / forth.push_value and map cleanly to SSA/registers. The default data stack should aspire to the same lowering when depth is static.

Without stack flattening, new GPU primitives will still sit on a memory-backed stack machine and leave large performance on the table.

Current behavior

  • !forth.stackmemref<256xi64> + SP (kStackSize = 256 in ForthToMemRef.cpp)
  • DUP/SWAP/+/etc. lower to explicit loads, stores, and pointer updates
  • Residual stack traffic survives into NVVM/PTX as local memory pressure

Proposed design

Add a stack simulation / flattening pass (either before or instead of naive full-buffer materialization):

  1. Simulate stack depth and slot provenance through straight-line code and simple control flow.
  2. Rewrite stack ops into SSA values for known slots (same spirit as locals).
  3. Keep a residual runtime stack only when depth or identity is not statically known (e.g. data-dependent depth, complex irreducible control flow).
  4. Verify that residual and promoted paths agree on stack effect at merge points (phi/block args).

Placement options

OptionNotes
A. Before MemRefHigh-level forth IR → SSA-heavy forth (or arith/cf) with residual stack ops
B. During MemRefEmit SSA + optional alloca residual instead of always allocating 256 cells
C. After MemRefMem2reg-like promotion of the stack buffer (harder; aliasing/SP updates)

Prefer A or B so control-flow and word boundaries see a cleaner model early.

Acceptance criteria

  • Straight-line kernels with fixed stack depth compile with little or no stack alloca traffic in the post-MemRef IR
  • Control flow (IF/ELSE/THEN, loops) either fully promotes or clearly falls back to residual stack with correct merges
  • User words still compose correctly (stack in/out as SSA tuple or residual)
  • LIT tests for promotion success cases and residual fallback cases
  • At least one GPU microbenchmark (e.g. matmul inner loop) shows reduced local memory / better SASS than the current lowering (document methodology)

Non-goals

  • Full Forth exception/catch stack
  • Dynamic stack depth as a first-class language feature
  • Replacing the programmer-facing stack model (source language stays stack-based)

Related

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions