Skip to main content

seqc/codegen/
state.rs

1//! CodeGen State and Core Types
2//!
3//! This module contains the CodeGen struct definition and core types
4//! used across the code generation modules.
5
6use crate::ast::UnionDef;
7use crate::ffi::FfiBindings;
8use crate::types::Type;
9use std::collections::HashMap;
10
11use super::specialization::SpecSignature;
12
13/// Sentinel value for unreachable predecessors in phi nodes.
14/// Used when a branch ends with a tail call (which emits ret directly).
15pub(super) const UNREACHABLE_PREDECESSOR: &str = "unreachable";
16
17/// Maximum number of values to keep in virtual registers (Issue #189).
18/// Values beyond this are spilled to memory.
19///
20/// Tuned for common patterns:
21/// - Binary ops need 2 values (`a b i.+`)
22/// - Dup patterns need 3 values (`a dup i.* b i.+`)
23/// - Complex expressions may use 4 (`a b i.+ c d i.* i.-`)
24///
25/// Larger values increase register pressure with diminishing returns,
26/// as most operations trigger spills (control flow, function calls, etc.).
27pub(super) const MAX_VIRTUAL_STACK: usize = 4;
28
29/// Tracks whether a statement is in tail position.
30///
31/// A statement is in tail position when its result is directly returned
32/// from the function without further processing. For tail calls, we can
33/// use LLVM's `musttail` to guarantee tail call optimization.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub(super) enum TailPosition {
36    /// This is the last operation before return - can use musttail
37    Tail,
38    /// More operations follow - use regular call
39    NonTail,
40}
41
42/// Result of generating code for an if-statement branch.
43pub(super) struct BranchResult {
44    /// The stack variable after executing the branch
45    pub stack_var: String,
46    /// Whether the branch emitted a tail call (and thus a ret)
47    pub emitted_tail_call: bool,
48    /// The predecessor block label for the phi node (or UNREACHABLE_PREDECESSOR)
49    pub predecessor: String,
50}
51
52/// Mangle a Seq word name into a valid LLVM IR identifier.
53///
54/// LLVM IR identifiers can contain: letters, digits, underscores, dollars, periods.
55/// Seq words can contain: letters, digits, hyphens, question marks, arrows, etc.
56///
57/// We escape special characters using underscore-based encoding:
58/// - `-` (hyphen) -> `_` (hyphens not valid in LLVM IR identifiers)
59/// - `?` -> `_Q_` (question)
60/// - `>` -> `_GT_` (greater than, for ->)
61/// - `<` -> `_LT_` (less than)
62/// - `!` -> `_BANG_`
63/// - `*` -> `_STAR_`
64/// - `/` -> `_SLASH_`
65/// - `+` -> `_PLUS_`
66/// - `=` -> `_EQ_`
67/// - `.` -> `_DOT_`
68pub(super) fn mangle_name(name: &str) -> String {
69    let mut result = String::new();
70    for c in name.chars() {
71        match c {
72            '?' => result.push_str("_Q_"),
73            '>' => result.push_str("_GT_"),
74            '<' => result.push_str("_LT_"),
75            '!' => result.push_str("_BANG_"),
76            '*' => result.push_str("_STAR_"),
77            '/' => result.push_str("_SLASH_"),
78            '+' => result.push_str("_PLUS_"),
79            '=' => result.push_str("_EQ_"),
80            // Hyphens converted to underscores (hyphens not valid in LLVM IR)
81            '-' => result.push('_'),
82            // Keep these as-is (valid in LLVM IR)
83            '_' | '.' | '$' => result.push(c),
84            // Alphanumeric kept as-is
85            c if c.is_alphanumeric() => result.push(c),
86            // Any other character gets hex-encoded
87            _ => result.push_str(&format!("_x{:02X}_", c as u32)),
88        }
89    }
90    result
91}
92
93/// Result of generating a quotation: wrapper and impl function names
94/// For closures, both names are the same (no TCO support yet)
95pub(super) struct QuotationFunctions {
96    /// C-convention wrapper function (for runtime calls)
97    pub wrapper: String,
98    /// tailcc implementation function (for TCO via musttail)
99    pub impl_: String,
100}
101
102/// A value held in an LLVM virtual register instead of memory (Issue #189).
103///
104/// This optimization keeps recently-pushed values in SSA variables,
105/// avoiding memory stores/loads for common patterns like `2 3 i.+`.
106/// Values are spilled to memory at control flow points and function calls.
107#[derive(Clone, Debug)]
108pub(super) enum VirtualValue {
109    /// Integer value in an SSA variable (i64)
110    Int {
111        ssa_var: String,
112        #[allow(dead_code)] // Used for constant folding in Phase 2
113        value: i64,
114    },
115    /// Float value in an SSA variable (double)
116    Float { ssa_var: String },
117    /// Boolean value in an SSA variable (i64: 0 or 1)
118    Bool { ssa_var: String },
119}
120
121pub struct CodeGen {
122    pub(super) output: String,
123    pub(super) string_globals: String,
124    pub(super) temp_counter: usize,
125    pub(super) string_counter: usize,
126    pub(super) block_counter: usize, // For generating unique block labels
127    pub(super) quot_counter: usize,  // For generating unique quotation function names
128    pub(super) string_constants: HashMap<String, String>, // string content -> global name
129    pub(super) quotation_functions: String, // Accumulates generated quotation functions
130    pub(super) type_map: HashMap<usize, Type>, // Maps quotation ID to inferred type (from typechecker)
131    pub(super) external_builtins: HashMap<String, String>, // seq_name -> symbol (for external builtins)
132    pub(super) inside_closure: bool, // Track if we're generating code inside a closure (disables TCO)
133    pub(super) inside_main: bool, // Track if we're generating code for main (uses C convention, no musttail)
134    pub(super) inside_quotation: bool, // Track if we're generating code for a quotation (uses C convention, no musttail)
135    pub(super) unions: Vec<UnionDef>,  // Union type definitions for pattern matching
136    pub(super) ffi_bindings: FfiBindings, // FFI function bindings
137    pub(super) ffi_wrapper_code: String, // Generated FFI wrapper functions
138    /// Pure inline test mode: bypasses scheduler, returns top of stack as exit code.
139    /// Used for testing pure integer programs without FFI dependencies.
140    pub(super) pure_inline_test: bool,
141    // Symbol interning for O(1) equality (Issue #166)
142    pub(super) symbol_globals: String, // LLVM IR for static symbol globals
143    pub(super) symbol_counter: usize,  // Counter for unique symbol names
144    pub(super) symbol_constants: HashMap<String, String>, // symbol name -> global name (deduplication)
145    /// Per-statement type info for optimization (Issue #186)
146    /// Maps (word_name, statement_index) -> top-of-stack type before statement
147    pub(super) statement_types: HashMap<(String, usize), Type>,
148    /// Resolved arithmetic sugar: maps (line, column) -> concrete op name
149    /// E.g., `+` at line 5, column 3 -> `"i.+"` if typechecker resolved it for Int operands
150    pub(super) resolved_sugar: HashMap<(usize, usize), String>,
151    /// Current word being compiled (for statement type lookup)
152    pub(super) current_word_name: Option<String>,
153    /// Current statement index within the word (for statement type lookup)
154    pub(super) current_stmt_index: usize,
155    /// Nesting depth for type lookup - only depth 0 can use type info
156    /// Nested contexts (if/else, loops) increment this to disable lookups
157    pub(super) codegen_depth: usize,
158    /// True if the previous statement was a trivially-copyable literal (Issue #195)
159    /// Used to optimize `dup` after literal push (e.g., `42 dup`)
160    pub(super) prev_stmt_is_trivial_literal: bool,
161    /// If previous statement was IntLiteral, stores its value (Issue #192)
162    /// Used to optimize `roll`/`pick` with constant N (e.g., `2 roll` -> rot)
163    pub(super) prev_stmt_int_value: Option<i64>,
164    /// Virtual register stack for top N values (Issue #189)
165    /// Values here are in SSA variables, not yet written to memory.
166    /// The memory stack pointer tracks where memory ends; virtual values are "above" it.
167    pub(super) virtual_stack: Vec<VirtualValue>,
168    /// Specialized word signatures for register-based codegen
169    /// Maps word name -> specialized signature
170    pub(super) specialized_words: HashMap<String, SpecSignature>,
171    /// Per-word aux stack slot counts from typechecker (Issue #350)
172    /// Maps word_name -> number of %Value allocas needed
173    pub(super) aux_slot_counts: HashMap<String, usize>,
174    /// LLVM alloca names for current word's aux slots (Issue #350)
175    pub(super) current_aux_slots: Vec<String>,
176    /// Compile-time index into aux slots (Issue #350)
177    pub(super) current_aux_sp: usize,
178    /// Whether to emit per-word atomic call counters (--instrument)
179    pub(super) instrument: bool,
180    /// Maps word name -> sequential ID for instrumentation counters
181    pub(super) word_instrument_ids: HashMap<String, usize>,
182}
183
184impl Default for CodeGen {
185    fn default() -> Self {
186        Self::new()
187    }
188}
189
190impl CodeGen {
191    pub fn new() -> Self {
192        CodeGen {
193            output: String::new(),
194            string_globals: String::new(),
195            temp_counter: 0,
196            string_counter: 0,
197            block_counter: 0,
198            inside_closure: false,
199            inside_main: false,
200            inside_quotation: false,
201            quot_counter: 0,
202            string_constants: HashMap::new(),
203            quotation_functions: String::new(),
204            type_map: HashMap::new(),
205            external_builtins: HashMap::new(),
206            unions: Vec::new(),
207            ffi_bindings: FfiBindings::new(),
208            ffi_wrapper_code: String::new(),
209            pure_inline_test: false,
210            symbol_globals: String::new(),
211            symbol_counter: 0,
212            symbol_constants: HashMap::new(),
213            statement_types: HashMap::new(),
214            resolved_sugar: HashMap::new(),
215            current_word_name: None,
216            current_stmt_index: 0,
217            codegen_depth: 0,
218            prev_stmt_is_trivial_literal: false,
219            prev_stmt_int_value: None,
220            virtual_stack: Vec::new(),
221            specialized_words: HashMap::new(),
222            aux_slot_counts: HashMap::new(),
223            current_aux_slots: Vec::new(),
224            current_aux_sp: 0,
225            instrument: false,
226            word_instrument_ids: HashMap::new(),
227        }
228    }
229
230    /// Create a CodeGen for pure inline testing.
231    /// Bypasses the scheduler, returning top of stack as exit code.
232    /// Only supports operations that are fully inlined (integers, arithmetic, stack ops).
233    pub fn new_pure_inline_test() -> Self {
234        let mut cg = Self::new();
235        cg.pure_inline_test = true;
236        cg
237    }
238
239    /// Set per-word aux stack slot counts from typechecker (Issue #350)
240    pub fn set_aux_slot_counts(&mut self, counts: HashMap<String, usize>) {
241        self.aux_slot_counts = counts;
242    }
243
244    /// Set resolved arithmetic sugar mappings from the typechecker
245    pub fn set_resolved_sugar(&mut self, sugar: HashMap<(usize, usize), String>) {
246        self.resolved_sugar = sugar;
247    }
248
249    /// Look up the resolved name for an arithmetic sugar op by source location
250    pub(super) fn resolve_sugar_at(&self, line: usize, column: usize) -> Option<&str> {
251        self.resolved_sugar.get(&(line, column)).map(|s| s.as_str())
252    }
253}