lib/std/lang/lower.rad 271.6 KiB raw
1
//! AST to IL lowering pass.
2
//!
3
//! This module converts the typed AST produced by the resolver into a linear
4
//! SSA-based intermediate language (IL). The IL is suitable for further
5
//! optimization and code generation.
6
//!
7
//! # Design Overview
8
//!
9
//! The lowering process works in two main phases:
10
//!
11
//! 1. Module-level pass: Iterates over top-level declarations, lowering
12
//!    each function independently while accumulating global data items (strings,
13
//!    constants, static arrays) into a shared data section.
14
//!
15
//! 2. Function-level pass: For each function, constructs an SSA-form control
16
//!    flow graph (CFG) with basic blocks connected by jumps and branches. Uses
17
//!    a simplified SSA construction algorithm where variables are tracked per-block
18
//!    and block parameters are inserted lazily when a variable is used before
19
//!    being defined in a block.
20
//!
21
//! # Memory Model
22
//!
23
//! All allocations use an arena allocator passed through the `Lowerer` context.
24
//! The IL is entirely stack-based at runtime -- there's no heap allocation during
25
//! program execution. Aggregate values (records, slices, optionals) are passed
26
//! by pointer on the stack.
27
//!
28
//! # SSA Construction
29
//!
30
//! SSA form is built incrementally as the AST is walked. When a variable is
31
//! defined (via `defVar`), its current value is recorded in the current block.
32
//! When a variable is used (via `useVar`), the algorithm either:
33
//! - Returns the value if defined in this block
34
//! - Recurses to predecessors if the block is sealed (all predecessors known)
35
//! - Inserts a block parameter if the variable value must come from multiple paths
36
//!
37
//! Block "sealing" indicates that all predecessor edges are known, enabling
38
//! the SSA construction to resolve cross-block variable references.
39
//!
40
//! # SSA Variable API
41
//!
42
//! 1. `newVar` creates a logical variable that can be defined differently in each block.
43
//! 2. `defVar` defines the variable's value in the current block.
44
//! 3. `useVar` reads the variable; if called in a block with multiple
45
//!             predecessors that defined it differently, the SSA algorithm
46
//!             automatically creates a block parameter.
47
//!
48
//! # Expression Lowering
49
//!
50
//! Expressions produce IL values which can be:
51
//!
52
//! - Imm(i64): immediate/constant values
53
//! - Reg(u32): SSA register references
54
//! - Sym(name): symbol references (for function pointers, data addresses)
55
//! - Undef: for unused values
56
//!
57
//! For aggregate types (records, arrays, slices, optionals), the "value" is
58
//! actually a pointer to stack-allocated memory containing the aggregate.
59
//!
60
//! # Block ordering invariant
61
//!
62
//! The register allocator processes blocks in forward index order and uses a
63
//! single global assignment array. This means a value's definition block must
64
//! have a lower index than any block that uses the value (except through
65
//! back-edges, where block parameters handle the merge). The lowerer maintains
66
//! this by creating blocks in control-flow order. For `for` loops, the step
67
//! block is created lazily (after the loop body) so that its index is higher
68
//! than all body blocks -- see [`lowerForLoop`] and [`getOrCreateContinueBlock`].
69
//!
70
//! A more robust alternative would be per-block register maps with edge-copy
71
//! resolution (as in QBE's `rega.c`), which is block-order-independent. That
72
//! would eliminate this invariant at the cost of a more complex allocator.
73
//!
74
//! # Notes on constant data lowering
75
//!
76
//! The lowerer flattens constant AST expressions directly into IL data values.
77
//! Primitive constants use [`resolver::ConstValue`] as an intermediate form.
78
//! Record padding is explicit: `undef * N;` for N padding bytes.
79
//!
80
//!   AST Node (ArrayLit, RecordLit, literals, etc.)
81
//!       ↓ [`lowerConstData`]
82
//!   resolver::ConstValue (Bool, Char, String, Int)
83
//!       ↓ [`constValueToDataItem`]
84
//!   il::DataItem (Val, Sym, Str, Undef)
85
//!       ↓
86
//!   il::DataValue
87
//!       ↓
88
//!   il::Data
89
//!
90
use std::fmt;
91
use std::io;
92
use std::lang::alloc;
93
use std::lang::types;
94
use std::mem;
95
use std::lang::ast;
96
use std::lang::il;
97
use std::lang::module;
98
use std::lang::resolver;
99
100
// TODO: Search for all `_ as i32` to ensure that casts from u32 to i32 don't
101
// happen, since they are potentially truncating values.
102
103
// TODO: Support constant union lowering.
104
// TODO: Void unions should be passed by value.
105
106
////////////////////
107
// Error Handling //
108
////////////////////
109
110
/// Lowering errors are typically unrecoverable since they indicate bugs in
111
/// the resolver or malformed AST that should have been caught earlier.
112
export union LowerError {
113
    /// A node's symbol was not set before lowering.
114
    MissingSymbol(*ast::Node),
115
    /// A node's type was not set before lowering.
116
    MissingType(*ast::Node),
117
    /// A node's constant value was not set before lowering.
118
    MissingConst(*ast::Node),
119
    /// An optional type was expected.
120
    ExpectedOptional,
121
    /// A record type was expected.
122
    ExpectedRecord,
123
    /// An array was expected.
124
    ExpectedArray,
125
    /// A block was expected.
126
    ExpectedBlock(*ast::Node),
127
    /// An identifier was expected.
128
    ExpectedIdentifier,
129
    /// A function parameter was expected.
130
    ExpectedFunctionParam,
131
    /// A function type was expected.
132
    ExpectedFunction,
133
    /// Trying to lower loop construct outside of loop.
134
    OutsideOfLoop,
135
    /// Invalid variable use.
136
    InvalidUse,
137
    /// Unexpected node value.
138
    UnexpectedNodeValue(*ast::Node),
139
    /// Unexpected type.
140
    UnexpectedType(*resolver::Type),
141
142
    /// Missing control flow target.
143
    MissingTarget,
144
    /// Missing metadata that should have been set by resolver.
145
    MissingMetadata,
146
    /// Expected a slice or array type for operation.
147
    ExpectedSliceOrArray,
148
    /// Expected a variant symbol.
149
    ExpectedVariant,
150
    /// Expected a call expression.
151
    ExpectedCall,
152
    /// Field not found in record or invalid field access.
153
    FieldNotFound,
154
    /// Assignment to an immutable variable.
155
    ImmutableAssignment,
156
    /// Nil used in non-optional context.
157
    NilInNonOptional,
158
    /// Invalid argument count for builtin.
159
    InvalidArgCount,
160
    /// Feature or pattern not supported by the lowerer.
161
    Unsupported,
162
    /// Unknown intrinsic function.
163
    UnknownIntrinsic,
164
    /// Allocation failure.
165
    AllocationFailed,
166
}
167
168
/// Print a LowerError for debugging.
169
export fn printError(err: LowerError) {
170
    match err {
171
        case LowerError::MissingSymbol(_) => io::print("MissingSymbol"),
172
        case LowerError::MissingType(_) => io::print("MissingType"),
173
        case LowerError::MissingConst(_) => io::print("MissingConst"),
174
        case LowerError::ExpectedOptional => io::print("ExpectedOptional"),
175
        case LowerError::ExpectedRecord => io::print("ExpectedRecord"),
176
        case LowerError::ExpectedArray => io::print("ExpectedArray"),
177
        case LowerError::ExpectedBlock(_) => io::print("ExpectedBlock"),
178
        case LowerError::ExpectedIdentifier => io::print("ExpectedIdentifier"),
179
        case LowerError::ExpectedFunctionParam => io::print("ExpectedFunctionParam"),
180
        case LowerError::ExpectedFunction => io::print("ExpectedFunction"),
181
        case LowerError::OutsideOfLoop => io::print("OutsideOfLoop"),
182
        case LowerError::InvalidUse => io::print("InvalidUse"),
183
        case LowerError::UnexpectedNodeValue(_) => io::print("UnexpectedNodeValue"),
184
        case LowerError::UnexpectedType(_) => io::print("UnexpectedType"),
185
        case LowerError::MissingTarget => io::print("MissingTarget"),
186
        case LowerError::MissingMetadata => io::print("MissingMetadata"),
187
        case LowerError::ExpectedSliceOrArray => io::print("ExpectedSliceOrArray"),
188
        case LowerError::ExpectedVariant => io::print("ExpectedVariant"),
189
        case LowerError::ExpectedCall => io::print("ExpectedCall"),
190
        case LowerError::FieldNotFound => io::print("FieldNotFound"),
191
        case LowerError::ImmutableAssignment => io::print("ImmutableAssignment"),
192
        case LowerError::NilInNonOptional => io::print("NilInNonOptional"),
193
        case LowerError::InvalidArgCount => io::print("InvalidArgCount"),
194
        case LowerError::Unsupported => io::print("Unsupported"),
195
        case LowerError::UnknownIntrinsic => io::print("UnknownIntrinsic"),
196
        case LowerError::AllocationFailed => io::print("AllocationFailed"),
197
    }
198
}
199
200
///////////////
201
// Constants //
202
///////////////
203
204
/// Maximum nesting depth of loops.
205
constant MAX_LOOP_DEPTH: u32 = 16;
206
/// Maximum number of `catch` clauses per `try`.
207
constant MAX_CATCH_CLAUSES: u32 = 32;
208
209
// Slice Layout
210
//
211
// A slice is a fat pointer consisting of a data pointer, a length and a capacity.
212
// `{ ptr: u32, len: u32, cap: u32 }`.
213
214
/// Slice data pointer offset.
215
constant SLICE_PTR_OFFSET: i32 = 0;
216
/// Offset of slice length in slice data structure.
217
constant SLICE_LEN_OFFSET: i32 = resolver::PTR_SIZE as i32;
218
/// Offset of slice capacity in slice data structure.
219
constant SLICE_CAP_OFFSET: i32 = resolver::PTR_SIZE as i32 + 4;
220
221
// Trait Object Layout
222
//
223
// A trait object is a fat pointer consisting of a data pointer and a
224
// v-table pointer. `{ data: *T, vtable: *VTable }`.
225
226
/// Trait object data pointer offset.
227
constant TRAIT_OBJ_DATA_OFFSET: i32 = 0;
228
/// Trait object v-table pointer offset.
229
constant TRAIT_OBJ_VTABLE_OFFSET: i32 = resolver::PTR_SIZE as i32;
230
231
// Tagged Value Layout (optionals, tagged unions)
232
//
233
// Optionals and unions use 1-byte tags. Results use 8-byte tags.
234
//
235
// `{ tag: u8, [padding], payload: T }`
236
//
237
// Optionals use `tag: 0` for `nil` and `tag: 1` otherwise.
238
// When `T` is a pointer, the entire optional is stored as a single pointer.
239
//
240
// Tagged unions have a payload the size of the maximum variant size.
241
242
/// Offset of tag in tagged value data structure.
243
constant TVAL_TAG_OFFSET: i32 = 0;
244
/// Offset of value in result data structure (8-byte tag).
245
constant RESULT_VAL_OFFSET: i32 = resolver::PTR_SIZE as i32;
246
247
//////////////////////////
248
// Core Data Structures //
249
//////////////////////////
250
251
/// Options controlling the lowering pass.
252
export record LowerOptions {
253
    /// Whether to emit source location info.
254
    debug: bool,
255
    /// Whether to lower `@test` functions.
256
    buildTest: bool,
257
}
258
259
/// Role of a lowered function in the final program.
260
export union FnRole {
261
    /// Regular function.
262
    Normal,
263
    /// Program entry function marked with `@default`.
264
    Default,
265
}
266
267
/// Function sink used by lowerers that consume functions as they are produced.
268
export record FnSink {
269
    /// Raw storage address reborrowed only for the duration of each callback.
270
    ctx: *unsafe mut u8,
271
    /// Callback invoked for each lowered function.
272
    emitFn: fn(&mut opaque, *il::Fn, FnRole),
273
}
274
275
/// Destination for functions produced by the lowerer.
276
export union FnOutput {
277
    /// Store lowered functions in the provided slice.
278
    Accumulate(*mut [*il::Fn]),
279
    /// Send lowered functions to an external consumer immediately.
280
    Stream(FnSink),
281
}
282
283
/// Module-level lowering context. Shared across all function lowerings.
284
/// Holds global state like the data section (strings, constants) and provides
285
/// access to the resolver for type queries.
286
export record Lowerer {
287
    /// Arena for persistent lowering state, including data and symbol names.
288
    arena: *mut alloc::Arena,
289
    /// Arena for allocations owned by the function currently being lowered.
290
    fnArena: *mut alloc::Arena,
291
    /// Allocator backed by the arena.
292
    allocator: alloc::Allocator,
293
    /// Resolver for type information. Used to query types, symbols, and
294
    /// compile-time constant values during lowering.
295
    resolver: *resolver::Resolver,
296
    /// Module graph for cross-module symbol resolution.
297
    moduleGraph: ?*module::ModuleGraph,
298
    /// Package name for qualified symbol names.
299
    pkgName: *[u8],
300
    /// Current module being lowered.
301
    currentMod: ?u16,
302
    /// Global data items (string literals, constants, static arrays).
303
    /// These become the data sections in the final binary.
304
    data: *mut [il::Data],
305
    /// Destination for lowered functions.
306
    output: FnOutput,
307
    /// Map of function symbols to qualified names.
308
    fnSyms: *mut [FnSymEntry],
309
    /// Global error type tag table. Maps nominal types to unique tags.
310
    errTags: *mut [ErrTagEntry],
311
    /// Next error tag to assign (starts at 1; 0 = success).
312
    errTagCounter: u32,
313
    /// Lowering options.
314
    options: LowerOptions,
315
}
316
317
/// Entry mapping a function symbol to its qualified name.
318
record FnSymEntry {
319
    sym: *resolver::Symbol,
320
    qualName: *[u8],
321
}
322
323
/// Entry in the global error tag table.
324
record ErrTagEntry {
325
    /// The type of this error, identified by its interned pointer.
326
    ty: resolver::Type,
327
    /// The globally unique tag assigned to this error type (non-zero).
328
    tag: u32,
329
}
330
331
/// Compute the maximum size of any error type in a throw list.
332
fn maxErrSize(throwList: *[*resolver::Type]) -> u32 {
333
    let mut maxSize: u32 = 0;
334
    for ty in throwList {
335
        let size = resolver::getTypeLayout(*ty).size;
336
        if size > maxSize {
337
            set maxSize = size;
338
        }
339
    }
340
    return maxSize;
341
}
342
343
/// Get or assign a globally unique error tag for the given error type.
344
/// Tag `0` is reserved for success; error tags start at `1`.
345
fn getOrAssignErrorTag(self: *mut Lowerer, errType: resolver::Type) -> u32 {
346
    for entry in self.errTags {
347
        if entry.ty == errType {
348
            return entry.tag;
349
        }
350
    }
351
    let tag = self.errTagCounter;
352
353
    set self.errTagCounter += 1;
354
    self.errTags.append(ErrTagEntry { ty: errType, tag }, self.allocator);
355
356
    return tag;
357
}
358
359
/// Emit one function to the active output.
360
fn emitFunction(self: *mut Lowerer, func: *il::Fn, role: FnRole) {
361
    match self.output {
362
        case FnOutput::Accumulate(accumulated) => {
363
            let mut fns = accumulated;
364
            fns.append(func, self.allocator);
365
            set self.output = FnOutput::Accumulate(fns);
366
        }
367
        case FnOutput::Stream(sink) => {
368
            sink.emitFn(&mut *sink.ctx as &mut opaque, func, role);
369
        }
370
    }
371
}
372
373
/// Get the function role for a top-level function declaration.
374
fn lowerFnRole(isRoot: bool, attrs: ?ast::Attributes) -> FnRole {
375
    if isRoot and checkAttr(attrs, ast::Attribute::Default) {
376
        return FnRole::Default;
377
    }
378
    return FnRole::Normal;
379
}
380
381
/// Builder for accumulating data values during constant lowering.
382
record DataValueBuilder {
383
    allocator: alloc::Allocator,
384
    values: *mut [il::DataValue],
385
    /// Whether all pushed values can be represented by zero-filled memory.
386
    zeroInit: bool,
387
}
388
389
/// Result of lowering constant data.
390
record ConstDataResult {
391
    values: *[il::DataValue],
392
    zeroInit: bool,
393
}
394
395
/// Create a new builder.
396
fn dataBuilder(allocator: alloc::Allocator) -> DataValueBuilder {
397
    return DataValueBuilder { allocator, values: &mut [], zeroInit: true };
398
}
399
400
/// Return whether a data item can be omitted from a zero-filled image.
401
fn dataIsZero(item: il::DataItem) -> bool {
402
    match item {
403
        case il::DataItem::Undef => return true,
404
        case il::DataItem::Val { val, .. } => return val == 0,
405
        else => return false,
406
    }
407
}
408
409
/// Return whether all data values can be omitted from a zero-filled image.
410
fn dataValuesAreZeroInit(values: *[il::DataValue]) -> bool {
411
    for value in values {
412
        if value.count > 0 and not dataIsZero(value.item) {
413
            return false;
414
        }
415
    }
416
    return true;
417
}
418
419
/// Append a data value to the builder.
420
fn dataBuilderPush(b: *mut DataValueBuilder, value: il::DataValue) {
421
    b.values.append(value, b.allocator);
422
423
    if value.count > 0 and not dataIsZero(value.item) {
424
        set b.zeroInit = false;
425
    }
426
}
427
428
/// Return the accumulated values.
429
fn dataBuilderFinish(b: *DataValueBuilder) -> ConstDataResult {
430
    return ConstDataResult {
431
        values: &b.values[..],
432
        zeroInit: b.zeroInit,
433
    };
434
}
435
436
///////////////////////////
437
// SSA Variable Tracking //
438
///////////////////////////
439
440
// The SSA construction algorithm tracks variable definitions per-block.
441
// Each source-level variable gets a [`Var`] handle, and each block maintains
442
// a mapping from [`Var`] to current SSA value. When control flow merges,
443
// block parameters are inserted to merge values from different control flow paths.
444
445
/// A variable handle. Represents a source-level variable during lowering.
446
/// The same [`Var`] can have different SSA values in different blocks.
447
export record Var(u32);
448
449
/// Metadata for a source-level variable, stored once per function.
450
///
451
/// Each variable declaration in the source creates one [`VarData`] entry in the
452
/// function's `variables` array, indexed by `id`. This contains static
453
/// properties that don't change across basic blocks.
454
///
455
/// Per-block SSA values are tracked separately in [`BlockData::vars`] as [`?il::Val`],
456
/// where `nil` means "not yet assigned in this block". Together they implement
457
/// SSA construction.
458
///
459
record VarData {
460
    /// Variable name, used by [`lookupVarByName`] to resolve identifiers.
461
    /// Nil for anonymous variables (e.g., internal loop counters).
462
    name: ?*[u8],
463
    /// IL type of this variable. Set at declaration time and used when
464
    /// generating loads, stores, and type-checking assignments.
465
    type: il::Type,
466
    /// Whether this variable was declared with `mut`. Controls whether [`defVar`]
467
    /// is allowed after the initial definition.
468
    mutable: bool,
469
    /// Whether this variable's address has been taken (e.g. via `&mut x`).
470
    /// When true, the SSA value is a pointer to a stack slot and reads/writes
471
    /// must go through memory instead of using the cached SSA value directly.
472
    addressTaken: bool,
473
}
474
475
/// Links a function parameter to its corresponding variable for the entry block.
476
/// After creating the entry block, we iterate through these to define initial values.
477
record FnParamBinding {
478
    /// The variable that receives this parameter's value.
479
    var: Var,
480
    /// SSA register containing the parameter value from the caller.
481
    reg: il::Reg,
482
}
483
484
////////////////////////////////
485
// Basic Block Representation //
486
////////////////////////////////
487
488
// During lowering, we build a CFG of basic blocks. Each block accumulates
489
// instructions until terminated by a jump, branch, return, or unreachable.
490
// Blocks can be created before they're filled (forward references for jumps).
491
492
/// A handle to a basic block within the current function.
493
/// Block handles are stable, they don't change as more blocks are added.
494
export record BlockId(u32);
495
496
/// Internal block state during construction.
497
///
498
/// The key invariants:
499
///
500
/// - A block is "open" if it has no terminator; instructions can be added.
501
/// - A block is "sealed" when all predecessor edges are known.
502
/// - Sealing is required before SSA construction can insert block parameters.
503
///
504
/// This differs from the final [`il::Block`] which is immutable and fully formed.
505
record BlockData {
506
    /// Block label for debugging and IL printing.
507
    label: *[u8],
508
    /// Block parameters for merging values at control flow joins. These
509
    /// receive values from predecessor edges when control flow merges.
510
    params: *mut [il::Param],
511
    /// Variable ids corresponding to each parameter. Used to map block params
512
    /// back to source variables when building argument lists for jumps.
513
    paramVars: *mut [u32],
514
    /// Instructions accumulated so far. The last instruction should eventually
515
    /// be a terminator.
516
    instrs: *mut [il::Instr],
517
    /// Debug source locations, one per instruction. Only populated when
518
    /// debug info is enabled.
519
    locs: *mut [il::SrcLoc],
520
    /// Predecessor block ids. Used for SSA construction to propagate values
521
    /// from predecessors when a variable is used before being defined locally.
522
    preds: *mut [u32],
523
    /// The current SSA value of each variable in this block. Indexed by variable
524
    /// id. A `nil` means the variable wasn't assigned in this block. Updated by
525
    /// [`defVar`], queried by [`useVarInBlock`].
526
    vars: *mut [?il::Val],
527
    /// Sealing state. Once sealed, all predecessors are known and we can resolve
528
    /// variable uses that need to pull values from predecessors.
529
    sealState: Sealed,
530
    /// Loop nesting depth when this block was created.
531
    loopDepth: u32,
532
}
533
534
/// Block sealing state for SSA construction.
535
///
536
/// A block is "unsealed" while its predecessors are still being discovered.
537
/// During this time, variables used before being defined locally are tracked.
538
/// Once all predecessors are known, the block is sealed and those variables
539
/// are resolved via [`resolveBlockArgs`].
540
union Sealed {
541
    /// Block is unsealed; predecessors may still be added.
542
    No { incompleteVars: *mut [u32] },
543
    /// Block is sealed; all predecessors are known.
544
    Yes,
545
}
546
547
///////////////////////////////////
548
// Loop and Control Flow Context //
549
///////////////////////////////////
550
551
/// Context for break/continue statements within a loop.
552
/// Each nested loop pushes a new context onto the loop stack.
553
export record LoopCtx {
554
    /// Where `break` should transfer control (the loop's exit block).
555
    breakTarget: BlockId,
556
    /// Where `continue` should transfer control.
557
    continueTarget: ?BlockId,
558
}
559
560
/// Logical operator.
561
union LogicalOp { And, Or }
562
563
/// Iterator state for for-loop lowering.
564
union ForIter {
565
    /// Range iterator: `for i in 0..n`.
566
    Range {
567
        valVar: Var,
568
        indexVar: ?Var,
569
        endVal: il::Val,
570
        valType: il::Type,
571
        unsigned: bool,
572
    },
573
    /// Collection iterator: `for elem in slice`.
574
    Collection {
575
        valVar: ?Var,
576
        idxVar: Var,
577
        dataReg: il::Reg,
578
        lengthVal: il::Val,
579
        elemType: *resolver::Type,
580
    },
581
}
582
583
//////////////////////////////
584
// Pattern Matching Support //
585
//////////////////////////////
586
587
// Match expressions are lowered by evaluating the subject once, then emitting
588
// a chain of comparison-and-branch sequences for each arm. The algorithm
589
// handles several subject types specially:
590
//
591
// - Optional pointers: compared against `null`.
592
// - Optional aggregates: tag checked then payload extracted.
593
// - Unions: tag compared against variant indices.
594
595
/// Cached information about a match subject. Computed once and reused across
596
/// all arms to avoid redundant lowering and type queries.
597
record MatchSubject {
598
    /// The lowered subject value.
599
    val: il::Val,
600
    /// Source-level type from the resolver.
601
    type: resolver::Type,
602
    /// IL-level type for code generation.
603
    ilType: il::Type,
604
    /// The type that binding arms should use. For optionals, this is the
605
    /// inner type; for regular values, it's the same as `type`.
606
    bindType: resolver::Type,
607
    /// Classification of how the subject should be compared and destructured.
608
    kind: MatchSubjectKind,
609
    /// How bindings are created: by value, or by reference.
610
    by: resolver::MatchBy,
611
}
612
613
/// Classifies a match subject by how it should be compared and destructured.
614
union MatchSubjectKind {
615
    /// Regular value: direct equality comparison.
616
    Regular,
617
    /// Optional with null pointer optimization: `?*T`, `?*[T]`.
618
    OptionalPtr,
619
    /// Optional aggregate `?T`: tagged union with payload.
620
    OptionalAggregate,
621
    /// Union type: tag compared against variant indices.
622
    Union(resolver::UnionType),
623
}
624
625
/// Determine the kind of a match subject from its type.
626
fn matchSubjectKind(type: resolver::Type) -> MatchSubjectKind {
627
    if resolver::isOptionalPointer(type) {
628
        return MatchSubjectKind::OptionalPtr;
629
    }
630
    if resolver::isOptionalAggregate(type) {
631
        return MatchSubjectKind::OptionalAggregate;
632
    }
633
    if let info = unionInfoFromType(type) {
634
        return MatchSubjectKind::Union(info);
635
    }
636
    return MatchSubjectKind::Regular;
637
}
638
639
//////////////////////////
640
// Field Access Support //
641
//////////////////////////
642
643
/// Result of resolving a place expression to a memory location.
644
record FieldRef {
645
    /// Base pointer register (points to the container).
646
    base: il::Reg,
647
    /// Byte offset of the value within the container.
648
    offset: i32,
649
    /// Type of the value held at that location.
650
    fieldType: resolver::Type,
651
}
652
653
/// Result of computing an element pointer for array/slice subscript operations.
654
/// Used by [`lowerElemPtr`] to return both the element address register and
655
/// the element type for subsequent load or address-of operations.
656
record ElemPtrResult {
657
    /// Register holding the computed element address.
658
    elemReg: il::Reg,
659
    /// Source-level type of the element.
660
    elemType: resolver::Type,
661
}
662
663
/// Result of resolving a slice range to a data pointer and element count.
664
record SliceRangeResult {
665
    dataReg: il::Reg,
666
    count: il::Val,
667
}
668
669
/////////////////////////////
670
// Function Lowering State //
671
/////////////////////////////
672
673
/// Per-function lowering state. Created fresh for each function and contains
674
/// all the mutable state needed during function body lowering.
675
record FnLowerer {
676
    /// Reference to the module-level lowerer.
677
    low: *mut Lowerer,
678
    /// Allocator for IL allocations.
679
    allocator: alloc::Allocator,
680
    /// Type signature of the function being lowered.
681
    fnType: *resolver::FnType,
682
    /// Function name, used as prefix for generated data symbols.
683
    fnName: *[u8],
684
685
    // ~ SSA variable tracking ~ //
686
687
    /// Metadata (name, type, mutability) for each variable. Indexed by variable
688
    /// id. Doesn't change after declaration. For the SSA value of a variable in
689
    /// a specific block, see [`BlockData::vars`].
690
    vars: *mut [VarData],
691
    /// Parameter-to-variable bindings, initialized in the entry block.
692
    params: *mut [FnParamBinding],
693
694
    // ~ Basic block management ~ //
695
696
    /// Block storage array, indexed by block id.
697
    blockData: *mut [BlockData],
698
    /// The entry block for this function.
699
    entryBlock: ?BlockId,
700
    /// The block currently receiving new instructions.
701
    currentBlock: ?BlockId,
702
703
    // ~ Loop management ~ //
704
705
    /// Stack of loop contexts for break/continue resolution.
706
    loopStack: *mut [LoopCtx],
707
    /// Current nesting depth (index into loopStack).
708
    loopDepth: u32,
709
710
    // ~ Counters ~ //
711
712
    /// Counter for generating unique block labels like `then#0`, `loop#1`, etc.
713
    labelCounter: u32,
714
    /// Counter for generating unique data names within this function.
715
    /// Each literal gets a name like `fnName$literal$N`.
716
    dataCounter: u32,
717
    /// Counter for generating SSA register numbers.
718
    regCounter: u32,
719
    /// When the function returns an aggregate type, the caller passes a hidden
720
    /// pointer as the first parameter. The callee writes the return value into
721
    /// this buffer and returns the pointer.
722
    returnReg: ?il::Reg,
723
    /// Whether the function is a leaf.
724
    isLeaf: bool,
725
726
    // ~ Debug info ~ //
727
728
    /// Current debug source location, set when processing AST nodes.
729
    srcLoc: il::SrcLoc,
730
}
731
732
/////////////////////////////////
733
// Module Lowering Entry Point //
734
/////////////////////////////////
735
736
/// Lower a complete module AST to an IL program.
737
///
738
/// This is the main entry point for the lowering pass. It:
739
/// 1. Counts functions to preallocate the output array.
740
/// 2. Iterates over top-level declarations, lowering each.
741
/// 3. Returns the complete IL program with functions and data section.
742
///
743
/// The resolver must have already processed the AST -- we rely on its type
744
/// annotations, symbol table, and constant evaluations.
745
export fn lower(
746
    res: *resolver::Resolver,
747
    root: *ast::Node,
748
    pkgName: *[u8],
749
    arena: *mut alloc::Arena
750
) -> il::Program throws (LowerError) {
751
    let mut low = Lowerer {
752
        arena: arena,
753
        fnArena: arena,
754
        allocator: alloc::arenaAllocator(arena),
755
        resolver: res,
756
        moduleGraph: nil,
757
        pkgName,
758
        currentMod: nil,
759
        data: &mut [],
760
        output: FnOutput::Accumulate(&mut []),
761
        fnSyms: &mut [],
762
        errTags: &mut [],
763
        errTagCounter: 1,
764
        options: LowerOptions { debug: false, buildTest: false },
765
    };
766
    try lowerDecls(&mut low, root, true);
767
768
    return finalize(&low);
769
}
770
771
/////////////////////////////////
772
// Multi-Module Lowering API   //
773
/////////////////////////////////
774
775
/// Create a lowerer for multi-module compilation.
776
export fn lowerer(
777
    res: *resolver::Resolver,
778
    graph: *module::ModuleGraph,
779
    pkgName: *[u8],
780
    arena: *mut alloc::Arena,
781
    fnArena: *mut alloc::Arena,
782
    options: LowerOptions
783
) -> Lowerer {
784
    return Lowerer {
785
        arena,
786
        fnArena,
787
        allocator: alloc::arenaAllocator(arena),
788
        resolver: res,
789
        moduleGraph: graph,
790
        pkgName,
791
        currentMod: nil,
792
        data: &mut [],
793
        output: FnOutput::Accumulate(&mut []),
794
        fnSyms: &mut [],
795
        errTags: &mut [],
796
        errTagCounter: 1,
797
        options,
798
    };
799
}
800
801
/// Lower a module's AST into the lowerer.
802
/// Call this for each module in the package, then use `finalize` to get the program.
803
export fn lowerModule(
804
    low: *mut Lowerer,
805
    moduleId: u16,
806
    root: *ast::Node,
807
    isRoot: bool
808
) throws (LowerError) {
809
    set low.currentMod = moduleId;
810
    try lowerDecls(low, root, isRoot);
811
}
812
813
/// Lower all top-level declarations in a block.
814
fn lowerDecls(low: *mut Lowerer, root: *ast::Node, isRoot: bool) throws (LowerError) {
815
    let case ast::NodeValue::Block(block) = root.value else {
816
        throw LowerError::ExpectedBlock(root);
817
    };
818
    let stmtsList = block.statements;
819
820
    for node in stmtsList {
821
        match node.value {
822
            case ast::NodeValue::FnDecl(decl) => {
823
                if let f = try lowerFnDecl(low, node, decl) {
824
                    let role = lowerFnRole(isRoot, decl.attrs);
825
                    emitFunction(low, f, role);
826
                }
827
            }
828
            case ast::NodeValue::ConstDecl(decl) => {
829
                try lowerDataDecl(low, node, decl.value, true);
830
            }
831
            case ast::NodeValue::StaticDecl(decl) => {
832
                try lowerDataDecl(low, node, decl.value, false);
833
            }
834
            case ast::NodeValue::InstanceDecl { traitName, targetType, methods } => {
835
                try lowerInstanceDecl(low, node, traitName, targetType, methods);
836
            }
837
            case ast::NodeValue::MethodDecl { name, receiverName, receiverType, sig, body, .. } => {
838
                if let f = try lowerMethodDecl(low, node, name, receiverName, sig, body) {
839
                    emitFunction(low, f, FnRole::Normal);
840
                }
841
            }
842
            else => {},
843
        }
844
    }
845
}
846
847
/// Finalize lowering and return the unified IL program.
848
export fn finalize(low: *Lowerer) -> il::Program {
849
    let mut fns: *mut [*il::Fn] = undefined;
850
    match low.output {
851
        case FnOutput::Accumulate(accumulated) => {
852
            set fns = accumulated;
853
        }
854
        case FnOutput::Stream(_) => {
855
            panic "finalize: cannot finalize streaming lowerer";
856
        }
857
    }
858
    return il::Program {
859
        data: &low.data[..],
860
        fns: &fns[..],
861
    };
862
}
863
864
/////////////////////////////////
865
// Qualified Name Construction //
866
/////////////////////////////////
867
868
/// Get module path segments for the current or specified module.
869
/// Returns empty slice if no module graph or module not found.
870
fn getModulePath(self: *mut Lowerer, modId: ?u16) -> *[*[u8]] {
871
    let graph = self.moduleGraph else {
872
        return &[];
873
    };
874
    let mut id = modId;
875
    if id == nil {
876
        set id = self.currentMod;
877
    }
878
    let actualId = id else {
879
        return &[];
880
    };
881
    let entry = module::get(graph, actualId) else {
882
        return &[];
883
    };
884
    return module::moduleQualifiedPath(entry);
885
}
886
887
/// Build a qualified name string for a symbol.
888
/// If `modId` is nil, uses current module.
889
fn qualifyName(self: *mut Lowerer, modId: ?u16, name: *[u8]) -> *[u8] {
890
    let path = getModulePath(self, modId);
891
    if path.len == 0 {
892
        return name;
893
    }
894
    return il::formatQualifiedName(self.arena, path, name);
895
}
896
897
/// Register a function symbol with its qualified name.
898
/// Called when lowering function declarations, so cross-package calls can find
899
/// the function by name.
900
fn registerFnSym(self: *mut Lowerer, sym: *resolver::Symbol, qualName: *[u8]) {
901
    self.fnSyms.append(FnSymEntry { sym, qualName }, self.allocator);
902
}
903
904
/// Look up a function's qualified name by its symbol.
905
/// Returns `nil` if the symbol wasn't registered (e.g. callee's module is not yet lowered).
906
// TODO: This is kind of dubious as an optimization, if it depends on the order
907
// in which modules are lowered.
908
// TODO: Use a hash table here?
909
fn lookupFnSym(self: *Lowerer, sym: *resolver::Symbol) -> ?*[u8] {
910
    for entry in self.fnSyms {
911
        if entry.sym == sym {
912
            return entry.qualName;
913
        }
914
    }
915
    return nil;
916
}
917
918
/// Set the package context for lowering.
919
/// Called before lowering each package.
920
export fn setPackage(self: *mut Lowerer, graph: *module::ModuleGraph, pkgName: *[u8]) {
921
    set self.moduleGraph = graph;
922
    set self.pkgName = pkgName;
923
    set self.currentMod = nil;
924
}
925
926
/// Create a new function lowerer for a given function type and name.
927
fn fnLowerer(
928
    self: *mut Lowerer,
929
    node: *ast::Node,
930
    fnType: *resolver::FnType,
931
    qualName: *[u8]
932
) -> FnLowerer {
933
    let loopStack = try! alloc::allocSlice(self.fnArena, @sizeOf(LoopCtx), @alignOf(LoopCtx), MAX_LOOP_DEPTH) as *mut [LoopCtx];
934
935
    let mut fnLow = FnLowerer {
936
        low: self,
937
        allocator: alloc::arenaAllocator(self.fnArena),
938
        fnType: fnType,
939
        fnName: qualName,
940
        vars: &mut [],
941
        params: &mut [],
942
        blockData: &mut [],
943
        entryBlock: nil,
944
        currentBlock: nil,
945
        loopStack,
946
        loopDepth: 0,
947
        labelCounter: 0,
948
        dataCounter: 0,
949
        regCounter: 0,
950
        returnReg: nil,
951
        isLeaf: true,
952
        srcLoc: undefined,
953
    };
954
    if self.options.debug {
955
        let modId = self.currentMod else {
956
            panic "fnLowerer: debug enabled but no current module";
957
        };
958
        set fnLow.srcLoc = il::SrcLoc {
959
            moduleId: modId,
960
            offset: node.span.offset,
961
        };
962
    }
963
    return fnLow;
964
}
965
966
/// Lower a function declaration.
967
///
968
/// This sets up the per-function lowering state, processes parameters,
969
/// then lowers the function body into a CFG of basic blocks.
970
///
971
/// For throwing functions, the return type is a result aggregate
972
/// rather than the declared return type.
973
fn lowerFnDecl(self: *mut Lowerer, node: *ast::Node, decl: ast::FnDecl) -> ?*il::Fn throws (LowerError) {
974
    if not shouldLowerFn(&decl, self.options.buildTest) {
975
        return nil;
976
    }
977
    let case ast::NodeValue::Ident(name) = decl.name.value else {
978
        throw LowerError::ExpectedIdentifier;
979
    };
980
    let data = resolver::nodeData(self.resolver, node);
981
    let case resolver::Type::Fn(fnType) = data.ty else {
982
        throw LowerError::ExpectedFunction;
983
    };
984
    let isExtern = checkAttr(decl.attrs, ast::Attribute::Extern);
985
986
    // Build qualified function name for multi-module compilation.
987
    let qualName = qualifyName(self, nil, name);
988
989
    // Register function symbol for cross-package call resolution.
990
    if let sym = data.sym {
991
        registerFnSym(self, sym, qualName);
992
    }
993
    let mut fnLow = fnLowerer(self, node, fnType, qualName);
994
995
    // If the function returns an aggregate or is throwing, prepend a hidden
996
    // return parameter. The caller allocates the buffer and passes it
997
    // as the first argument; the callee writes the return value into it.
998
    if requiresReturnParam(fnType) and not isExtern {
999
        set fnLow.returnReg = nextReg(&mut fnLow);
1000
    }
1001
    let lowParams = try lowerParams(&mut fnLow, *fnType, decl.sig.params, nil);
1002
    let func = try! alloc::alloc(self.fnArena, @sizeOf(il::Fn), @alignOf(il::Fn)) as *mut il::Fn;
1003
1004
    set *func = il::Fn {
1005
        name: qualName,
1006
        params: lowParams,
1007
        returnType: undefined,
1008
        isExtern,
1009
        isLeaf: true,
1010
        blocks: &[],
1011
    };
1012
    // Throwing functions return a result aggregate (word-sized pointer).
1013
    // TODO: The resolver should set an appropriate type that takes into account
1014
    //       the throws list. It shouldn't set the return type to the "success"
1015
    //       value only.
1016
    if fnType.throwList.len > 0 {
1017
        set func.returnType = il::Type::W64;
1018
    } else {
1019
        set func.returnType = ilType(self, *fnType.returnType);
1020
    }
1021
    let body = decl.body else {
1022
        // Extern functions have no body.
1023
        assert isExtern;
1024
        return func;
1025
    };
1026
    set func.blocks = try lowerFnBody(&mut fnLow, body);
1027
    set func.isLeaf = fnLow.isLeaf;
1028
1029
    return func;
1030
}
1031
1032
/// Build a qualified name of the form "Type::method".
1033
fn instanceMethodName(self: *mut Lowerer, modId: ?u16, typeName: *[u8], methodName: *[u8]) -> *[u8] {
1034
    let sepLen: u32 = 2; // "::"
1035
    let totalLen = typeName.len + sepLen + methodName.len;
1036
    let buf = try! alloc::allocSlice(self.arena, 1, 1, totalLen) as *mut [u8];
1037
    let mut pos: u32 = 0;
1038
1039
    set pos += try! mem::copy(&mut buf[pos..], typeName);
1040
    set pos += try! mem::copy(&mut buf[pos..], "::");
1041
    set pos += try! mem::copy(&mut buf[pos..], methodName);
1042
    assert pos == totalLen;
1043
1044
    return qualifyName(self, modId, &buf[..totalLen]);
1045
}
1046
1047
/// Build a v-table data name of the form "vtable::Type::Trait".
1048
fn vtableName(self: *mut Lowerer, modId: ?u16, typeName: *[u8], traitName: *[u8]) -> *[u8] {
1049
    let prefix = "vtable::";
1050
    let sepLen: u32 = 2; // "::"
1051
    let totalLen = prefix.len + typeName.len + sepLen + traitName.len;
1052
    let buf = try! alloc::allocSlice(self.arena, 1, 1, totalLen) as *mut [u8];
1053
    let mut pos: u32 = 0;
1054
1055
    set pos += try! mem::copy(&mut buf[pos..], prefix);
1056
    set pos += try! mem::copy(&mut buf[pos..], typeName);
1057
    set pos += try! mem::copy(&mut buf[pos..], "::");
1058
    set pos += try! mem::copy(&mut buf[pos..], traitName);
1059
    assert pos == totalLen;
1060
1061
    return qualifyName(self, modId, &buf[..totalLen]);
1062
}
1063
1064
/// Lower an instance declaration (`instance Trait for Type { ... }`).
1065
///
1066
/// Each method in the instance block is lowered as a standalone function
1067
/// with a qualified name of the form `Type::method`. A read-only v-table
1068
/// data record is emitted containing pointers to these functions, ordered
1069
/// by the trait's method indices. The v-table is later referenced when
1070
/// constructing trait objects for dynamic dispatch.
1071
fn lowerInstanceDecl(
1072
    self: *mut Lowerer,
1073
    node: *ast::Node,
1074
    traitNameNode: *ast::Node,
1075
    targetTypeNode: *ast::Node,
1076
    methods: *mut [*ast::Node]
1077
) throws (LowerError) {
1078
    // Look up the trait and type from the resolver.
1079
    let traitSym = resolver::nodeData(self.resolver, traitNameNode).sym
1080
        else throw LowerError::MissingSymbol(traitNameNode);
1081
    let case resolver::SymbolData::Trait(traitInfo) = traitSym.data
1082
        else throw LowerError::MissingMetadata;
1083
    let typeSym = resolver::nodeData(self.resolver, targetTypeNode).sym
1084
        else throw LowerError::MissingSymbol(targetTypeNode);
1085
1086
    let tName = traitSym.name;
1087
    let typeName = typeSym.name;
1088
1089
    // Lower each instance method as a regular function.
1090
    // Collect qualified names for the v-table. Empty entries are filled
1091
    // later from inherited supertrait methods.
1092
    let mut methodNames: [*[u8]; ast::MAX_TRAIT_METHODS] = undefined;
1093
    let mut methodNameSet: [bool; ast::MAX_TRAIT_METHODS] = [false; ast::MAX_TRAIT_METHODS];
1094
1095
    for methodNode in methods {
1096
        let case ast::NodeValue::MethodDecl {
1097
            name, receiverName, receiverType, sig, body, ..
1098
        } = methodNode.value else continue;
1099
1100
        let case ast::NodeValue::Ident(mName) = name.value else {
1101
            throw LowerError::ExpectedIdentifier;
1102
        };
1103
        let qualName = instanceMethodName(self, nil, typeName, mName);
1104
        let func = try lowerMethod(self, methodNode, qualName, receiverName, sig, body)
1105
            else continue;
1106
        emitFunction(self, func, FnRole::Normal);
1107
1108
        let method = resolver::findTraitMethod(traitInfo, mName)
1109
            else panic "lowerInstanceDecl: method not found in trait";
1110
1111
        set methodNames[method.index] = qualName;
1112
        set methodNameSet[method.index] = true;
1113
    }
1114
1115
    // Fill inherited method slots from supertraits.
1116
    // These methods were already lowered as part of the supertrait instance
1117
    // declarations and use the same `Type::method` qualified name.
1118
    for method, i in traitInfo.methods {
1119
        if not methodNameSet[i] {
1120
            set methodNames[i] = instanceMethodName(self, nil, typeName, method.name);
1121
        }
1122
    }
1123
1124
    // Create v-table in data section, used for dynamic dispatch.
1125
    let vName = vtableName(self, nil, typeName, tName);
1126
    let values = try! alloc::allocSlice(
1127
        self.arena, @sizeOf(il::DataValue), @alignOf(il::DataValue), traitInfo.methods.len as u32
1128
    ) as *mut [il::DataValue];
1129
1130
    for i in 0..traitInfo.methods.len {
1131
        set values[i] = il::DataValue {
1132
            item: il::DataItem::Fn(methodNames[i]),
1133
            count: 1,
1134
        };
1135
    }
1136
    self.data.append(il::Data {
1137
        name: vName,
1138
        size: traitInfo.methods.len as u32 * resolver::PTR_SIZE,
1139
        alignment: resolver::PTR_SIZE,
1140
        readOnly: true,
1141
        isZeroInit: false,
1142
        values: &values[..traitInfo.methods.len as u32],
1143
    }, self.allocator);
1144
}
1145
1146
/// Lower a method node into an IL function with the given qualified name.
1147
/// Shared by both instance methods and standalone methods.
1148
fn lowerMethod(
1149
    self: *mut Lowerer,
1150
    node: *ast::Node,
1151
    qualName: *[u8],
1152
    receiverName: *ast::Node,
1153
    sig: ast::FnSig,
1154
    body: *ast::Node,
1155
) -> ?*il::Fn throws (LowerError) {
1156
    let data = resolver::nodeData(self.resolver, node);
1157
    let case resolver::Type::Fn(fnType) = data.ty else {
1158
        throw LowerError::ExpectedFunction;
1159
    };
1160
    let sym = data.sym else throw LowerError::MissingSymbol(node);
1161
    registerFnSym(self, sym, qualName);
1162
1163
    let mut fnLow = fnLowerer(self, node, fnType, qualName);
1164
    if requiresReturnParam(fnType) {
1165
        set fnLow.returnReg = nextReg(&mut fnLow);
1166
    }
1167
    let lowParams = try lowerParams(&mut fnLow, *fnType, sig.params, receiverName);
1168
    let func = try! alloc::alloc(self.fnArena, @sizeOf(il::Fn), @alignOf(il::Fn)) as *mut il::Fn;
1169
1170
    set *func = il::Fn {
1171
        name: qualName,
1172
        params: lowParams,
1173
        returnType: ilType(self, *fnType.returnType),
1174
        isExtern: false,
1175
        isLeaf: true,
1176
        blocks: &[],
1177
    };
1178
    if fnType.throwList.len > 0 {
1179
        set func.returnType = il::Type::W64;
1180
    }
1181
    set func.blocks = try lowerFnBody(&mut fnLow, body);
1182
    set func.isLeaf = fnLow.isLeaf;
1183
1184
    return func;
1185
}
1186
1187
/// Lower a standalone method declaration.
1188
/// Produces a function with qualified name `Type::method`.
1189
fn lowerMethodDecl(
1190
    self: *mut Lowerer,
1191
    node: *ast::Node,
1192
    name: *ast::Node,
1193
    receiverName: *ast::Node,
1194
    sig: ast::FnSig,
1195
    body: *ast::Node,
1196
) -> ?*il::Fn throws (LowerError) {
1197
    let sym = resolver::nodeData(self.resolver, node).sym
1198
        else throw LowerError::MissingSymbol(node);
1199
    let case ast::NodeValue::Ident(mName) = name.value
1200
        else throw LowerError::ExpectedIdentifier;
1201
    let me = resolver::findMethodBySymbol(self.resolver, sym)
1202
        else throw LowerError::MissingMetadata;
1203
    let qualName = instanceMethodName(self, nil, me.concreteTypeName, mName);
1204
1205
    return try lowerMethod(self, node, qualName, receiverName, sig, body);
1206
}
1207
1208
/// Check if a function should be lowered.
1209
fn shouldLowerFn(decl: *ast::FnDecl, buildTest: bool) -> bool {
1210
    if checkAttr(decl.attrs, ast::Attribute::Test) {
1211
        return buildTest;
1212
    }
1213
    return true;
1214
}
1215
1216
/// Check if a specific attribute is present in the attribute set.
1217
fn checkAttr(attrs: ?ast::Attributes, attr: ast::Attribute) -> bool {
1218
    if let a = attrs {
1219
        return ast::attributesContains(&a, attr);
1220
    }
1221
    return false;
1222
}
1223
1224
/// Create a label with a numeric suffix, eg. `@base0`.
1225
/// This ensures unique labels like `@then0`, `@then1`, etc.
1226
fn labelWithSuffix(self: *mut FnLowerer, base: *[u8], suffix: u32) -> *[u8] throws (LowerError) {
1227
    let mut digits: [u8; fmt::U32_STR_LEN] = undefined;
1228
    let suffixText = fmt::formatU32(suffix, &mut digits[..]);
1229
    let totalLen = base.len + suffixText.len;
1230
    let buf = try! alloc::allocSlice(self.low.fnArena, 1, 1, totalLen) as *mut [u8];
1231
1232
    try! mem::copy(&mut buf[..base.len], base);
1233
    try! mem::copy(&mut buf[base.len..totalLen], suffixText);
1234
1235
    return &buf[..totalLen];
1236
}
1237
1238
/// Generate a unique label by appending the global counter to the base.
1239
fn nextLabel(self: *mut FnLowerer, base: *[u8]) -> *[u8] throws (LowerError) {
1240
    let idx = self.labelCounter;
1241
    set self.labelCounter += 1;
1242
1243
    return try labelWithSuffix(self, base, idx);
1244
}
1245
1246
///////////////////////////////
1247
// Data Section Construction //
1248
///////////////////////////////
1249
1250
// Functions for building the data section from constant/static
1251
// declarations and inline literals.
1252
1253
/// Convert a constant integer payload to a signed 64-bit value.
1254
fn constIntToI64(intVal: resolver::ConstInt) -> i64 {
1255
    return (0 - intVal.magnitude as i64) if intVal.negative else intVal.magnitude as i64;
1256
}
1257
1258
/// Convert a scalar constant value to an i64.
1259
/// String constants are not handled here and should be checked before calling.
1260
/// Panics if a non-scalar value is passed.
1261
fn constToScalar(val: resolver::ConstValue) -> i64 {
1262
    match val {
1263
        case resolver::ConstValue::Bool(b) => return 1 if b else 0,
1264
        case resolver::ConstValue::Char(c) => return c as i64,
1265
        case resolver::ConstValue::Int(i) => return constIntToI64(i),
1266
        else => panic,
1267
    }
1268
}
1269
1270
/// Convert a constant value to an IL value.
1271
fn constValueToVal(self: *mut FnLowerer, val: resolver::ConstValue, node: *ast::Node) -> il::Val throws (LowerError) {
1272
    if let case resolver::ConstValue::String(s) = val {
1273
        return try lowerStringLit(self, node, s);
1274
    }
1275
    return il::Val::Imm(constToScalar(val));
1276
}
1277
1278
/// Convert a resolver constant value to an IL data initializer item.
1279
fn constValueToDataItem(self: *mut Lowerer, val: resolver::ConstValue, typ: resolver::Type) -> il::DataItem {
1280
    if let case resolver::ConstValue::String(s) = val {
1281
        return il::DataItem::Str(s);
1282
    }
1283
    // Bool and char are byte-sized; integer uses the declared type.
1284
    let mut irTyp = il::Type::W8;
1285
    if let case resolver::ConstValue::Int(_) = val {
1286
        set irTyp = ilType(self, typ);
1287
    }
1288
    return il::DataItem::Val { typ: irTyp, val: constToScalar(val) };
1289
}
1290
1291
/// Lower scalar-like constant nodes into data values, including fallback handling
1292
/// for void-variant tags and slice string initializers.
1293
fn lowerConstScalarDataInto(
1294
    self: *mut Lowerer,
1295
    node: *ast::Node,
1296
    ty: resolver::Type,
1297
    dataPrefix: *[u8],
1298
    b: *mut DataValueBuilder
1299
) throws (LowerError) {
1300
    let val = resolver::constValueEntry(self.resolver, node) else {
1301
        if let idx = voidVariantIndex(self.resolver, node) {
1302
            dataBuilderPush(b, il::DataValue {
1303
                item: il::DataItem::Val { typ: il::Type::W8, val: idx },
1304
                count: 1
1305
            });
1306
            return;
1307
        }
1308
        throw LowerError::MissingConst(node);
1309
    };
1310
1311
    if let case resolver::ConstValue::String(s) = val {
1312
        if let case resolver::Type::Slice { .. } = ty {
1313
            let strSym = try getOrCreateStringData(self, s, dataPrefix);
1314
            dataSliceHeader(b, strSym, s.len);
1315
            return;
1316
        }
1317
    }
1318
    dataBuilderPush(b, il::DataValue {
1319
        item: constValueToDataItem(self, val, ty),
1320
        count: 1
1321
    });
1322
}
1323
1324
/// Lower a constant or static declaration to the data section.
1325
fn lowerDataDecl(
1326
    self: *mut Lowerer,
1327
    node: *ast::Node,
1328
    value: *ast::Node,
1329
    readOnly: bool
1330
) throws (LowerError) {
1331
    let data = resolver::nodeData(self.resolver, node);
1332
    let sym = data.sym else {
1333
        throw LowerError::MissingSymbol(node);
1334
    };
1335
    if data.ty == resolver::Type::Unknown {
1336
        throw LowerError::MissingType(node);
1337
    }
1338
    let layout = resolver::getTypeLayout(data.ty);
1339
    let qualName = qualifyName(self, nil, sym.name);
1340
    let mut b = dataBuilder(self.allocator);
1341
    try lowerConstDataInto(self, value, data.ty, layout.size, qualName, &mut b);
1342
    let result = dataBuilderFinish(&b);
1343
1344
    self.data.append(il::Data {
1345
        name: qualName,
1346
        size: layout.size,
1347
        alignment: layout.alignment,
1348
        readOnly,
1349
        isZeroInit: not readOnly and result.zeroInit,
1350
        values: result.values,
1351
    }, self.allocator);
1352
}
1353
1354
/// Emit the in-memory representation of a slice header: `{ ptr, len, cap }`.
1355
fn dataSliceHeader(b: *mut DataValueBuilder, dataSym: *[u8], len: u32) {
1356
    dataBuilderPush(b, il::DataValue {
1357
        item: il::DataItem::Sym(dataSym),
1358
        count: 1
1359
    });
1360
    dataBuilderPush(b, il::DataValue {
1361
        item: il::DataItem::Val {
1362
            typ: il::Type::W32,
1363
            val: len as i64
1364
        },
1365
        count: 1
1366
    });
1367
    dataBuilderPush(b, il::DataValue {
1368
        item: il::DataItem::Val {
1369
            typ: il::Type::W32,
1370
            val: len as i64
1371
        },
1372
        count: 1
1373
    });
1374
}
1375
1376
/// Lower a compile-time `&[...]` expression to a concrete slice header.
1377
fn lowerConstAddressSliceInto(
1378
    self: *mut Lowerer,
1379
    addr: ast::AddressOf,
1380
    ty: resolver::Type,
1381
    dataPrefix: *[u8],
1382
    b: *mut DataValueBuilder
1383
) throws (LowerError) {
1384
    let case resolver::Type::Slice { mutable, .. } = ty
1385
        else throw LowerError::ExpectedSliceOrArray;
1386
    let targetTy = resolver::typeFor(self.resolver, addr.target)
1387
        else throw LowerError::MissingType(addr.target);
1388
    let case resolver::Type::Array(arrInfo) = targetTy
1389
        else throw LowerError::ExpectedArray;
1390
1391
    let mut nested = dataBuilder(self.allocator);
1392
    let layout = resolver::getTypeLayout(targetTy);
1393
    try lowerConstDataInto(self, addr.target, targetTy, layout.size, dataPrefix, &mut nested);
1394
1395
    let backing = dataBuilderFinish(&nested);
1396
    let readOnly = not mutable;
1397
    let mut dataName: *[u8] = undefined;
1398
    if readOnly {
1399
        if let found = findConstData(self, backing.values, layout.alignment) {
1400
            set dataName = found;
1401
        } else {
1402
            set dataName = try pushDeclData(self, layout.size, layout.alignment, readOnly, backing.values, dataPrefix);
1403
        }
1404
    } else {
1405
        set dataName = try pushDeclData(self, layout.size, layout.alignment, readOnly, backing.values, dataPrefix);
1406
    }
1407
    dataSliceHeader(b, dataName, arrInfo.length);
1408
}
1409
1410
/// Lower a constant expression payload into a builder without slot padding.
1411
fn lowerConstDataPayloadInto(
1412
    self: *mut Lowerer,
1413
    node: *ast::Node,
1414
    ty: resolver::Type,
1415
    dataPrefix: *[u8],
1416
    b: *mut DataValueBuilder
1417
) throws (LowerError) {
1418
    // Function pointer references in constant data.
1419
    if let case resolver::Type::Fn(_) = ty {
1420
        let sym = resolver::nodeData(self.resolver, node).sym
1421
            else throw LowerError::MissingSymbol(node);
1422
        let modId = resolver::moduleIdForSymbol(self.resolver, sym);
1423
        let qualName = qualifyName(self, modId, sym.name);
1424
        dataBuilderPush(b, il::DataValue {
1425
            item: il::DataItem::Fn(qualName), count: 1,
1426
        });
1427
        return;
1428
    }
1429
    // In constant data, a void variant of a mixed union still occupies the
1430
    // full tagged-union slot. Emitting only the tag corrupts following fields.
1431
    if let sym = resolver::nodeData(self.resolver, node).sym {
1432
        if let case resolver::SymbolData::Variant { type: resolver::Type::Void, .. } = sym.data {
1433
            if let case resolver::Type::Nominal(resolver::NominalType::Union(_)) = ty {
1434
                try lowerConstUnionVariantInto(self, node, sym, ty, &mut [], dataPrefix, b);
1435
                return;
1436
            }
1437
        }
1438
    }
1439
    let layout = resolver::getTypeLayout(ty);
1440
1441
    match node.value {
1442
        case ast::NodeValue::Undef => {
1443
            dataBuilderPush(b, il::DataValue {
1444
                item: il::DataItem::Undef,
1445
                count: layout.size
1446
            });
1447
        }
1448
        case ast::NodeValue::ArrayLit(elems) =>
1449
            try lowerConstArrayLitInto(self, elems, ty, dataPrefix, b),
1450
        case ast::NodeValue::ArrayRepeatLit(repeat) =>
1451
            try lowerConstArrayRepeatInto(self, repeat, ty, dataPrefix, b),
1452
        case ast::NodeValue::RecordLit(recLit) =>
1453
            try lowerConstRecordLitInto(self, node, recLit, ty, dataPrefix, b),
1454
        case ast::NodeValue::Call(call) => {
1455
            let calleeSym = resolver::nodeData(self.resolver, call.callee).sym
1456
                else throw LowerError::MissingSymbol(call.callee);
1457
            match calleeSym.data {
1458
                case resolver::SymbolData::Variant { .. } =>
1459
                    try lowerConstUnionVariantInto(self, node, calleeSym, ty, call.args, dataPrefix, b),
1460
                case resolver::SymbolData::Type(resolver::NominalType::Record(recInfo)) => {
1461
                    try lowerConstRecordCtorInto(self, call.args, recInfo, dataPrefix, b);
1462
                }
1463
                else => throw LowerError::MissingConst(node)
1464
            }
1465
        }
1466
        case ast::NodeValue::AddressOf(addr) => {
1467
            try lowerConstAddressSliceInto(self, addr, ty, dataPrefix, b);
1468
        }
1469
        case ast::NodeValue::Ident(_) => {
1470
            // Identifier referencing a constant.
1471
            let sym = resolver::nodeData(self.resolver, node).sym
1472
                else throw LowerError::MissingSymbol(node);
1473
            let case ast::NodeValue::ConstDecl(decl) = sym.node.value
1474
                else throw LowerError::MissingConst(node);
1475
1476
            try lowerConstDataPayloadInto(self, decl.value, ty, dataPrefix, b);
1477
        },
1478
        case ast::NodeValue::ScopeAccess(_) => {
1479
            let sym = resolver::nodeData(self.resolver, node).sym
1480
                else throw LowerError::MissingSymbol(node);
1481
            if let case ast::NodeValue::ConstDecl(decl) = sym.node.value {
1482
                try lowerConstDataPayloadInto(self, decl.value, ty, dataPrefix, b);
1483
            } else {
1484
                try lowerConstScalarDataInto(self, node, ty, dataPrefix, b);
1485
            }
1486
        }
1487
        else => {
1488
            // Scalar values: integers, bools, strings, void union variants, etc.
1489
            try lowerConstScalarDataInto(self, node, ty, dataPrefix, b);
1490
        }
1491
    }
1492
}
1493
1494
/// Lower a constant expression into a builder, padding to the given slot size.
1495
fn lowerConstDataInto(
1496
    self: *mut Lowerer,
1497
    node: *ast::Node,
1498
    ty: resolver::Type,
1499
    slotSize: u32,
1500
    dataPrefix: *[u8],
1501
    b: *mut DataValueBuilder
1502
) throws (LowerError) {
1503
    let layout = resolver::getTypeLayout(ty);
1504
    try lowerConstDataPayloadInto(self, node, ty, dataPrefix, b);
1505
    // Pad to fill the enclosing slot.
1506
    let padding = slotSize - layout.size;
1507
    if padding > 0 {
1508
        dataBuilderPush(b, il::DataValue { item: il::DataItem::Undef, count: padding });
1509
    }
1510
}
1511
1512
/// Flatten a constant array literal `[a, b, c]` into a builder.
1513
fn lowerConstArrayLitInto(
1514
    self: *mut Lowerer,
1515
    elems: *mut [*ast::Node],
1516
    ty: resolver::Type,
1517
    dataPrefix: *[u8],
1518
    b: *mut DataValueBuilder
1519
) throws (LowerError) {
1520
    let case resolver::Type::Array(arrInfo) = ty
1521
        else throw LowerError::ExpectedArray;
1522
    let elemTy = *arrInfo.item;
1523
    let elemLayout = resolver::getTypeLayout(elemTy);
1524
1525
    for elem in elems {
1526
        try lowerConstDataInto(self, elem, elemTy, elemLayout.size, dataPrefix, b);
1527
    }
1528
}
1529
1530
/// Build data values for a constant array repeat literal `[item; count]`.
1531
fn lowerConstArrayRepeatInto(
1532
    self: *mut Lowerer,
1533
    repeat: ast::ArrayRepeatLit,
1534
    ty: resolver::Type,
1535
    dataPrefix: *[u8],
1536
    b: *mut DataValueBuilder
1537
) throws (LowerError) {
1538
    let case resolver::Type::Array(arrInfo) = ty
1539
        else throw LowerError::ExpectedArray;
1540
    let length = arrInfo.length;
1541
    let elemTy = *arrInfo.item;
1542
    let elemLayout = resolver::getTypeLayout(elemTy);
1543
1544
    if let case ast::NodeValue::Undef = repeat.item.value {
1545
        dataBuilderPush(b, il::DataValue {
1546
            item: il::DataItem::Undef,
1547
            count: elemLayout.size * length
1548
        });
1549
    } else if let val = resolver::constValueEntry(self.resolver, repeat.item) {
1550
        if let case resolver::ConstValue::String(_) = val {
1551
            // A string used as a slice is represented by a three-word slice
1552
            // header, not by the bytes of the string itself.
1553
            for _ in 0..length {
1554
                try lowerConstDataInto(self, repeat.item, elemTy, elemLayout.size, dataPrefix, b);
1555
            }
1556
        } else {
1557
            dataBuilderPush(b, il::DataValue {
1558
                item: constValueToDataItem(self, val, elemTy),
1559
                count: length
1560
            });
1561
        }
1562
    } else {
1563
        for _ in 0..length {
1564
            try lowerConstDataInto(self, repeat.item, elemTy, elemLayout.size, dataPrefix, b);
1565
        }
1566
    }
1567
}
1568
1569
/// Build data values for a constant record literal.
1570
/// Each field is lowered with a slot size that includes trailing padding.
1571
fn lowerConstRecordLitInto(
1572
    self: *mut Lowerer,
1573
    node: *ast::Node,
1574
    recLit: ast::RecordLit,
1575
    ty: resolver::Type,
1576
    dataPrefix: *[u8],
1577
    b: *mut DataValueBuilder
1578
) throws (LowerError) {
1579
    match ty {
1580
        case resolver::Type::Nominal(resolver::NominalType::Record(recInfo)) => {
1581
            try lowerConstRecordCtorInto(self, recLit.fields, recInfo, dataPrefix, b);
1582
        }
1583
        case resolver::Type::Nominal(resolver::NominalType::Union(_)) => {
1584
            let typeName = recLit.typeName else {
1585
                throw LowerError::ExpectedVariant;
1586
            };
1587
            let sym = resolver::nodeData(self.resolver, typeName).sym else {
1588
                throw LowerError::MissingSymbol(typeName);
1589
            };
1590
            try lowerConstUnionVariantInto(self, node, sym, ty, recLit.fields, dataPrefix, b);
1591
        }
1592
        else => throw LowerError::ExpectedRecord,
1593
    }
1594
}
1595
1596
/// Build data values for record constants.
1597
fn lowerConstRecordCtorInto(
1598
    self: *mut Lowerer,
1599
    args: *mut [*ast::Node],
1600
    recInfo: resolver::RecordType,
1601
    dataPrefix: *[u8],
1602
    b: *mut DataValueBuilder
1603
) throws (LowerError) {
1604
    let layout = recInfo.layout;
1605
    for argNode, i in args {
1606
        let mut valueNode = argNode;
1607
        if let case ast::NodeValue::RecordLitField(fieldLit) = argNode.value {
1608
            set valueNode = fieldLit.value;
1609
        }
1610
        let fieldInfo = recInfo.fields[i];
1611
        let fieldOffset = fieldInfo.offset as u32;
1612
1613
        // Slot extends to the next field's offset,
1614
        // or record size for the last field.
1615
        let slotEnd = recInfo.fields[i + 1].offset as u32 if i + 1 < recInfo.fields.len else layout.size;
1616
        let slotSize = slotEnd - fieldOffset;
1617
1618
        try lowerConstDataInto(self, valueNode, fieldInfo.fieldType, slotSize, dataPrefix, b);
1619
    }
1620
}
1621
1622
/// Build data values for a constant union variant value from payload fields/args.
1623
fn lowerConstUnionVariantInto(
1624
    self: *mut Lowerer,
1625
    node: *ast::Node,
1626
    variantSym: *mut resolver::Symbol,
1627
    ty: resolver::Type,
1628
    payloadArgs: *mut [*ast::Node],
1629
    dataPrefix: *[u8],
1630
    b: *mut DataValueBuilder
1631
) throws (LowerError) {
1632
    let case resolver::SymbolData::Variant { type: payloadType, index, .. } = variantSym.data
1633
        else throw LowerError::UnexpectedNodeValue(node);
1634
1635
    let unionInfo = unionInfoFromType(ty) else {
1636
        throw LowerError::MissingMetadata;
1637
    };
1638
    let unionLayout = resolver::getTypeLayout(ty);
1639
    let payloadSlotSize = unionLayout.size - unionInfo.valOffset;
1640
1641
    // Tag byte.
1642
    dataBuilderPush(b, il::DataValue {
1643
        item: il::DataItem::Val {
1644
            typ: il::Type::W8,
1645
            val: index as i64
1646
        },
1647
        count: 1
1648
    });
1649
    // Padding between tag and payload.
1650
    if unionInfo.valOffset > 1 {
1651
        dataBuilderPush(b, il::DataValue {
1652
            item: il::DataItem::Undef,
1653
            count: unionInfo.valOffset - 1
1654
        });
1655
    }
1656
    if payloadType == resolver::Type::Void {
1657
        if payloadSlotSize > 0 {
1658
            dataBuilderPush(b, il::DataValue {
1659
                item: il::DataItem::Undef,
1660
                count: payloadSlotSize
1661
            });
1662
        }
1663
        return;
1664
    }
1665
1666
    let case resolver::Type::Nominal(resolver::NominalType::Record(payloadRec)) = payloadType else {
1667
        throw LowerError::ExpectedRecord;
1668
    };
1669
    let payloadLayout = payloadRec.layout;
1670
    try lowerConstRecordCtorInto(self, payloadArgs, payloadRec, dataPrefix, b);
1671
1672
    // Unused bytes in the union payload slot for smaller variants.
1673
    if payloadSlotSize > payloadLayout.size {
1674
        dataBuilderPush(b, il::DataValue {
1675
            item: il::DataItem::Undef,
1676
            count: payloadSlotSize - payloadLayout.size
1677
        });
1678
    }
1679
}
1680
1681
/// Find an existing string data entry with matching content.
1682
// TODO: Optimize with hash table or remove?
1683
fn findStringData(self: *Lowerer, s: *[u8]) -> ?*[u8] {
1684
    for d in self.data {
1685
        if d.values.len == 1 {
1686
            if let case il::DataItem::Str(existing) = d.values[0].item {
1687
                if mem::eq(existing, s) {
1688
                    return d.name;
1689
                }
1690
            }
1691
        }
1692
    }
1693
    return nil;
1694
}
1695
1696
/// Compose a segmented symbol name from a list of path segments.
1697
/// Example: `["func", "nominal", "VALUE"]` -> `func$nominal$VALUE`.
1698
fn buildSegmentedName(
1699
    self: *mut Lowerer,
1700
    segments: *[*[u8]]
1701
) -> *[u8] throws (LowerError) {
1702
    assert segments.len > 0;
1703
1704
    let mut totalLen: u32 = 0;
1705
    for segment in segments {
1706
        set totalLen += segment.len;
1707
    }
1708
    if segments.len > 1 {
1709
        set totalLen += segments.len - 1;
1710
    }
1711
    let buf = try! alloc::allocSlice(self.arena, 1, 1, totalLen) as *mut [u8];
1712
    let mut pos: u32 = 0;
1713
1714
    for segment, i in segments {
1715
        set pos += try! mem::copy(&mut buf[pos..], segment);
1716
        if i + 1 <> segments.len {
1717
            set buf[pos] = '$';
1718
            set pos += 1;
1719
        }
1720
    }
1721
    assert pos == totalLen;
1722
1723
    return &buf[..totalLen];
1724
}
1725
1726
/// Generate a unique name for declaration-local backing data entries.
1727
fn nextDeclDataName(
1728
    self: *mut Lowerer,
1729
    prefix: *[u8],
1730
    count: u32,
1731
    namespace: *[u8]
1732
) -> *[u8] throws (LowerError) {
1733
    let mut digits: [u8; fmt::U32_STR_LEN] = undefined;
1734
    let suffix = fmt::formatU32(count, &mut digits[..]);
1735
    let segments: *mut [*[u8]] = &mut [prefix, namespace, suffix];
1736
1737
    return try buildSegmentedName(self, segments);
1738
}
1739
1740
/// Append a data entry using a function-local literal namespace (`prefix$literal$N`).
1741
fn pushDeclData(
1742
    self: *mut Lowerer,
1743
    size: u32,
1744
    alignment: u32,
1745
    readOnly: bool,
1746
    values: *[il::DataValue],
1747
    dataPrefix: *[u8]
1748
) -> *[u8] throws (LowerError) {
1749
    let name = try nextDeclDataName(self, dataPrefix, self.data.len, "literal");
1750
    self.data.append(il::Data {
1751
        name,
1752
        size,
1753
        alignment,
1754
        readOnly,
1755
        isZeroInit: not readOnly and dataValuesAreZeroInit(values),
1756
        values,
1757
    }, self.allocator);
1758
1759
    return name;
1760
}
1761
1762
/// Find or create read-only string data and return its symbol name.
1763
fn getOrCreateStringData(
1764
    self: *mut Lowerer,
1765
    s: *[u8],
1766
    dataPrefix: *[u8]
1767
) -> *[u8] throws (LowerError) {
1768
    if let existing = findStringData(self, s) {
1769
        return existing;
1770
    }
1771
    let values = try! alloc::allocSlice(
1772
        self.arena, @sizeOf(il::DataValue), @alignOf(il::DataValue), 1
1773
    ) as *mut [il::DataValue];
1774
1775
    set values[0] = il::DataValue {
1776
        item: il::DataItem::Str(s),
1777
        count: 1
1778
    };
1779
    return try pushDeclData(self, s.len, 1, true, &values[..1], dataPrefix);
1780
}
1781
1782
/// Compare two data items for structural equality.
1783
/// Unlike raw byte comparison, this correctly ignores padding bytes in unions.
1784
fn dataItemEq(a: il::DataItem, b: il::DataItem) -> bool {
1785
    match a {
1786
        case il::DataItem::Val { typ: aTyp, val: aVal } =>
1787
            if let case il::DataItem::Val { typ: bTyp, val: bVal } = b {
1788
                return aTyp == bTyp and aVal == bVal;
1789
            } else {
1790
                return false;
1791
            },
1792
        case il::DataItem::Sym(aPtr) =>
1793
            if let case il::DataItem::Sym(bPtr) = b {
1794
                return mem::eq(aPtr, bPtr);
1795
            } else {
1796
                return false;
1797
            },
1798
        case il::DataItem::Fn(aName) =>
1799
            if let case il::DataItem::Fn(bName) = b {
1800
                return mem::eq(aName, bName);
1801
            } else {
1802
                return false;
1803
            },
1804
        case il::DataItem::Str(aStr) =>
1805
            if let case il::DataItem::Str(bStr) = b {
1806
                return mem::eq(aStr, bStr);
1807
            } else {
1808
                return false;
1809
            },
1810
        case il::DataItem::Undef =>
1811
            if let case il::DataItem::Undef = b {
1812
                return true;
1813
            } else {
1814
                return false;
1815
            },
1816
    }
1817
}
1818
1819
/// Compare two data value slices for structural equality.
1820
fn dataValuesEq(a: *[il::DataValue], b: *[il::DataValue]) -> bool {
1821
    if a.len <> b.len {
1822
        return false;
1823
    }
1824
    for i in 0..a.len {
1825
        if a[i].count <> b[i].count {
1826
            return false;
1827
        }
1828
        if not dataItemEq(a[i].item, b[i].item) {
1829
            return false;
1830
        }
1831
    }
1832
    return true;
1833
}
1834
1835
/// Find an existing read-only slice data entry with matching values.
1836
// TODO: Optimize with hash table or remove?
1837
fn findSliceData(self: *Lowerer, values: *[il::DataValue], alignment: u32) -> ?*[u8] {
1838
    for d in self.data {
1839
        if d.alignment == alignment and d.readOnly and dataValuesEq(d.values, values) {
1840
            return d.name;
1841
        }
1842
    }
1843
    return nil;
1844
}
1845
1846
/// Find existing constant data entry with matching content.
1847
/// Handles both string data and slice data.
1848
fn findConstData(self: *Lowerer, values: *[il::DataValue], alignment: u32) -> ?*[u8] {
1849
    // Fast path for strings.
1850
    if values.len == 1 and alignment == 1 {
1851
        if let case il::DataItem::Str(s) = values[0].item {
1852
            return findStringData(self, s);
1853
        }
1854
    }
1855
    // General case: byte comparison of data values.
1856
    return findSliceData(self, values, alignment);
1857
}
1858
1859
/// Lower constant data to a slice value.
1860
/// Creates or reuses a data section entry, then builds a slice header on the stack.
1861
fn lowerConstDataAsSlice(
1862
    self: *mut FnLowerer,
1863
    values: *[il::DataValue],
1864
    alignment: u32,
1865
    readOnly: bool,
1866
    elemTy: *resolver::Type,
1867
    mutable: bool,
1868
    length: u32
1869
) -> il::Val throws (LowerError) {
1870
    let elemLayout = resolver::getTypeLayout(*elemTy);
1871
    let size = elemLayout.size * length;
1872
    let mut dataName: *[u8] = undefined;
1873
    if readOnly {
1874
        if let found = findConstData(self.low, values, alignment) {
1875
            set dataName = found;
1876
        } else {
1877
            set dataName = try nextDataName(self);
1878
            self.low.data.append(il::Data {
1879
                name: dataName,
1880
                size,
1881
                alignment,
1882
                readOnly,
1883
                isZeroInit: false,
1884
                values,
1885
            }, self.low.allocator);
1886
        }
1887
    } else {
1888
        set dataName = try nextDataName(self);
1889
        self.low.data.append(il::Data {
1890
            name: dataName,
1891
            size,
1892
            alignment,
1893
            readOnly,
1894
            isZeroInit: dataValuesAreZeroInit(values),
1895
            values,
1896
        }, self.low.allocator);
1897
    }
1898
1899
    // Get data address.
1900
    let ptrReg = nextReg(self);
1901
    emit(self, il::Instr::Copy { dst: ptrReg, val: il::Val::DataSym(dataName) });
1902
1903
    return try buildSliceValue(
1904
        self, elemTy, mutable, il::Val::Reg(ptrReg), il::Val::Imm(length as i64), il::Val::Imm(length as i64)
1905
    );
1906
}
1907
1908
/// Generate a unique data name for inline literals, eg. `fnName$literal$N`.
1909
fn nextDataName(self: *mut FnLowerer) -> *[u8] throws (LowerError) {
1910
    let counter = self.dataCounter;
1911
    set self.dataCounter += 1;
1912
    return try nextDeclDataName(self.low, self.fnName, counter, "literal");
1913
}
1914
1915
/// Assign a unique function-local data symbol name.
1916
fn registerLocalDataDeclName(self: *mut FnLowerer, node: *ast::Node) throws (LowerError) {
1917
    let sym = resolver::nodeData(self.low.resolver, node).sym
1918
        else throw LowerError::MissingSymbol(node);
1919
1920
    let prefix = self.fnName;
1921
    let segments: *mut [*[u8]] = &mut [prefix, "nominal", sym.name];
1922
    let name = try buildSegmentedName(self.low, segments);
1923
1924
    set sym.name = name;
1925
}
1926
1927
/// Get the next available SSA register.
1928
fn nextReg(self: *mut FnLowerer) -> il::Reg {
1929
    let reg = il::Reg { n: self.regCounter };
1930
    set self.regCounter += 1;
1931
    return reg;
1932
}
1933
1934
/// Look up the resolved type of an AST node, or throw `MissingType`.
1935
fn typeOf(self: *mut FnLowerer, node: *ast::Node) -> resolver::Type throws (LowerError) {
1936
    let ty = resolver::typeFor(self.low.resolver, node)
1937
        else throw LowerError::MissingType(node);
1938
    return ty;
1939
}
1940
1941
/// Look up the symbol for an AST node, or throw `MissingSymbol`.
1942
fn symOf(self: *mut FnLowerer, node: *ast::Node) -> *mut resolver::Symbol throws (LowerError) {
1943
    let sym = resolver::nodeData(self.low.resolver, node).sym
1944
        else throw LowerError::MissingSymbol(node);
1945
    return sym;
1946
}
1947
1948
/// Remove the last block parameter and its associated variable.
1949
/// Used when detecting a trivial phi that can be eliminated.
1950
fn removeLastBlockParam(self: *mut FnLowerer, block: BlockId) {
1951
    let blk = getBlockMut(self, block);
1952
    if blk.params.len > 0 {
1953
        // TODO: Use `pop`?
1954
        set blk.params = @sliceOf(blk.params.ptr, blk.params.len - 1, blk.params.cap);
1955
    }
1956
    if blk.paramVars.len > 0 {
1957
        // TODO: Use `pop`?
1958
        set blk.paramVars = @sliceOf(blk.paramVars.ptr, blk.paramVars.len - 1, blk.paramVars.cap);
1959
    }
1960
}
1961
1962
/// Rewrite cached SSA values for a variable across all blocks, and also
1963
/// rewrite any terminator arguments that reference the provisional register.
1964
/// The latter is necessary because recursive SSA resolution may have already
1965
/// patched terminator arguments with the provisional value before it was
1966
/// found to be trivial.
1967
fn rewriteCachedVarValue(self: *mut FnLowerer, v: Var, from: il::Val, to: il::Val) {
1968
    for i in 0..self.blockData.len {
1969
        let blk = getBlockMut(self, BlockId(i));
1970
        if blk.vars[*v] == from {
1971
            set blk.vars[*v] = to;
1972
        }
1973
        if blk.instrs.len > 0 {
1974
            let ix = blk.instrs.len - 1;
1975
            match &mut blk.instrs[ix] {
1976
                case il::Instr::Jmp { args, .. } =>
1977
                    rewriteValInSlice(*args, from, to),
1978
                case il::Instr::Br { thenArgs, elseArgs, .. } => {
1979
                    rewriteValInSlice(*thenArgs, from, to);
1980
                    rewriteValInSlice(*elseArgs, from, to);
1981
                }
1982
                case il::Instr::Switch { defaultArgs, cases, .. } => {
1983
                    rewriteValInSlice(*defaultArgs, from, to);
1984
                    for j in 0..cases.len {
1985
                        rewriteValInSlice(cases[j].args, from, to);
1986
                    }
1987
                }
1988
                else => {}
1989
            }
1990
        }
1991
    }
1992
}
1993
1994
/// Replace all occurrences of `from` with `to` in an args slice.
1995
fn rewriteValInSlice(args: *mut [il::Val], from: il::Val, to: il::Val) {
1996
    for i in 0..args.len {
1997
        if args[i] == from {
1998
            set args[i] = to;
1999
        }
2000
    }
2001
}
2002
2003
////////////////////////////
2004
// Basic Block Management //
2005
////////////////////////////
2006
2007
// Basic blocks are the fundamental unit of the CFG. Each block contains a
2008
// sequence of instructions ending in a terminator (jump, branch, return).
2009
//
2010
// The block management API supports forward references -- you can create a
2011
// block before switching to it and emitting instructions.
2012
// This is essential for control flow where we need to reference target blocks
2013
// before we've built them (e.g., the "else" block when building "then").
2014
//
2015
// Sealing is a key concept for SSA construction: a block is sealed once all
2016
// its predecessor edges are known. Before sealing, we can't resolve variable
2017
// uses that require looking up values from predecessors.
2018
2019
/// Create a new basic block with the given label base.
2020
///
2021
/// The block is initially unsealed (predecessors may be added later) and empty.
2022
/// Returns a [`BlockId`] that can be used for jumps and branches. The block must
2023
/// be switched to via [`switchToBlock`] before instructions can be emitted.
2024
fn createBlock(self: *mut FnLowerer, labelBase: *[u8]) -> BlockId throws (LowerError) {
2025
    let label = try nextLabel(self, labelBase);
2026
    let id = BlockId(self.blockData.len);
2027
    let varCount = self.fnType.localCount;
2028
    let vars = try! alloc::allocSlice(self.low.fnArena, @sizeOf(?il::Val), @alignOf(?il::Val), varCount) as *mut [?il::Val];
2029
2030
    for i in 0..varCount {
2031
        set vars[i] = nil;
2032
    }
2033
    self.blockData.append(BlockData {
2034
        label,
2035
        params: &mut [],
2036
        paramVars: &mut [],
2037
        instrs: &mut [],
2038
        locs: &mut [],
2039
        preds: &mut [],
2040
        vars,
2041
        sealState: Sealed::No { incompleteVars: &mut [] },
2042
        loopDepth: self.loopDepth,
2043
    }, self.allocator);
2044
2045
    return id;
2046
}
2047
2048
/// Create a new block with a single parameter.
2049
fn createBlockWithParam(
2050
    self: *mut FnLowerer,
2051
    labelBase: *[u8],
2052
    param: il::Param
2053
) -> BlockId throws (LowerError) {
2054
    let block = try createBlock(self, labelBase);
2055
    let blk = getBlockMut(self, block);
2056
    blk.params.append(param, self.allocator);
2057
2058
    return block;
2059
}
2060
2061
/// Switch to building a different block.
2062
/// All subsequent `emit` calls will add instructions to this block.
2063
fn switchToBlock(self: *mut FnLowerer, block: BlockId) {
2064
    set self.currentBlock = block;
2065
}
2066
2067
/// Seal a block, indicating all predecessor edges are now known.
2068
///
2069
/// Sealing enables SSA construction to resolve variable uses by looking up
2070
/// values from predecessors and inserting block parameters as needed. It
2071
/// does not prevent instructions from being added to the block.
2072
fn sealBlock(self: *mut FnLowerer, block: BlockId) throws (LowerError) {
2073
    let blk = getBlockMut(self, block);
2074
    let case Sealed::No { incompleteVars } = blk.sealState else {
2075
        return; // Already sealed.
2076
    };
2077
    set blk.sealState = Sealed::Yes;
2078
2079
    // Complete all incomplete block parameters.
2080
    for varId in incompleteVars {
2081
        try resolveBlockArgs(self, block, Var(varId));
2082
    }
2083
}
2084
2085
/// Seal a block and switch to it.
2086
fn switchToAndSeal(self: *mut FnLowerer, block: BlockId) throws (LowerError) {
2087
    try sealBlock(self, block);
2088
    switchToBlock(self, block);
2089
}
2090
2091
/// Get block data by block id.
2092
fn getBlock(self: *FnLowerer, block: BlockId) -> *BlockData {
2093
    return &self.blockData[*block];
2094
}
2095
2096
/// Get mutable block data by block id.
2097
fn getBlockMut(self: *mut FnLowerer, block: BlockId) -> *mut BlockData {
2098
    return &mut self.blockData[*block];
2099
}
2100
2101
/// Get the current block being built.
2102
fn currentBlock(self: *FnLowerer) -> BlockId {
2103
    let block = self.currentBlock else {
2104
        panic "currentBlock: no current block";
2105
    };
2106
    return block;
2107
}
2108
2109
//////////////////////////
2110
// Instruction Emission //
2111
//////////////////////////
2112
2113
/// Emit an instruction to the current block.
2114
fn emit(self: *mut FnLowerer, instr: il::Instr) {
2115
    let blk = self.currentBlock else panic;
2116
    let mut block = getBlockMut(self, blk);
2117
2118
    // Track whether this function is a leaf.
2119
    if self.isLeaf {
2120
        match instr {
2121
            case il::Instr::Call { .. },
2122
                 il::Instr::Ecall { .. } => set self.isLeaf = false,
2123
            else => {},
2124
        }
2125
    }
2126
    // Record source location alongside instruction when enabled.
2127
    if self.low.options.debug {
2128
        block.locs.append(self.srcLoc, self.allocator);
2129
    }
2130
    block.instrs.append(instr, self.allocator);
2131
}
2132
2133
/// Emit an unconditional jump to `target`.
2134
fn emitJmp(self: *mut FnLowerer, target: BlockId) throws (LowerError) {
2135
    emit(self, il::Instr::Jmp { target: *target, args: &mut [] });
2136
    addPredecessor(self, target, currentBlock(self));
2137
}
2138
2139
/// Emit an unconditional jump to `target` with a single argument.
2140
fn emitJmpWithArg(self: *mut FnLowerer, target: BlockId, arg: il::Val) throws (LowerError) {
2141
    let args = try allocVal(self, arg);
2142
    emit(self, il::Instr::Jmp { target: *target, args });
2143
    addPredecessor(self, target, currentBlock(self));
2144
}
2145
2146
/// Emit an unconditional jump to `target` and switch to it.
2147
fn switchAndJumpTo(self: *mut FnLowerer, target: BlockId) throws (LowerError) {
2148
    try emitJmp(self, target);
2149
    switchToBlock(self, target);
2150
}
2151
2152
/// Emit a conditional branch based on `cond`.
2153
fn emitBr(self: *mut FnLowerer, cond: il::Reg, thenBlock: BlockId, elseBlock: BlockId) throws (LowerError) {
2154
    assert thenBlock <> elseBlock;
2155
    emit(self, il::Instr::Br {
2156
        op: il::CmpOp::Ne,
2157
        typ: il::Type::W32,
2158
        a: il::Val::Reg(cond),
2159
        b: il::Val::Imm(0),
2160
        thenTarget: *thenBlock,
2161
        thenArgs: &mut [],
2162
        elseTarget: *elseBlock,
2163
        elseArgs: &mut [],
2164
    });
2165
    addPredecessor(self, thenBlock, currentBlock(self));
2166
    addPredecessor(self, elseBlock, currentBlock(self));
2167
}
2168
2169
/// Emit a compare-and-branch instruction with the given comparison op.
2170
fn emitBrCmp(
2171
    self: *mut FnLowerer,
2172
    op: il::CmpOp,
2173
    typ: il::Type,
2174
    a: il::Val,
2175
    b: il::Val,
2176
    thenBlock: BlockId,
2177
    elseBlock: BlockId
2178
) throws (LowerError) {
2179
    assert thenBlock <> elseBlock;
2180
    emit(self, il::Instr::Br {
2181
        op, typ, a, b,
2182
        thenTarget: *thenBlock, thenArgs: &mut [],
2183
        elseTarget: *elseBlock, elseArgs: &mut [],
2184
    });
2185
    addPredecessor(self, thenBlock, currentBlock(self));
2186
    addPredecessor(self, elseBlock, currentBlock(self));
2187
}
2188
2189
/// Emit a guard that traps with `ebreak` when a comparison is false.
2190
fn emitTrapUnlessCmp(
2191
    self: *mut FnLowerer,
2192
    op: il::CmpOp,
2193
    typ: il::Type,
2194
    a: il::Val,
2195
    b: il::Val
2196
) throws (LowerError) {
2197
    let passBlock = try createBlock(self, "guard#pass");
2198
    let trapBlock = try createBlock(self, "guard#trap");
2199
2200
    try emitBrCmp(self, op, typ, a, b, passBlock, trapBlock);
2201
    try switchToAndSeal(self, trapBlock);
2202
2203
    emit(self, il::Instr::Ebreak);
2204
    emit(self, il::Instr::Unreachable);
2205
2206
    try switchToAndSeal(self, passBlock);
2207
}
2208
2209
/// Return whether two IL values are known `u32` immediates satisfying `a <= b`.
2210
fn isLtEq(a: il::Val, b: il::Val) -> bool {
2211
    if a == b {
2212
        return true;
2213
    }
2214
    if a == il::Val::Imm(0) {
2215
        return true;
2216
    }
2217
    let case il::Val::Imm(aa) = a else {
2218
        return false;
2219
    };
2220
    let case il::Val::Imm(bb) = b else {
2221
        return false;
2222
    };
2223
    if aa < 0 or bb < 0 {
2224
        return false;
2225
    }
2226
    return aa <= bb;
2227
}
2228
2229
/// Emit an `ebreak` when `a < b` holds.
2230
fn emitTrapIfLt(
2231
    self: *mut FnLowerer,
2232
    typ: il::Type,
2233
    a: il::Val,
2234
    b: il::Val
2235
) throws (LowerError) {
2236
    let trapBlock = try createBlock(self, "guard#trap");
2237
    let passBlock = try createBlock(self, "guard#pass");
2238
2239
    try emitBrCmp(self, il::CmpOp::Ult, typ, a, b, trapBlock, passBlock);
2240
    try switchToAndSeal(self, trapBlock);
2241
2242
    emit(self, il::Instr::Ebreak);
2243
    emit(self, il::Instr::Unreachable);
2244
2245
    try switchToAndSeal(self, passBlock);
2246
}
2247
2248
/// Emit a conditional branch. Uses fused compare-and-branch for simple scalar
2249
/// comparisons, falls back to separate comparison plus branch otherwise.
2250
fn emitCondBranch(
2251
    self: *mut FnLowerer,
2252
    cond: *ast::Node,
2253
    thenBlock: BlockId,
2254
    elseBlock: BlockId
2255
) throws (LowerError) {
2256
    // Try fused compare-and-branch for simple scalar comparisons.
2257
    if let case ast::NodeValue::BinOp(binop) = cond.value {
2258
        let leftTy = try typeOf(self, binop.left);
2259
        let rightTy = try typeOf(self, binop.right);
2260
        if not isAggregateType(leftTy) and not isAggregateType(rightTy) {
2261
            let operandTy = scalarComparisonType(leftTy, rightTy);
2262
            let unsigned = isUnsignedType(operandTy);
2263
            if let op = cmpOpFrom(binop.op, unsigned) {
2264
                let a = try lowerExpr(self, binop.left);
2265
                let b = try lowerExpr(self, binop.right);
2266
                let typ = ilType(self.low, operandTy);
2267
2268
                // Swap operands if needed.
2269
                match binop.op {
2270
                    case ast::BinaryOp::Gt => // `a > b` = `b < a`
2271
                        try emitBrCmp(self, op, typ, b, a, thenBlock, elseBlock),
2272
                    case ast::BinaryOp::Lte => // `a <= b` = `!(b < a)`
2273
                        try emitBrCmp(self, op, typ, b, a, elseBlock, thenBlock),
2274
                    case ast::BinaryOp::Gte => // `a >= b` = `!(a < b)`
2275
                        try emitBrCmp(self, op, typ, a, b, elseBlock, thenBlock),
2276
                    else =>
2277
                        try emitBrCmp(self, op, typ, a, b, thenBlock, elseBlock),
2278
                }
2279
                return;
2280
            }
2281
        }
2282
    }
2283
    // Fallback: evaluate condition and emit boolean branch.
2284
    let condVal = try lowerExpr(self, cond);
2285
    let condReg = emitValToReg(self, condVal);
2286
2287
    try emitBr(self, condReg, thenBlock, elseBlock);
2288
}
2289
2290
/// Emit a 32-bit store instruction at the given offset.
2291
fn emitStoreW32At(self: *mut FnLowerer, src: il::Val, dst: il::Reg, offset: i32) {
2292
    emit(self, il::Instr::Store { typ: il::Type::W32, src, dst, offset });
2293
}
2294
2295
/// Emit a 32-bit load instruction at the given offset.
2296
fn emitLoadW32At(self: *mut FnLowerer, dst: il::Reg, src: il::Reg, offset: i32) {
2297
    emit(self, il::Instr::Load { typ: il::Type::W32, dst, src, offset });
2298
}
2299
2300
/// Emit an 8-bit store instruction at the given offset.
2301
fn emitStoreW8At(self: *mut FnLowerer, src: il::Val, dst: il::Reg, offset: i32) {
2302
    emit(self, il::Instr::Store { typ: il::Type::W8, src, dst, offset });
2303
}
2304
2305
/// Emit an 8-bit load instruction at the given offset.
2306
fn emitLoadW8At(self: *mut FnLowerer, dst: il::Reg, src: il::Reg, offset: i32) {
2307
    emit(self, il::Instr::Load { typ: il::Type::W8, dst, src, offset });
2308
}
2309
2310
/// Emit a 64-bit store instruction at the given offset.
2311
fn emitStoreW64At(self: *mut FnLowerer, src: il::Val, dst: il::Reg, offset: i32) {
2312
    emit(self, il::Instr::Store { typ: il::Type::W64, src, dst, offset });
2313
}
2314
2315
/// Emit a 64-bit load instruction at the given offset.
2316
fn emitLoadW64At(self: *mut FnLowerer, dst: il::Reg, src: il::Reg, offset: i32) {
2317
    emit(self, il::Instr::Load { typ: il::Type::W64, dst, src, offset });
2318
}
2319
2320
/// Load a tag from memory at `src` plus `offset` with the given IL type.
2321
fn loadTag(self: *mut FnLowerer, src: il::Reg, offset: i32, tagType: il::Type) -> il::Val {
2322
    let dst = nextReg(self);
2323
    emit(self, il::Instr::Load { typ: tagType, dst, src, offset });
2324
    return il::Val::Reg(dst);
2325
}
2326
2327
/// Load the data pointer from a slice value.
2328
fn loadSlicePtr(self: *mut FnLowerer, sliceReg: il::Reg) -> il::Reg {
2329
    let ptrReg = nextReg(self);
2330
    emitLoadW64At(self, ptrReg, sliceReg, SLICE_PTR_OFFSET);
2331
    return ptrReg;
2332
}
2333
2334
/// Load the length from a slice value.
2335
fn loadSliceLen(self: *mut FnLowerer, sliceReg: il::Reg) -> il::Val {
2336
    let lenReg = nextReg(self);
2337
    emitLoadW32At(self, lenReg, sliceReg, SLICE_LEN_OFFSET);
2338
    return il::Val::Reg(lenReg);
2339
}
2340
2341
/// Load the capacity from a slice value.
2342
fn loadSliceCap(self: *mut FnLowerer, sliceReg: il::Reg) -> il::Val {
2343
    let capReg = nextReg(self);
2344
    emitLoadW32At(self, capReg, sliceReg, SLICE_CAP_OFFSET);
2345
    return il::Val::Reg(capReg);
2346
}
2347
2348
/// Emit a load instruction for a scalar value at `src` plus `offset`.
2349
/// For reading values that may be aggregates, use `emitRead` instead.
2350
fn emitLoad(self: *mut FnLowerer, src: il::Reg, offset: i32, typ: resolver::Type) -> il::Val {
2351
    let dst = nextReg(self);
2352
    let ilTyp = ilType(self.low, typ);
2353
2354
    if isSignedType(typ) {
2355
        emit(self, il::Instr::Sload { typ: ilTyp, dst, src, offset });
2356
    } else {
2357
        emit(self, il::Instr::Load { typ: ilTyp, dst, src, offset });
2358
    }
2359
    return il::Val::Reg(dst);
2360
}
2361
2362
/// Read a value from memory at `src` plus `offset`. Aggregates are represented
2363
/// as pointers, so we return the address directly. Scalars are loaded via [`emitLoad`].
2364
fn emitRead(self: *mut FnLowerer, src: il::Reg, offset: i32, typ: resolver::Type) -> il::Val {
2365
    if isAggregateType(typ) {
2366
        let ptr = emitPtrOffset(self, src, offset);
2367
        return il::Val::Reg(ptr);
2368
    }
2369
    return emitLoad(self, src, offset, typ);
2370
}
2371
2372
/// Emit a copy instruction that loads a data symbol's address into a register.
2373
fn emitDataAddr(self: *mut FnLowerer, sym: *resolver::Symbol) -> il::Reg {
2374
    let dst = nextReg(self);
2375
    let modId = resolver::moduleIdForSymbol(self.low.resolver, sym);
2376
    let qualName = qualifyName(self.low, modId, sym.name);
2377
2378
    emit(self, il::Instr::Copy { dst, val: il::Val::DataSym(qualName) });
2379
2380
    return dst;
2381
}
2382
2383
/// Emit a copy instruction that loads a function's address into a register.
2384
fn emitFnAddr(self: *mut FnLowerer, sym: *resolver::Symbol) -> il::Reg {
2385
    let dst = nextReg(self);
2386
    let modId = resolver::moduleIdForSymbol(self.low.resolver, sym);
2387
    let qualName = qualifyName(self.low, modId, sym.name);
2388
2389
    emit(self, il::Instr::Copy { dst, val: il::Val::FnAddr(qualName) });
2390
2391
    return dst;
2392
}
2393
2394
/// Emit pattern tests for a single pattern.
2395
fn emitPatternMatch(
2396
    self: *mut FnLowerer,
2397
    subject: *MatchSubject,
2398
    pattern: *ast::Node,
2399
    matchBlock: BlockId,
2400
    fallthrough: BlockId
2401
) throws (LowerError) {
2402
    // Wildcards always match; array patterns are tested element-by-element
2403
    // during binding, so they also unconditionally enter the match block.
2404
    if isWildcardPattern(pattern) {
2405
        try emitJmp(self, matchBlock);
2406
        return;
2407
    }
2408
    if let case ast::NodeValue::ArrayLit(_) = pattern.value {
2409
        try emitJmp(self, matchBlock);
2410
        return;
2411
    }
2412
    let isNil = pattern.value == ast::NodeValue::Nil;
2413
2414
    match subject.kind {
2415
        case MatchSubjectKind::OptionalPtr if isNil => {
2416
            // Null pointer optimization: branch on the data pointer being null.
2417
            let nilReg = try optionalNilReg(self, subject.val, subject.type);
2418
            try emitBrCmp(self, il::CmpOp::Eq, il::Type::W64, il::Val::Reg(nilReg), il::Val::Imm(0), matchBlock, fallthrough);
2419
        }
2420
        case MatchSubjectKind::OptionalAggregate => {
2421
            let base = emitValToReg(self, subject.val);
2422
2423
            if isNil { // Optional aggregate: `nil` means tag is zero.
2424
                let tagReg = tvalTagReg(self, base);
2425
                try emitBr(self, tagReg, fallthrough, matchBlock);
2426
            } else {
2427
                // `lowerExpr` applies the resolver's optional-lift coercion,
2428
                // materializing the tagged representation for value patterns.
2429
                let pattVal = try lowerExpr(self, pattern);
2430
                let pattReg = emitValToReg(self, pattVal);
2431
                let eq = try lowerOptionalEq(self, subject.bindType, base, pattReg, 0);
2432
                let eqReg = emitValToReg(self, eq);
2433
2434
                try emitBr(self, eqReg, matchBlock, fallthrough);
2435
            }
2436
        }
2437
        case MatchSubjectKind::Union(unionInfo) => {
2438
            assert not isNil;
2439
2440
            let case resolver::NodeExtra::UnionVariant { tag: variantTag, .. } =
2441
                resolver::nodeData(self.low.resolver, pattern).extra
2442
            else {
2443
                throw LowerError::ExpectedVariant;
2444
            };
2445
            // Void unions are passed by value (the tag itself).
2446
            // Non-void unions are passed by reference (need to load tag).
2447
            // When matching by reference, always load from the pointer.
2448
            if unionInfo.isAllVoid {
2449
                let mut tagVal = subject.val;
2450
                match subject.by {
2451
                    case resolver::MatchBy::Ref, resolver::MatchBy::MutRef => {
2452
                        let base = emitValToReg(self, subject.val);
2453
                        set tagVal = loadTag(self, base, 0, il::Type::W8);
2454
                    }
2455
                    case resolver::MatchBy::Value => {}
2456
                }
2457
                try emitBrCmp(self, il::CmpOp::Eq, il::Type::W8, tagVal, il::Val::Imm(variantTag as i64), matchBlock, fallthrough);
2458
            } else {
2459
                let base = emitValToReg(self, subject.val);
2460
                let tagReg = tvalTagReg(self, base);
2461
2462
                try emitBrCmp(self, il::CmpOp::Eq, il::Type::W8, il::Val::Reg(tagReg), il::Val::Imm(variantTag as i64), matchBlock, fallthrough);
2463
            }
2464
        }
2465
        else => { // Value comparison.
2466
            assert not isNil;
2467
            let pattVal = try lowerExpr(self, pattern);
2468
            if isAggregateType(subject.type) {
2469
                // Aggregate types need structural comparison rather than
2470
                // scalar compare.
2471
                let subjectReg = emitValToReg(self, subject.val);
2472
                let pattReg = emitValToReg(self, pattVal);
2473
                let eq = try lowerAggregateEq(self, subject.type, subjectReg, pattReg, 0);
2474
                let eqReg = emitValToReg(self, eq);
2475
2476
                try emitBr(self, eqReg, matchBlock, fallthrough);
2477
            } else {
2478
                try emitBrCmp(self, il::CmpOp::Eq, subject.ilType, subject.val, pattVal, matchBlock, fallthrough);
2479
            }
2480
        }
2481
    }
2482
}
2483
2484
/// Emit branches for multiple patterns. The first pattern that matches
2485
/// causes a jump to the match block. If no patterns match, we jump to the
2486
/// fallthrough block.
2487
fn emitPatternMatches(
2488
    self: *mut FnLowerer,
2489
    subject: *MatchSubject,
2490
    patterns: *mut [*ast::Node],
2491
    matchBlock: BlockId,
2492
    fallthrough: BlockId
2493
) throws (LowerError) {
2494
    assert patterns.len > 0;
2495
2496
    for i in 0..(patterns.len - 1) {
2497
        let pattern = patterns[i];
2498
        let nextArm = try createBlock(self, "arm");
2499
        try emitPatternMatch(self, subject, pattern, matchBlock, nextArm);
2500
2501
        // Seal the intermediate arm block: all predecessor edges are known
2502
        // This ensures SSA construction can resolve variable uses through
2503
        // single-predecessor optimization instead of creating unresolved block
2504
        // parameters.
2505
        try switchToAndSeal(self, nextArm);
2506
    }
2507
    // Handle last pattern: go to fallthrough block on failure.
2508
    let last = patterns[patterns.len - 1];
2509
    try emitPatternMatch(self, subject, last, matchBlock, fallthrough);
2510
}
2511
2512
/// Emit a match binding pattern.
2513
/// Binding patterns always match for regular values, but for optionals they
2514
/// check for the presence of a value. Jumps to `valuePresent` on success,
2515
/// `valueAbsent` on failure.
2516
fn emitBindingTest(
2517
    self: *mut FnLowerer,
2518
    subject: *MatchSubject,
2519
    valuePresent: BlockId,
2520
    valueAbsent: BlockId
2521
) throws (LowerError) {
2522
    match subject.kind {
2523
        case MatchSubjectKind::OptionalPtr, MatchSubjectKind::OptionalAggregate => {
2524
            let nilReg = try optionalNilReg(self, subject.val, subject.type);
2525
            try emitBr(self, nilReg, valuePresent, valueAbsent);
2526
        }
2527
        else => {
2528
            // Regular values always match binding patterns unconditionally.
2529
            try emitJmp(self, valuePresent);
2530
        }
2531
    }
2532
}
2533
2534
/// Emit a jump to target if the current block hasn't terminated, then seal the target block.
2535
fn emitJmpAndSeal(self: *mut FnLowerer, target: BlockId) throws (LowerError) {
2536
    if not blockHasTerminator(self) {
2537
        try emitJmp(self, target);
2538
    }
2539
    try sealBlock(self, target);
2540
}
2541
2542
/// Check if the current block already has a terminator instruction.
2543
fn blockHasTerminator(self: *FnLowerer) -> bool {
2544
    let blk = getBlock(self, currentBlock(self));
2545
    if blk.instrs.len == 0 {
2546
        return false;
2547
    }
2548
    match blk.instrs[blk.instrs.len - 1] {
2549
        case il::Instr::Ret { .. },
2550
             il::Instr::Jmp { .. },
2551
             il::Instr::Br { .. },
2552
             il::Instr::Switch { .. },
2553
             il::Instr::Unreachable =>
2554
            return true,
2555
        else =>
2556
            return false,
2557
    }
2558
}
2559
2560
/// Emit a jump to merge block if the current block hasn't terminated.
2561
///
2562
/// This is used after lowering branches of an if-else, for example. If the
2563
/// branch diverges, the block already has a terminator and no jump is needed.
2564
///
2565
/// This handles cases like:
2566
///
2567
///     if cond {
2568
///         return 1;   // @then diverges, no jump to merge.
2569
///     } else {
2570
///         return 0;   // @else diverges, no jump to merge.
2571
///     }
2572
///
2573
/// In the above example, the merge block stays `nil`, and no code is generated
2574
/// after the `if`. The merge block is created on first use.
2575
fn emitMergeIfUnterminated(self: *mut FnLowerer, mergeBlock: *mut ?BlockId) throws (LowerError) {
2576
    if not blockHasTerminator(self) {
2577
        if *mergeBlock == nil {
2578
            set *mergeBlock = try createBlock(self, "merge");
2579
        }
2580
        let target = *mergeBlock else { throw LowerError::MissingTarget; };
2581
        try emitJmp(self, target);
2582
    }
2583
}
2584
2585
//////////////////////////////////
2586
// Control Flow Edge Management //
2587
//////////////////////////////////
2588
2589
/// Add a predecessor edge from `pred` to `target`.
2590
/// Must be called before the target block is sealed. Duplicates are ignored.
2591
fn addPredecessor(self: *mut FnLowerer, target: BlockId, pred: BlockId) {
2592
    let blk = getBlockMut(self, target);
2593
    assert blk.sealState <> Sealed::Yes, "addPredecessor: adding predecessor to sealed block";
2594
    let preds = &mut blk.preds;
2595
    for i in 0..preds.len {
2596
        if preds[i] == *pred { // Avoid duplicate predecessor entries.
2597
            return;
2598
        }
2599
    }
2600
    preds.append(*pred, self.allocator);
2601
}
2602
2603
/// Finalize all blocks and return the block array.
2604
fn finalizeBlocks(self: *mut FnLowerer) -> *[il::Block] throws (LowerError) {
2605
    let blocks = try! alloc::allocSlice(
2606
        self.low.fnArena, @sizeOf(il::Block), @alignOf(il::Block), self.blockData.len
2607
    ) as *mut [il::Block];
2608
2609
    for i in 0..self.blockData.len {
2610
        let data = &self.blockData[i];
2611
2612
        set blocks[i] = il::Block {
2613
            label: data.label,
2614
            params: &data.params[..],
2615
            instrs: data.instrs,
2616
            locs: &data.locs[..],
2617
            preds: &data.preds[..],
2618
            loopDepth: data.loopDepth,
2619
        };
2620
    }
2621
    return &blocks[..self.blockData.len];
2622
}
2623
2624
/////////////////////
2625
// Loop Management //
2626
/////////////////////
2627
2628
/// Enter a loop context for break/continue handling.
2629
/// `continueBlock` is `nil` when the continue target is created lazily.
2630
fn enterLoop(self: *mut FnLowerer, breakBlock: BlockId, continueBlock: ?BlockId) {
2631
    assert self.loopDepth < self.loopStack.len, "enterLoop: loop depth overflow";
2632
    let slot = &mut self.loopStack[self.loopDepth];
2633
2634
    set slot.breakTarget = breakBlock;
2635
    set slot.continueTarget = continueBlock;
2636
    set self.loopDepth += 1;
2637
}
2638
2639
/// Exit the current loop context.
2640
fn exitLoop(self: *mut FnLowerer) {
2641
    assert self.loopDepth <> 0, "exitLoop: loopDepth is zero";
2642
    set self.loopDepth -= 1;
2643
}
2644
2645
/// Get the current loop context.
2646
fn currentLoop(self: *mut FnLowerer) -> ?*mut LoopCtx {
2647
    if self.loopDepth == 0 {
2648
        return nil;
2649
    }
2650
    return &mut self.loopStack[self.loopDepth - 1];
2651
}
2652
2653
/// Get or lazily create the continue target block for the current loop.
2654
fn getOrCreateContinueBlock(self: *mut FnLowerer) -> BlockId throws (LowerError) {
2655
    let ctx = currentLoop(self) else {
2656
        throw LowerError::OutsideOfLoop;
2657
    };
2658
    if let block = ctx.continueTarget {
2659
        return block;
2660
    }
2661
    let block = try createBlock(self, "step");
2662
    set ctx.continueTarget = block;
2663
    return block;
2664
}
2665
2666
/// Allocate a slice of values in the lowering arena.
2667
fn allocVals(self: *mut FnLowerer, len: u32) -> *mut [il::Val] throws (LowerError) {
2668
    return try! alloc::allocSlice(self.low.fnArena, @sizeOf(il::Val), @alignOf(il::Val), len) as *mut [il::Val];
2669
}
2670
2671
/// Allocate a single-value slice in the lowering arena.
2672
fn allocVal(self: *mut FnLowerer, val: il::Val) -> *mut [il::Val] throws (LowerError) {
2673
    let args = try allocVals(self, 1);
2674
    set args[0] = val;
2675
    return args;
2676
}
2677
2678
////////////////////////
2679
// SSA Var Management //
2680
////////////////////////
2681
2682
// This section implements SSA construction following "Simple and Efficient
2683
// Construction of Static Single Assignment Form" (Braun et al., 2013). The IL
2684
// uses block parameters (equivalent to phi nodes) that receive values via
2685
// terminator arguments. Block args are resolved eagerly at seal time via
2686
// [`resolveBlockArgs`], matching Braun's on-the-fly approach.
2687
//
2688
// In SSA form, each variable definition creates a unique value. When control
2689
// flow diverges and merges (like after an if-else), a variable might have
2690
// different definitions from different paths.
2691
//
2692
// # What "Value" means
2693
//
2694
// An [`il::Val`] is a compile-time representation of *where* a runtime value
2695
// lives, not the runtime value itself. Values can live in registers, as symbol
2696
// references, or as immediate values, ie. static constants.
2697
//
2698
// When we "find the value" of a variable, we're answering: "Which SSA register
2699
// (or constant) represents this variable at this program point?"
2700
//
2701
// Each source-level variable gets a `Var` handle on declaration. When a
2702
// variable is defined via [`defVar`], its SSA value is recorded in the current
2703
// block's variable mapping. When a variable is used with [`useVar`] or
2704
// [`useVarInBlock`], we either return the local definition or recursively look
2705
// up the value from predecessor blocks. When multiple predecessors define
2706
// different values for a given variable, we insert a block parameter
2707
// (equivalent to a phi node).
2708
//
2709
// The algorithm used by [`useVarInBlock`] handles three cases:
2710
//
2711
// 1. **Local definition exists**: If the variable was assigned in this block,
2712
//    return that value immediately (fast path).
2713
//
2714
// 2. **Sealed block with single predecessor**: If all incoming edges are known
2715
//    and there's exactly one predecessor, recurse to that predecessor. No merge
2716
//    is needed since there's only one path. The result is cached.
2717
//
2718
// 3. **Multiple predecessors**: Create a block parameter to receive the merged
2719
//    value. If the block is sealed, immediately look up each predecessor's value
2720
//    and patch their terminators via [`resolveBlockArgs`]. If unsealed, defer by
2721
//    recording the variable in `incompleteVars`; when [`sealBlock`] is called,
2722
//    all incomplete block params are resolved at that point.
2723
//
2724
// Consider this code:
2725
//
2726
//     let mut x = 1;
2727
//     if cond {
2728
//         x = 2;
2729
//     } else {
2730
//         x = f();   // Result in register %r.
2731
//     }
2732
//     print(x);      // Which value?
2733
//
2734
// The Control Flow Graph (CFG) looks like:
2735
//
2736
//         [entry]
2737
//           _|_
2738
//          /   \
2739
//     [then]   [else]
2740
//     x = 2    x = %r
2741
//         \    /
2742
//        [merge]
2743
//         use(x)
2744
//
2745
// At the `print(x)` point, the compiler doesn't know which branch ran (that's
2746
// a runtime decision), but it needs to emit code that works for either case.
2747
// This is where [`useVarInBlock`] is called.
2748
//
2749
// The generated IL looks like this:
2750
//
2751
//     @then
2752
//       jmp @merge(2);           // pass immediate `2`
2753
//     @else
2754
//       jmp @merge(%r);          // pass register `%r`
2755
//     @merge(w32 %m)             // `%m` receives whichever value arrives at runtime
2756
//       call w32 $print(%m);     // `print` is called with runtime value in `%m`
2757
//
2758
// A block is "sealed" when all predecessor edges are known. This is crucial
2759
// because until sealed, we can't know how many paths merge into the block,
2760
// and thus can't create the right number of block parameter arguments.
2761
//
2762
// If a block isn't sealed but we need a variable's value, we still create
2763
// a block parameter, but defer filling in the terminator arguments. When the
2764
// block is later sealed via [`sealBlock`], all incomplete block params are resolved.
2765
2766
/// Declare a new source-level variable and define its initial value.
2767
/// If called before any block exists (e.g., for parameters), the definition is skipped.
2768
fn newVar(
2769
    self: *mut FnLowerer,
2770
    name: ?*[u8],
2771
    type: il::Type,
2772
    mutable: bool,
2773
    val: il::Val
2774
) -> Var {
2775
    let id = self.vars.len;
2776
    self.vars.append(VarData { name, type, mutable, addressTaken: false }, self.allocator);
2777
2778
    let v = Var(id);
2779
    if self.currentBlock <> nil {
2780
        defVar(self, v, val);
2781
    }
2782
    return v;
2783
}
2784
2785
/// Define (write) a variable. Record the SSA value of a variable in the
2786
/// current block. Called when a variable is assigned or initialized (`let`
2787
/// bindings, assignments, loop updates). When [`useVar`] is later called,
2788
/// it will retrieve this value.
2789
fn defVar(self: *mut FnLowerer, v: Var, val: il::Val) {
2790
    assert *v < self.vars.len;
2791
    set getBlockMut(self, currentBlock(self)).vars[*v] = val;
2792
}
2793
2794
/// Use (read) the current value of a variable in the current block.
2795
/// May insert block parameters if the value must come from predecessors.
2796
fn useVar(self: *mut FnLowerer, v: Var) -> il::Val throws (LowerError) {
2797
    return try useVarInBlock(self, currentBlock(self), v);
2798
}
2799
2800
/// Resolve which SSA definition of a variable reaches a use point in a given block.
2801
///
2802
/// Given a variable and a block where it's used, this function finds the
2803
/// correct [`il::Val`] that holds the variable's value at that program point.
2804
/// When control flow merges from multiple predecessors with different
2805
/// definitions, it creates a block parameter to unify them.
2806
fn useVarInBlock(self: *mut FnLowerer, block: BlockId, v: Var) -> il::Val throws (LowerError) {
2807
    assert *v < self.vars.len;
2808
2809
    let blk = getBlockMut(self, block);
2810
    if let val = blk.vars[*v] {
2811
        return val;
2812
    }
2813
    // Entry block cannot have block parameters. If variable isn't defined
2814
    // in entry, we return undefined.
2815
    if block == self.entryBlock {
2816
        return il::Val::Undef;
2817
    }
2818
    if blk.sealState == Sealed::Yes {
2819
        if blk.preds.len == 0 {
2820
            // Variable used in sealed block with no predecessors.
2821
            throw LowerError::InvalidUse;
2822
        }
2823
        // Single predecessor means no merge needed, variable is implicitly
2824
        // available without a block parameter.
2825
        if blk.preds.len == 1 {
2826
            let pred = BlockId(blk.preds[0]);
2827
            if *pred <> *block {
2828
                let val = try useVarInBlock(self, pred, v);
2829
                set blk.vars[*v] = val; // Cache.
2830
                return val;
2831
            }
2832
        }
2833
    }
2834
    // Multiple predecessors or unsealed block: need a block parameter to merge
2835
    // the control flow paths.
2836
    return try createBlockParam(self, block, v);
2837
}
2838
2839
/// Look up a variable by name in the current scope.
2840
/// Searches from most recently declared to first, enabling shadowing.
2841
fn lookupVarByName(self: *FnLowerer, name: *[u8]) -> ?Var {
2842
    let mut id = self.vars.len;
2843
    while id > 0 {
2844
        set id -= 1;
2845
        if let varName = self.vars[id].name {
2846
            // Names are interned strings, so pointer comparison suffices.
2847
            if varName == name {
2848
                return Var(id);
2849
            }
2850
        }
2851
    }
2852
    return nil;
2853
}
2854
2855
/// Look up a local variable bound to an identifier node.
2856
fn lookupLocalVar(self: *FnLowerer, node: *ast::Node) -> ?Var {
2857
    let case ast::NodeValue::Ident(name) = node.value else {
2858
        return nil;
2859
    };
2860
    return lookupVarByName(self, name);
2861
}
2862
2863
/// Save current lexical variable scope depth.
2864
fn enterVarScope(self: *FnLowerer) -> u32 {
2865
    return self.vars.len;
2866
}
2867
2868
/// Restore lexical variable scope depth.
2869
fn exitVarScope(self: *mut FnLowerer, savedVarsLen: u32) {
2870
    set self.vars = @sliceOf(self.vars.ptr, savedVarsLen, self.vars.cap);
2871
}
2872
2873
/// Get the metadata for a variable.
2874
fn getVar(self: *FnLowerer, v: Var) -> *VarData {
2875
    assert *v < self.vars.len;
2876
    return &self.vars[*v];
2877
}
2878
2879
/// Create a block parameter to merge a variable's value from multiple
2880
/// control flow paths.
2881
///
2882
/// Called when [`useVarInBlock`] can't find a local definition and the block has
2883
/// multiple predecessors. For example, when `x` is used in `@end` but defined
2884
/// differently in `@then` and `@else`:
2885
///
2886
///     @then
2887
///       jmp @end(1);            // x = 1
2888
///     @else
2889
///       jmp @end(2);            // x = 2
2890
///     @end(w32 %1)              // x = %1, merged from predecessors
2891
///       ret %1;
2892
///
2893
/// This function creates a fresh register `%1` as a block parameter, then patches
2894
/// each predecessor's jump to pass its value of `x` as an argument.
2895
fn createBlockParam(self: *mut FnLowerer, block: BlockId, v: Var) -> il::Val throws (LowerError) {
2896
    // Entry block must not have block parameters.
2897
    assert block <> self.entryBlock, "createBlockParam: entry block must not have block parameters";
2898
    // Allocate a register to hold the merged value.
2899
    let reg = nextReg(self);
2900
    let type = getVar(self, v).type;
2901
2902
    // Create block parameter and add it to the block.
2903
    let param = il::Param { value: reg, type };
2904
    let blk = getBlockMut(self, block);
2905
    blk.params.append(param, self.allocator);
2906
    blk.paramVars.append(*v, self.allocator); // Associate variable with parameter.
2907
2908
    // Record that this variable's value in this block is now the parameter register.
2909
    // This must happen before the predecessor loop to handle self-referential loops.
2910
    set blk.vars[*v] = il::Val::Reg(reg);
2911
2912
    match &mut blk.sealState {
2913
        case Sealed::No { incompleteVars } => {
2914
            // Block unsealed: defer until sealing.
2915
            incompleteVars.append(*v, self.allocator);
2916
        },
2917
        case Sealed::Yes => {
2918
            // Block sealed: check for trivial phi before committing. If all
2919
            // predecessors provide the same value, we can remove the param we
2920
            // just created and use that value directly.
2921
            if let trivial = try getTrivialPhiVal(self, block, v) {
2922
                let provisional = il::Val::Reg(reg);
2923
                removeLastBlockParam(self, block);
2924
                rewriteCachedVarValue(self, v, provisional, trivial);
2925
                set getBlockMut(self, block).vars[*v] = trivial;
2926
                return trivial;
2927
            }
2928
            // Non-trivial phi: patch predecessors to pass their values.
2929
            try resolveBlockArgs(self, block, v);
2930
        },
2931
    }
2932
    return il::Val::Reg(reg);
2933
}
2934
2935
/// Complete a block parameter by looking up the variable's value in all
2936
/// predecessors and patching their terminator instructions with edge arguments.
2937
///
2938
/// This is the block-parameter equivalent of adding operands to a phi-function in
2939
/// traditional SSA. Where a phi-function merges values at the join point:
2940
///
2941
///     x3 = phi(x1, x2)
2942
///
2943
/// This representation avoids the need for phi nodes to reference their
2944
/// predecessor blocks explicitly, since the control flow edges already encode
2945
/// that information.
2946
fn resolveBlockArgs(self: *mut FnLowerer, block: BlockId, v: Var) throws (LowerError) {
2947
    let blk = getBlock(self, block);
2948
2949
    // Find the parameter index corresponding to this variable.
2950
    // Each variable that needs merging gets its own block parameter slot.
2951
    let mut paramIdx: u32 = 0;
2952
    for i in 0..blk.paramVars.len {
2953
        if blk.paramVars[i] == *v {
2954
            set paramIdx = i;
2955
            break;
2956
        }
2957
    }
2958
2959
    // For each predecessor, recursively look up the variable's reaching definition
2960
    // in that block, then patch the predecessor's terminator to pass that value
2961
    // as an argument to this block's parameter.
2962
    for predId in blk.preds {
2963
        let pred = BlockId(predId);
2964
        // This may recursively trigger more block arg resolution if the
2965
        // predecessor also needs to look up the variable from its predecessors.
2966
        let val = try useVarInBlock(self, pred, v);
2967
        assert val <> il::Val::Undef, "createBlockParam: predecessor provides undef value for block parameter";
2968
        patchTerminatorArg(self, pred, *block, paramIdx, val);
2969
    }
2970
}
2971
2972
/// Check if a block parameter is trivial, i.e. all predecessors provide
2973
/// the same value. Returns the trivial value if so.
2974
fn getTrivialPhiVal(self: *mut FnLowerer, block: BlockId, v: Var) -> ?il::Val throws (LowerError) {
2975
    let blk = getBlock(self, block);
2976
    // Get the block parameter register.
2977
    let paramReg = blk.vars[*v];
2978
    // Check if all predecessors provide the same value.
2979
    let mut sameVal: ?il::Val = nil;
2980
2981
    for predId in blk.preds {
2982
        let pred = BlockId(predId);
2983
        let val = try useVarInBlock(self, pred, v);
2984
2985
        // Check if this is a self-reference.
2986
        // This happens in cycles where the loop back-edge passes the phi to
2987
        // itself. We skip self-references when checking for trivial phis.
2988
        if let reg = paramReg {
2989
            if val == reg {
2990
                // Self-reference, skip this predecessor.
2991
            } else if let sv = sameVal {
2992
                if val <> sv {
2993
                    // Multiple different values, not trivial.
2994
                    return nil;
2995
                }
2996
            } else {
2997
                set sameVal = val;
2998
            }
2999
        } else { // No param reg set yet, can't be trivial.
3000
            return nil;
3001
        }
3002
    }
3003
    return sameVal;
3004
}
3005
3006
/// Patch a single terminator argument for a specific edge. This is used during
3007
/// SSA construction to pass variable values along control flow edges.
3008
fn patchTerminatorArg(
3009
    self: *mut FnLowerer,
3010
    from: BlockId,         // The predecessor block containing the terminator to patch.
3011
    target: u32,           // The index of the target block we're passing the value to.
3012
    paramIdx: u32,         // The index of the block parameter to set.
3013
    val: il::Val           // The value to pass as the argument.
3014
) {
3015
    let data = getBlockMut(self, from);
3016
    let ix = data.instrs.len - 1; // The terminator is always the last instruction.
3017
3018
    // TODO: We shouldn't need to use a mutable subscript here, given that the
3019
    // fields are already mutable.
3020
    match &mut data.instrs[ix] {
3021
        case il::Instr::Jmp { args, .. } => {
3022
            set *args = growArgs(self, *args, paramIdx + 1);
3023
            set args[paramIdx] = val;
3024
        }
3025
        case il::Instr::Br { thenTarget, thenArgs, elseTarget, elseArgs, .. } => {
3026
            // Nb. both branches could target the same block (e.g. `if cond { x } else { x }`).
3027
            if *thenTarget == target {
3028
                set *thenArgs = growArgs(self, *thenArgs, paramIdx + 1);
3029
                set thenArgs[paramIdx] = val;
3030
            }
3031
            if *elseTarget == target {
3032
                set *elseArgs = growArgs(self, *elseArgs, paramIdx + 1);
3033
                set elseArgs[paramIdx] = val;
3034
            }
3035
        }
3036
        case il::Instr::Switch { defaultTarget, defaultArgs, cases, .. } => {
3037
            if *defaultTarget == target {
3038
                set *defaultArgs = growArgs(self, *defaultArgs, paramIdx + 1);
3039
                set defaultArgs[paramIdx] = val;
3040
            }
3041
            let idx = paramIdx + 1;
3042
            for ci in 0..cases.len {
3043
                if cases[ci].target == target {
3044
                    set cases[ci].args = growArgs(self, cases[ci].args, idx);
3045
                    set cases[ci].args[paramIdx] = val;
3046
                }
3047
            }
3048
        }
3049
        else => {
3050
            // Other terminators (e.g. `Ret`, `Unreachable`) don't have successor blocks.
3051
        }
3052
    }
3053
}
3054
3055
/// Grow an args array to hold at least the given capacity.
3056
fn growArgs(self: *mut FnLowerer, args: *mut [il::Val], capacity: u32) -> *mut [il::Val] {
3057
    if args.len >= capacity {
3058
        return args;
3059
    }
3060
    let newArgs = try! alloc::allocSlice(
3061
        self.low.fnArena, @sizeOf(il::Val), @alignOf(il::Val), capacity
3062
    ) as *mut [il::Val];
3063
3064
    for arg, i in args {
3065
        set newArgs[i] = arg;
3066
    }
3067
    for i in args.len..capacity {
3068
        set newArgs[i] = il::Val::Undef;
3069
    }
3070
    return newArgs;
3071
}
3072
3073
/// Extract the parameter name from an [`FnParam`] AST node value.
3074
fn paramName(value: *ast::NodeValue) -> *[u8] throws (LowerError) {
3075
    let case ast::NodeValue::FnParam(param) = *value else {
3076
        throw LowerError::ExpectedFunctionParam;
3077
    };
3078
    let case ast::NodeValue::Ident(name) = param.name.value else {
3079
        throw LowerError::ExpectedIdentifier;
3080
    };
3081
    return name;
3082
}
3083
3084
/// Lower function parameters. Declares variables for each parameter.
3085
/// When a receiver name is passed, we're handling a trait method.
3086
fn lowerParams(
3087
    self: *mut FnLowerer,
3088
    fnType: resolver::FnType,
3089
    astParams: *mut [*ast::Node],
3090
    receiverName: ?*ast::Node
3091
) -> *[il::Param] throws (LowerError) {
3092
    let offset: u32 = 1 if self.returnReg <> nil else 0;
3093
    let totalLen = fnType.paramTypes.len as u32 + offset;
3094
    if totalLen == 0 {
3095
        return &[];
3096
    }
3097
    assert fnType.paramTypes.len as u32 <= resolver::MAX_FN_PARAMS;
3098
3099
    let params = try! alloc::allocSlice(
3100
        self.low.fnArena, @sizeOf(il::Param), @alignOf(il::Param), totalLen
3101
    ) as *mut [il::Param];
3102
3103
    if let reg = self.returnReg {
3104
        set params[0] = il::Param { value: reg, type: il::Type::W64 };
3105
    }
3106
    for i in 0..fnType.paramTypes.len as u32 {
3107
        let type = ilType(self.low, *fnType.paramTypes[i]);
3108
        let reg = nextReg(self);
3109
3110
        set params[i + offset] = il::Param { value: reg, type };
3111
3112
        // Declare the parameter variable. For the receiver, the name comes
3113
        // from the receiver node.
3114
        // For all other parameters, the name comes from the AST params.
3115
        let mut name: *[u8] = undefined;
3116
        if let recNode = receiverName {
3117
            if i == 0 {
3118
                let case ast::NodeValue::Ident(recName) = recNode.value else {
3119
                    throw LowerError::ExpectedIdentifier;
3120
                };
3121
                set name = recName;
3122
            } else {
3123
                set name = try paramName(&astParams[i - 1].value);
3124
            }
3125
        } else {
3126
            set name = try paramName(&astParams[i].value);
3127
        }
3128
        let v = newVar(self, name, type, false, il::Val::Undef);
3129
3130
        self.params.append(FnParamBinding { var: v, reg }, self.allocator);
3131
    }
3132
    return params;
3133
}
3134
3135
/// Resolve match subject.
3136
fn lowerMatchSubject(self: *mut FnLowerer, subject: *ast::Node) -> MatchSubject throws (LowerError) {
3137
    let mut val = try lowerExpr(self, subject);
3138
    let subjectType = try typeOf(self, subject);
3139
    let unwrapped = resolver::unwrapMatchSubject(subjectType);
3140
3141
    // When matching an aggregate by value, copy it to a fresh stack slot so
3142
    // that bindings are independent of the original memory.  Without this,
3143
    // the lowerer returns a pointer into the source and mutations to the
3144
    // source silently corrupt the bound variables.
3145
    if unwrapped.by == resolver::MatchBy::Value and isAggregateType(unwrapped.effectiveTy) {
3146
        set val = try emitStackVal(self, unwrapped.effectiveTy, val);
3147
    }
3148
3149
    let mut bindType = unwrapped.effectiveTy;
3150
    if let case resolver::Type::Optional(inner) = unwrapped.effectiveTy {
3151
        set bindType = *inner;
3152
    }
3153
    let ilType = ilType(self.low, unwrapped.effectiveTy);
3154
    let kind = matchSubjectKind(unwrapped.effectiveTy);
3155
3156
    return MatchSubject { val, type: unwrapped.effectiveTy, ilType, bindType, kind, by: unwrapped.by };
3157
}
3158
3159
/// Check whether a case pattern is an unconditional wildcard.
3160
fn isWildcardPattern(pattern: *ast::Node) -> bool {
3161
    match pattern.value {
3162
        case ast::NodeValue::Placeholder => return true,
3163
        else => return false,
3164
    }
3165
}
3166
3167
/// Check whether an AST node is the `undefined` literal.
3168
fn isUndef(node: *ast::Node) -> bool {
3169
    match node.value {
3170
        case ast::NodeValue::Undef => return true,
3171
        else => return false,
3172
    }
3173
}
3174
3175
/// Load the tag byte from a tagged value aggregate (optionals and unions).
3176
fn tvalTagReg(self: *mut FnLowerer, base: il::Reg) -> il::Reg {
3177
    let tagReg = nextReg(self);
3178
    emitLoadW8At(self, tagReg, base, TVAL_TAG_OFFSET);
3179
    return tagReg;
3180
}
3181
3182
/// Load the tag word from a result aggregate.
3183
fn resultTagReg(self: *mut FnLowerer, base: il::Reg) -> il::Reg {
3184
    let tagReg = nextReg(self);
3185
    emitLoadW64At(self, tagReg, base, TVAL_TAG_OFFSET);
3186
    return tagReg;
3187
}
3188
3189
/// Get the register to compare against `0` for optional `nil` checking.
3190
/// For null-ptr-optimized types, loads the data pointer, or returns it
3191
/// directly for scalar pointers. For aggregates, returns the tag register.
3192
fn optionalNilReg(self: *mut FnLowerer, val: il::Val, typ: resolver::Type) -> il::Reg throws (LowerError) {
3193
    let reg = emitValToReg(self, val);
3194
3195
    match typ {
3196
        case resolver::Type::Optional(resolver::Type::Slice { .. }) => {
3197
            let ptrReg = nextReg(self);
3198
            emitLoadW64At(self, ptrReg, reg, SLICE_PTR_OFFSET);
3199
            return ptrReg;
3200
        }
3201
        case resolver::Type::Optional(resolver::Type::Pointer { .. }) => return reg,
3202
        case resolver::Type::Optional(_) => return tvalTagReg(self, reg),
3203
        else => return reg,
3204
    }
3205
}
3206
3207
/// Lower an optional nil check (`opt == nil` or `opt <> nil`).
3208
fn lowerNilCheck(self: *mut FnLowerer, opt: *ast::Node, isEq: bool) -> il::Val throws (LowerError) {
3209
    let optTy = try typeOf(self, opt);
3210
    // Handle `nil == nil` or `nil <> nil`.
3211
    if optTy == resolver::Type::Nil {
3212
        return il::Val::Imm(1) if isEq else il::Val::Imm(0);
3213
    }
3214
    let val = try lowerExpr(self, opt);
3215
    let cmpReg = try optionalNilReg(self, val, optTy);
3216
3217
    // Null-pointer-optimized types compare a 64-bit pointer against zero.
3218
    // Aggregate optionals compare an 8-bit tag byte against zero.
3219
    let cmpType = il::Type::W64 if resolver::isOptionalPointer(optTy) else il::Type::W8;
3220
3221
    let op = il::BinOp::Eq if isEq else il::BinOp::Ne;
3222
    return emitTypedBinOp(self, op, cmpType, il::Val::Reg(cmpReg), il::Val::Imm(0));
3223
}
3224
3225
/// Load the payload value from a tagged value aggregate at the given offset.
3226
fn tvalPayloadVal(self: *mut FnLowerer, base: il::Reg, payload: resolver::Type, valOffset: i32) -> il::Val {
3227
    if payload == resolver::Type::Void {
3228
        return il::Val::Undef;
3229
    }
3230
    return emitRead(self, base, valOffset, payload);
3231
}
3232
3233
/// Compute the address of the payload in a tagged value aggregate.
3234
fn tvalPayloadAddr(self: *mut FnLowerer, base: il::Reg, valOffset: i32) -> il::Val {
3235
    return il::Val::Reg(emitPtrOffset(self, base, valOffset));
3236
}
3237
3238
/// Bind a variable to a tagged value's payload.
3239
fn bindPayloadVariable(
3240
    self: *mut FnLowerer,
3241
    name: *[u8],
3242
    subjectVal: il::Val,
3243
    bindType: resolver::Type,
3244
    matchBy: resolver::MatchBy,
3245
    valOffset: i32,
3246
    mutable: bool
3247
) -> Var throws (LowerError) {
3248
    let base = emitValToReg(self, subjectVal);
3249
    let mut payload: il::Val = undefined;
3250
3251
    match matchBy {
3252
        case resolver::MatchBy::Value =>
3253
            set payload = tvalPayloadVal(self, base, bindType, valOffset),
3254
        case resolver::MatchBy::Ref, resolver::MatchBy::MutRef =>
3255
            set payload = tvalPayloadAddr(self, base, valOffset),
3256
    };
3257
    return newVar(self, name, ilType(self.low, bindType), mutable, payload);
3258
}
3259
3260
/// Bind an identifier from a matched subject.
3261
fn bindMatchVariable(
3262
    self: *mut FnLowerer,
3263
    subject: *MatchSubject,
3264
    binding: *ast::Node,
3265
    mutable: bool
3266
) -> ?Var throws (LowerError) {
3267
    // Only bind if the pattern is an identifier.
3268
    let case ast::NodeValue::Ident(name) = binding.value else {
3269
        return nil;
3270
    };
3271
    // For optional aggregates, extract the payload from the tagged value.
3272
    // The tag check already passed, so we know the payload is valid.
3273
    if let case MatchSubjectKind::OptionalAggregate = subject.kind {
3274
        let valOffset = resolver::getOptionalValOffset(subject.bindType) as i32;
3275
        return try bindPayloadVariable(self, name, subject.val, subject.bindType, subject.by, valOffset, mutable);
3276
    }
3277
    // Declare the variable in the current block's scope.
3278
    return newVar(self, name, ilType(self.low, subject.bindType), mutable, subject.val);
3279
}
3280
3281
/// Bind variables from inside case patterns (union variants, records, slices).
3282
/// `failBlock` is passed when nested patterns may require additional tests
3283
/// that branch on mismatch (e.g. nested union variant tests).
3284
fn bindPatternVariables(self: *mut FnLowerer, subject: *MatchSubject, patterns: *mut [*ast::Node], failBlock: BlockId) throws (LowerError) {
3285
    for pattern in patterns {
3286
3287
        // Handle simple variant patterns like `Variant(x)`.
3288
        if let arg = resolver::variantPatternBinding(self.low.resolver, pattern) {
3289
            let case MatchSubjectKind::Union(unionInfo) = subject.kind
3290
                else panic "bindPatternVariables: expected union subject";
3291
            let valOffset = unionInfo.valOffset as i32;
3292
3293
            // Get the actual field type from the variant's record info.
3294
            // This preserves the original data layout type (e.g. `*T`) even when
3295
            // the resolver resolved the pattern against a dereferenced type (`T`).
3296
            let variantExtra = resolver::nodeData(self.low.resolver, pattern).extra;
3297
            let case resolver::NodeExtra::UnionVariant { ordinal, .. } = variantExtra
3298
                else panic "bindPatternVariables: expected variant extra";
3299
            let payloadType = unionInfo.variants[ordinal].valueType;
3300
            let payloadRec = resolver::getRecord(payloadType)
3301
                else panic "bindPatternVariables: expected record payload";
3302
            let fieldType = payloadRec.fields[0].fieldType;
3303
3304
            match arg.value {
3305
                case ast::NodeValue::Ident(name) => {
3306
                    try bindPayloadVariable(self, name, subject.val, fieldType, subject.by, valOffset, false);
3307
                }
3308
                case ast::NodeValue::Placeholder => {}
3309
                else => {
3310
                    // Nested pattern inside a variant call, e.g. `Variant(Inner { x, y })`.
3311
                    let base = emitValToReg(self, subject.val);
3312
                    let payloadBase = emitPtrOffset(self, base, valOffset);
3313
                    let fieldInfo = resolver::RecordField {
3314
                        name: nil,
3315
                        fieldType,
3316
                        offset: 0,
3317
                    };
3318
                    try bindFieldVariable(self, arg, payloadBase, fieldInfo, subject.by, failBlock);
3319
                }
3320
            }
3321
        }
3322
        match pattern.value {
3323
            // Compound variant patterns like `Variant { a, b }`.
3324
            case ast::NodeValue::RecordLit(lit) =>
3325
                try bindRecordPatternFields(self, subject, pattern, lit, failBlock),
3326
            // Array patterns like `[a, b, c]`.
3327
            case ast::NodeValue::ArrayLit(items) =>
3328
                try bindArrayPatternElements(self, subject, items, failBlock),
3329
            // Literals, wildcards, identifiers: no bindings needed.
3330
            else => {},
3331
        }
3332
    }
3333
}
3334
3335
/// Bind variables from an array literal pattern (e.g., `[a, 1, c]`).
3336
/// Each element is either bound as a variable, skipped (placeholder), or
3337
/// tested against the subject element, branching to `failBlock` on mismatch.
3338
fn bindArrayPatternElements(
3339
    self: *mut FnLowerer,
3340
    subject: *MatchSubject,
3341
    items: *mut [*ast::Node],
3342
    failBlock: BlockId
3343
) throws (LowerError) {
3344
    let case resolver::Type::Array(arrInfo) = subject.type
3345
        else throw LowerError::ExpectedSliceOrArray;
3346
3347
    let elemTy = *arrInfo.item;
3348
    let elemLayout = resolver::getTypeLayout(elemTy);
3349
    let stride = elemLayout.size as i32;
3350
    let base = emitValToReg(self, subject.val);
3351
3352
    for elem, i in items {
3353
        let fieldInfo = resolver::RecordField {
3354
            name: nil,
3355
            fieldType: elemTy,
3356
            offset: (i as i32) * stride,
3357
        };
3358
        try bindFieldVariable(self, elem, base, fieldInfo, subject.by, failBlock);
3359
    }
3360
}
3361
3362
/// Bind fields from a record pattern.
3363
fn bindRecordPatternFields(self: *mut FnLowerer, subject: *MatchSubject, pattern: *ast::Node, lit: ast::RecordLit, failBlock: BlockId) throws (LowerError) {
3364
    // No fields to bind (e.g., `{ .. }`).
3365
    if lit.fields.len == 0 {
3366
        return;
3367
    }
3368
    // Optional value patterns were already compared structurally by
3369
    // `emitPatternMatch`; unlike union record patterns, they have no payload
3370
    // bindings to extract here.
3371
    if let case MatchSubjectKind::OptionalAggregate = subject.kind {
3372
        return;
3373
    }
3374
    // Get the union type info from the subject.
3375
    let case MatchSubjectKind::Union(unionInfo) = subject.kind
3376
        else panic "bindRecordPatternFields: expected union subject";
3377
3378
    // Get the variant index from the pattern node.
3379
    let case resolver::NodeExtra::UnionVariant { ordinal: variantOrdinal, .. } =
3380
        resolver::nodeData(self.low.resolver, pattern).extra
3381
    else throw LowerError::MissingMetadata;
3382
3383
    // Get the record type from the variant's payload type.
3384
    let payloadType = unionInfo.variants[variantOrdinal].valueType;
3385
    let recInfo = resolver::getRecord(payloadType)
3386
        else throw LowerError::ExpectedRecord;
3387
3388
    // Get the payload base pointer which points to the record within the tagged union.
3389
    let base = emitValToReg(self, subject.val);
3390
    let valOffset = unionInfo.valOffset as i32;
3391
    let payloadBase = emitPtrOffset(self, base, valOffset);
3392
3393
    try bindNestedRecordFields(self, payloadBase, lit, recInfo, subject.by, failBlock);
3394
}
3395
3396
/// Bind a single record field to a pattern variable, with support for nested
3397
/// pattern tests that branch to `failBlock` on mismatch.
3398
fn bindFieldVariable(
3399
    self: *mut FnLowerer,
3400
    binding: *ast::Node,
3401
    base: il::Reg,
3402
    fieldInfo: resolver::RecordField,
3403
    matchBy: resolver::MatchBy,
3404
    failBlock: BlockId
3405
) throws (LowerError) {
3406
    match binding.value {
3407
        case ast::NodeValue::Ident(name) => {
3408
            let val = emitRead(self, base, fieldInfo.offset, fieldInfo.fieldType)
3409
                if matchBy == resolver::MatchBy::Value
3410
                else il::Val::Reg(emitPtrOffset(self, base, fieldInfo.offset));
3411
            newVar(self, name, ilType(self.low, fieldInfo.fieldType), false, val);
3412
        }
3413
        case ast::NodeValue::Placeholder => {}
3414
        case ast::NodeValue::RecordLit(lit) => {
3415
            // Check if this record literal is a union variant pattern.
3416
            if let keyNode = resolver::patternVariantKeyNode(binding) {
3417
                if let case resolver::NodeExtra::UnionVariant { .. } = resolver::nodeData(self.low.resolver, keyNode).extra {
3418
                    try emitNestedFieldTest(self, binding, base, fieldInfo, matchBy, failBlock);
3419
                    return;
3420
                }
3421
            }
3422
            // Plain nested record destructuring pattern.
3423
            // Auto-deref: if the field is a pointer, load it first.
3424
            let mut derefType = fieldInfo.fieldType;
3425
            let mut nestedBase = emitPtrOffset(self, base, fieldInfo.offset);
3426
            if let case resolver::Type::Pointer { target, .. } = fieldInfo.fieldType {
3427
                let ptrReg = nextReg(self);
3428
                emitLoadW64At(self, ptrReg, nestedBase, 0);
3429
                set nestedBase = ptrReg;
3430
                set derefType = *target;
3431
            }
3432
            let recInfo = resolver::getRecord(derefType)
3433
                else throw LowerError::ExpectedRecord;
3434
3435
            try bindNestedRecordFields(self, nestedBase, lit, recInfo, matchBy, failBlock);
3436
        }
3437
        else => {
3438
            // Nested pattern requiring a test (union variant scope access, literal, etc).
3439
            try emitNestedFieldTest(self, binding, base, fieldInfo, matchBy, failBlock);
3440
        }
3441
    }
3442
}
3443
3444
/// Emit a nested pattern test for a record field value, branching to
3445
/// `failBlock` if the pattern does not match. On success, continues in
3446
/// a fresh block and binds any nested variables.
3447
fn emitNestedFieldTest(
3448
    self: *mut FnLowerer,
3449
    pattern: *ast::Node,
3450
    base: il::Reg,
3451
    fieldInfo: resolver::RecordField,
3452
    matchBy: resolver::MatchBy,
3453
    failBlock: BlockId
3454
) throws (LowerError) {
3455
    let mut fieldType = fieldInfo.fieldType;
3456
    let fieldPtr = emitPtrOffset(self, base, fieldInfo.offset);
3457
3458
    // Auto-deref: when the field is a pointer and the pattern destructures
3459
    // the pointed-to value, load the pointer and use the target type.
3460
    // The loaded pointer becomes the base address for the nested subject.
3461
    let mut derefBase: ?il::Reg = nil;
3462
    if let case resolver::Type::Pointer { target, .. } = fieldType {
3463
        if resolver::isDestructuringPattern(pattern) {
3464
            let ptrReg = nextReg(self);
3465
            emitLoadW64At(self, ptrReg, fieldPtr, 0);
3466
            set derefBase = ptrReg;
3467
            set fieldType = *target;
3468
        }
3469
    }
3470
    // Build a MatchSubject for the nested field.
3471
    let ilTy = ilType(self.low, fieldType);
3472
    let kind = matchSubjectKind(fieldType);
3473
3474
    // Determine the subject value.
3475
    let mut val: il::Val = undefined;
3476
    if let reg = derefBase {
3477
        // Auto-deref: the loaded pointer is the address of the target value.
3478
        set val = il::Val::Reg(reg);
3479
    } else if isAggregateType(fieldType) {
3480
        // Aggregate: use the pointer.
3481
        set val = il::Val::Reg(fieldPtr);
3482
    } else {
3483
        // Scalar: load the value.
3484
        set val = emitRead(self, base, fieldInfo.offset, fieldType);
3485
    }
3486
    let nestedSubject = MatchSubject {
3487
        val,
3488
        type: fieldType,
3489
        ilType: ilTy,
3490
        bindType: fieldType,
3491
        kind,
3492
        by: matchBy,
3493
    };
3494
3495
    // Emit the pattern test: on success jump to `continueBlock`, on fail to `failBlock`.
3496
    let continueBlock = try createBlock(self, "nest");
3497
    try emitPatternMatch(self, &nestedSubject, pattern, continueBlock, failBlock);
3498
    try switchToAndSeal(self, continueBlock);
3499
3500
    // After the test succeeds, bind any nested variables.
3501
    let patterns: *mut [*ast::Node] = &mut [pattern];
3502
    try bindPatternVariables(self, &nestedSubject, patterns, failBlock);
3503
}
3504
3505
/// Bind variables from a nested record literal pattern.
3506
fn bindNestedRecordFields(
3507
    self: *mut FnLowerer,
3508
    base: il::Reg,
3509
    lit: ast::RecordLit,
3510
    recInfo: resolver::RecordType,
3511
    matchBy: resolver::MatchBy,
3512
    failBlock: BlockId
3513
) throws (LowerError) {
3514
    for fieldNode in lit.fields {
3515
        let case ast::NodeValue::RecordLitField(field) = fieldNode.value else {
3516
            throw LowerError::UnexpectedNodeValue(fieldNode);
3517
        };
3518
        let fieldIdx = resolver::recordFieldIndexFor(self.low.resolver, fieldNode)
3519
            else throw LowerError::MissingMetadata;
3520
        if fieldIdx >= recInfo.fields.len {
3521
            throw LowerError::MissingMetadata;
3522
        }
3523
        let fieldInfo = recInfo.fields[fieldIdx];
3524
3525
        try bindFieldVariable(self, field.value, base, fieldInfo, matchBy, failBlock);
3526
    }
3527
}
3528
3529
/// Lower function body to a list of basic blocks.
3530
fn lowerFnBody(self: *mut FnLowerer, body: *ast::Node) -> *[il::Block] throws (LowerError) {
3531
    // Create and switch to entry block.
3532
    let entry = try createBlock(self, "entry");
3533
    set self.entryBlock = entry;
3534
    switchToBlock(self, entry);
3535
3536
    /// Bind parameter registers to variables in the entry block.
3537
    for def in self.params {
3538
        defVar(self, def.var, il::Val::Reg(def.reg));
3539
    }
3540
    /// Lower function body.
3541
    try lowerBlock(self, body);
3542
3543
    // Add implicit return if body doesn't diverge.
3544
    if not blockHasTerminator(self) {
3545
        if self.fnType.throwList.len > 0 {
3546
            if *self.fnType.returnType == resolver::Type::Void {
3547
                // Implicit `void` return in throwing function: wrap in result success.
3548
                let val = try buildResult(self, 0, nil, resolver::Type::Void);
3549
                try emitRetVal(self, val);
3550
            } else {
3551
                // Non-void throwing function without explicit return should
3552
                // not happen.
3553
                panic "lowerFnBody: missing return in non-void function";
3554
            }
3555
        } else {
3556
            emit(self, il::Instr::Ret { val: nil });
3557
        }
3558
    }
3559
    return try finalizeBlocks(self);
3560
}
3561
3562
/// Lower a scalar match as a switch instruction.
3563
fn lowerMatchSwitch(self: *mut FnLowerer, prongs: *mut [*ast::Node], subject: *MatchSubject, mergeBlock: *mut ?BlockId) throws (LowerError) {
3564
    let mut blocks: [BlockId; 32] = undefined;
3565
    let mut cases: *mut [il::SwitchCase] = &mut [];
3566
    let mut defaultIdx: u32 = 0;
3567
    let entry = currentBlock(self);
3568
3569
    for p, i in prongs {
3570
        let case ast::NodeValue::MatchProng(prong) = p.value
3571
            else throw LowerError::UnexpectedNodeValue(p);
3572
3573
        match prong.arm {
3574
            case ast::ProngArm::Binding(_), ast::ProngArm::Else => {
3575
                set blocks[i] = try createBlock(self, "default");
3576
                set defaultIdx = i;
3577
            }
3578
            case ast::ProngArm::Case(pats) => {
3579
                set blocks[i] = try createBlock(self, "case");
3580
                for pat in pats {
3581
                    let cv = resolver::constValueEntry(self.low.resolver, pat)
3582
                        else throw LowerError::MissingConst(pat);
3583
3584
                    cases.append(il::SwitchCase {
3585
                        value: constToScalar(cv),
3586
                        target: *blocks[i],
3587
                        args: &mut []
3588
                    }, self.allocator);
3589
                }
3590
            }
3591
        }
3592
        addPredecessor(self, blocks[i], entry);
3593
    }
3594
    emit(self, il::Instr::Switch {
3595
        val: subject.val,
3596
        defaultTarget: *blocks[defaultIdx],
3597
        defaultArgs: &mut [],
3598
        cases: &mut cases[..]
3599
    });
3600
3601
    for p, i in prongs {
3602
        let case ast::NodeValue::MatchProng(prong) = p.value
3603
            else throw LowerError::UnexpectedNodeValue(p);
3604
3605
        try switchToAndSeal(self, blocks[i]);
3606
        try lowerNode(self, prong.body);
3607
        try emitMergeIfUnterminated(self, mergeBlock);
3608
    }
3609
    if let blk = *mergeBlock {
3610
        try switchToAndSeal(self, blk);
3611
    }
3612
}
3613
3614
/// Lower a match statement.
3615
///
3616
/// Processes prongs sequentially, generating comparison code and branches for each.
3617
/// Prongs are processed in source order, so earlier prongs take precedence.
3618
///
3619
/// Guards are handled by emitting an additional branch after pattern matching
3620
/// but before the body.
3621
///
3622
/// Example:
3623
///
3624
///   match x {
3625
///       case 0 => return 0,
3626
///       case 1 => return 1,
3627
///       else => return 2,
3628
///   }
3629
///
3630
/// Generates:
3631
///
3632
///   arm#0:
3633
///       br.eq w32 %x 0 case#0 arm#1;    // if `x == 0`, jump to case#0, else arm#1
3634
///   case#0:
3635
///       ret 0;                          // `case 0` body
3636
///   arm#1:
3637
///       br.eq w32 %x 1 case#1 arm#2;    // if `x == 1`, jump to case#1, else arm#2
3638
///   case#1:
3639
///       ret 1;                          // `case 1` body
3640
///   arm#2:
3641
///       jmp else#0;                     // fallthrough to `else`
3642
///   else#0:
3643
///       ret 2;                          // `else` body
3644
///
3645
/// Example: Binding with guard
3646
///
3647
///   match x {
3648
///       y if y > 0 => return y,
3649
///       else => return 0,
3650
///   }
3651
///
3652
/// Generates:
3653
///
3654
///   arm#0:
3655
///       jmp guard#0;                    // catch-all binding, jump to guard
3656
///   case#0(w32 %y):
3657
///       ret %y;                         // guarded case body, receives bound var
3658
///   guard#0:
3659
///       sgt w32 %cmp %x 0;              // evaluate guard `y > 0`
3660
///       br.ne w32 %cmp 0 case#0 arm#1;  // if `true`, jump to case body
3661
///   arm#1:
3662
///       jmp else#0;                     // guard failed, fallthrough to `else`
3663
///   else#0:
3664
///       ret 0;                          // `else` body
3665
///
3666
fn lowerMatch(self: *mut FnLowerer, node: *ast::Node, m: ast::Match) throws (LowerError) {
3667
    assert m.prongs.len > 0;
3668
3669
    let prongs = m.prongs;
3670
    // Lower the subject expression once; reused across all arms.
3671
    let subject = try lowerMatchSubject(self, m.subject);
3672
    // Merge block created lazily if any arm needs it (i.e., doesn't diverge).
3673
    let mut mergeBlock: ?BlockId = nil;
3674
3675
    // Use `switch` instruction for matches with constant patterns.
3676
    if resolver::isMatchConst(self.low.resolver, node) {
3677
        try lowerMatchSwitch(self, prongs, &subject, &mut mergeBlock);
3678
        return;
3679
    }
3680
    // Fallback: chained branches.
3681
    let firstArm = try createBlock(self, "arm");
3682
    try emitJmp(self, firstArm);
3683
    try switchToAndSeal(self, firstArm);
3684
3685
    for prongNode, i in prongs {
3686
        let prongScope = enterVarScope(self);
3687
        let case ast::NodeValue::MatchProng(prong) = prongNode.value
3688
            else panic "lowerMatch: expected match prong";
3689
3690
        let isLastArm = i + 1 == prongs.len;
3691
        let hasGuard = prong.guard <> nil;
3692
        let catchAll = resolver::isProngCatchAll(self.low.resolver, prongNode);
3693
3694
        // Entry block: guard block if present, otherwise the body block.
3695
        // The guard block must be created before the body block so that
3696
        // block indices are in reverse post-order (RPO), which the register
3697
        // allocator requires.
3698
        let mut entryBlock: BlockId = undefined;
3699
        if hasGuard {
3700
            set entryBlock = try createBlock(self, "guard");
3701
        }
3702
        // Body block: where the case body lives.
3703
        let mut bodyLabel = "case";
3704
        if prong.arm == ast::ProngArm::Else {
3705
            set bodyLabel = "else";
3706
        }
3707
        let mut bodyBlock = try createBlock(self, bodyLabel);
3708
        if not hasGuard {
3709
            set entryBlock = bodyBlock;
3710
        }
3711
        // Fallthrough block: jumped to when pattern or guard fails.
3712
        let nextArm = try createBlock(self, "arm");
3713
3714
        // Emit pattern test: branch to entry block on match, next arm on fail.
3715
        match prong.arm {
3716
            case ast::ProngArm::Binding(_) if not catchAll =>
3717
                try emitBindingTest(self, &subject, entryBlock, nextArm),
3718
            case ast::ProngArm::Case(patterns) if not catchAll =>
3719
                try emitPatternMatches(self, &subject, patterns, entryBlock, nextArm),
3720
            else =>
3721
                try emitJmp(self, entryBlock),
3722
        }
3723
        // Switch to entry block, where any variable bindings need to be created.
3724
        try switchToAndSeal(self, entryBlock);
3725
3726
        // Bind pattern variables after successful match. Note that the guard
3727
        // has not been evaluated yet. Nested patterns may emit additional
3728
        // tests that branch to `nextArm` on failure, switching the current
3729
        // block.
3730
        match prong.arm {
3731
            case ast::ProngArm::Binding(pat) =>
3732
                try bindMatchVariable(self, &subject, pat, false),
3733
            case ast::ProngArm::Case(patterns) =>
3734
                try bindPatternVariables(self, &subject, patterns, nextArm),
3735
            else => {},
3736
        }
3737
3738
        // Evaluate guard if present; can still fail to next arm.
3739
        if let g = prong.guard {
3740
            try emitCondBranch(self, g, bodyBlock, nextArm);
3741
        } else if *currentBlock(self) <> *bodyBlock {
3742
            // Nested tests changed the current block. Create a new body block
3743
            // after the nest blocks to maintain RPO ordering, and jump to it.
3744
            set bodyBlock = try createBlock(self, bodyLabel);
3745
            try emitJmp(self, bodyBlock);
3746
        }
3747
        // Lower prong body and jump to merge if unterminated.
3748
        try switchToAndSeal(self, bodyBlock);
3749
        try lowerNode(self, prong.body);
3750
        try emitMergeIfUnterminated(self, &mut mergeBlock);
3751
        exitVarScope(self, prongScope);
3752
3753
        // Switch to next arm, unless last arm without guard.
3754
        if not isLastArm or hasGuard {
3755
            try switchToAndSeal(self, nextArm);
3756
            if isLastArm {
3757
                // Last arm with guard: guard failure jumps to merge.
3758
                try emitMergeIfUnterminated(self, &mut mergeBlock);
3759
            }
3760
        }
3761
    }
3762
    // Continue in merge block if we have one, ie. if at least one arm doesn't
3763
    // diverge.
3764
    if let blk = mergeBlock {
3765
        try switchToAndSeal(self, blk);
3766
    }
3767
}
3768
3769
/// Lower an `if let` statement.
3770
fn lowerIfLet(self: *mut FnLowerer, cond: ast::IfLet) throws (LowerError) {
3771
    let savedVarsLen = enterVarScope(self);
3772
    let subject = try lowerMatchSubject(self, cond.pattern.scrutinee);
3773
    let mut thenBlock: BlockId = undefined;
3774
    if cond.pattern.guard == nil {
3775
        set thenBlock = try createBlock(self, "then");
3776
    }
3777
    let elseBlock = try createBlock(self, "else");
3778
    let mut mergeBlock: ?BlockId = nil;
3779
3780
    // Pattern match: jump to @then on success, @else on failure.
3781
    try lowerPatternMatch(self, &subject, &cond.pattern, &mut thenBlock, "then", elseBlock);
3782
3783
    // Lower then branch.
3784
    try lowerNode(self, cond.thenBranch);
3785
    try emitMergeIfUnterminated(self, &mut mergeBlock);
3786
    // Pattern bindings are visible only in the success branch. Restore the
3787
    // outer variable scope before lowering `else`, where a same-named outer
3788
    // variable may be referenced.
3789
    exitVarScope(self, savedVarsLen);
3790
3791
    // Lower else branch.
3792
    try switchToAndSeal(self, elseBlock);
3793
    if let elseBranch = cond.elseBranch {
3794
        try lowerNode(self, elseBranch);
3795
    }
3796
    try emitMergeIfUnterminated(self, &mut mergeBlock);
3797
3798
    if let blk = mergeBlock {
3799
        try switchToAndSeal(self, blk);
3800
    }
3801
}
3802
3803
/// Emit pattern match branch with optional guard, and bind variables.
3804
/// Used by `if-let`, `let-else`, and `while-let` lowering.
3805
///
3806
/// When a guard is present, the guard block is created before `successBlock`
3807
/// to ensure block indices are in RPO.
3808
fn lowerPatternMatch(
3809
    self: *mut FnLowerer,
3810
    subject: *MatchSubject,
3811
    pat: *ast::PatternMatch,
3812
    successBlock: *mut BlockId,
3813
    successLabel: *[u8],
3814
    failBlock: BlockId
3815
) throws (LowerError) {
3816
    // If guard present, pattern match jumps to @guard, then guard evaluation
3817
    // jumps to `successBlock` or `failBlock`. Otherwise, jump directly to
3818
    // `successBlock`.
3819
    let mut targetBlock: BlockId = undefined;
3820
    if pat.guard <> nil {
3821
        set targetBlock = try createBlock(self, "guard");
3822
        set *successBlock = try createBlock(self, successLabel);
3823
    } else {
3824
        set targetBlock = *successBlock;
3825
    }
3826
    match pat.kind {
3827
        case ast::PatternKind::Case => {
3828
            let patterns: *mut [*ast::Node] = &mut [pat.pattern];
3829
            // Jump to `targetBlock` if the pattern matches, `failBlock` otherwise.
3830
            try emitPatternMatches(self, subject, patterns, targetBlock, failBlock);
3831
            try switchToAndSeal(self, targetBlock);
3832
            // Bind any variables inside the pattern. Nested patterns may
3833
            // emit additional tests that branch to `failBlock`, switching
3834
            // the current block.
3835
            try bindPatternVariables(self, subject, patterns, failBlock);
3836
        }
3837
        case ast::PatternKind::Binding => {
3838
            // Jump to `targetBlock` if there is a value present, `failBlock` otherwise.
3839
            try emitBindingTest(self, subject, targetBlock, failBlock);
3840
            try switchToAndSeal(self, targetBlock);
3841
            // Bind the matched value to the pattern variable.
3842
            try bindMatchVariable(self, subject, pat.pattern, pat.mutable);
3843
        }
3844
    }
3845
    // Handle guard: on success jump to `successBlock`, on failure jump to `failBlock`.
3846
    if let g = pat.guard {
3847
        try emitCondBranch(self, g, *successBlock, failBlock);
3848
        try switchToAndSeal(self, *successBlock);
3849
    } else if *currentBlock(self) <> *targetBlock {
3850
        // Nested tests changed the current block. Create a new success block
3851
        // after the nest blocks to maintain RPO ordering, and jump to it.
3852
        set *successBlock = try createBlock(self, successLabel);
3853
3854
        try emitJmp(self, *successBlock);
3855
        try switchToAndSeal(self, *successBlock);
3856
    }
3857
}
3858
3859
/// Lower a `let-else` statement.
3860
fn lowerLetElse(self: *mut FnLowerer, letElse: ast::LetElse) throws (LowerError) {
3861
    let subject = try lowerMatchSubject(self, letElse.pattern.scrutinee);
3862
    let mut successBlock: BlockId = undefined;
3863
    if letElse.pattern.guard == nil {
3864
        set successBlock = try createBlock(self, "success");
3865
    }
3866
    // The else branch executes when the pattern fails to match.
3867
    let elseBlock = try createBlock(self, "else");
3868
3869
    // Evaluate the pattern and jump to @success or @else.
3870
    try lowerPatternMatch(
3871
        self,
3872
        &subject,
3873
        &letElse.pattern,
3874
        &mut successBlock,
3875
        "success",
3876
        elseBlock,
3877
    );
3878
    let mut bindingVar: ?Var = nil;
3879
    if let case ast::PatternKind::Binding = letElse.pattern.kind {
3880
        set bindingVar = lookupLocalVar(self, letElse.pattern.pattern);
3881
    }
3882
    let mergeBlock = try createBlock(self, "merge");
3883
    try emitJmp(self, mergeBlock);
3884
3885
    try switchToAndSeal(self, elseBlock);
3886
    if try typeOf(self, letElse.elseBranch) == resolver::Type::Never {
3887
        try lowerNode(self, letElse.elseBranch);
3888
    } else {
3889
        let fallback = try lowerExpr(self, letElse.elseBranch);
3890
        if let variable = bindingVar {
3891
            defVar(self, variable, fallback);
3892
        }
3893
        try emitJmp(self, mergeBlock);
3894
    }
3895
3896
    // Continue at @merge after a successful match or value-producing fallback.
3897
    try switchToAndSeal(self, mergeBlock);
3898
}
3899
3900
/// Lower a `while let` loop as a match-driven loop.
3901
fn lowerWhileLet(self: *mut FnLowerer, w: ast::WhileLet) throws (LowerError) {
3902
    let savedVarsLen = enterVarScope(self);
3903
    // Create control flow blocks: loop header, body (created lazily when
3904
    // there's a guard), and exit.
3905
    let whileBlock = try createBlock(self, "while");
3906
    let mut bodyBlock: BlockId = undefined;
3907
    if w.pattern.guard == nil {
3908
        set bodyBlock = try createBlock(self, "body");
3909
    }
3910
    let endBlock = try createBlock(self, "merge");
3911
3912
    // Enter loop context and jump to loop header.
3913
    enterLoop(self, endBlock, whileBlock);
3914
    try switchAndJumpTo(self, whileBlock);
3915
    let subject = try lowerMatchSubject(self, w.pattern.scrutinee);
3916
3917
    // Evaluate pattern and jump to loop body or loop end.
3918
    try lowerPatternMatch(self, &subject, &w.pattern, &mut bodyBlock, "body", endBlock);
3919
3920
    // Lower loop body, jump back to loop header, and exit loop context.
3921
    try lowerBlock(self, w.body);
3922
    try emitJmpAndSeal(self, whileBlock);
3923
3924
    exitLoop(self);
3925
    try switchToAndSeal(self, endBlock);
3926
    exitVarScope(self, savedVarsLen);
3927
}
3928
3929
///////////////////
3930
// Node Lowering //
3931
///////////////////
3932
3933
/// Lower an AST node.
3934
fn lowerNode(self: *mut FnLowerer, node: *ast::Node) throws (LowerError) {
3935
    if self.low.options.debug {
3936
        set self.srcLoc.offset = node.span.offset;
3937
    }
3938
    match node.value {
3939
        case ast::NodeValue::Block(_) => {
3940
            try lowerBlock(self, node);
3941
        }
3942
        case ast::NodeValue::Unsafe(body) => {
3943
            try lowerNode(self, body);
3944
        }
3945
        case ast::NodeValue::Return { value } => {
3946
            try lowerReturnStmt(self, node, value);
3947
        }
3948
        case ast::NodeValue::Throw { expr } => {
3949
            try lowerThrowStmt(self, expr);
3950
        }
3951
        case ast::NodeValue::Let(l) => {
3952
            try lowerLet(self, node, l);
3953
        }
3954
        case ast::NodeValue::ConstDecl(decl) => {
3955
            // Local constants lower to data declarations and emit no runtime code.
3956
            try registerLocalDataDeclName(self, node);
3957
            try lowerDataDecl(self.low, node, decl.value, true);
3958
        }
3959
        case ast::NodeValue::StaticDecl(decl) => {
3960
            // Local statics lower to data declarations and emit no runtime code.
3961
            try registerLocalDataDeclName(self, node);
3962
            try lowerDataDecl(self.low, node, decl.value, false);
3963
        }
3964
        case ast::NodeValue::If(i) => {
3965
            try lowerIf(self, i);
3966
        }
3967
        case ast::NodeValue::IfLet(i) => {
3968
            try lowerIfLet(self, i);
3969
        }
3970
        case ast::NodeValue::Assign(a) => {
3971
            try lowerAssign(self, node, a);
3972
        }
3973
        case ast::NodeValue::Loop { body } => {
3974
            try lowerLoop(self, body);
3975
        }
3976
        case ast::NodeValue::While(w) => {
3977
            try lowerWhile(self, w);
3978
        }
3979
        case ast::NodeValue::WhileLet(w) => {
3980
            try lowerWhileLet(self, w);
3981
        }
3982
        case ast::NodeValue::For(f) => {
3983
            try lowerFor(self, node, f);
3984
        }
3985
        case ast::NodeValue::Break => {
3986
            try lowerBreak(self);
3987
        }
3988
        case ast::NodeValue::Continue => {
3989
            try lowerContinue(self);
3990
        }
3991
        case ast::NodeValue::Match(m) => {
3992
            try lowerMatch(self, node, m);
3993
        }
3994
        case ast::NodeValue::LetElse(letElse) => {
3995
            try lowerLetElse(self, letElse);
3996
        }
3997
        case ast::NodeValue::ExprStmt(expr) => {
3998
            let _ = try lowerExpr(self, expr);
3999
        }
4000
        case ast::NodeValue::Panic { .. } => {
4001
            emit(self, il::Instr::Unreachable);
4002
        }
4003
        case ast::NodeValue::Assert { condition, .. } => {
4004
            // Lower `assert <cond>` as: `if not cond { unreachable; }`.
4005
            let thenBlock = try createBlock(self, "assert.fail");
4006
            let endBlock = try createBlock(self, "assert.ok");
4007
4008
            // Branch: if condition is `true`, go to `endBlock`; if `false`, go to `thenBlock`.
4009
            try emitCondBranch(self, condition, endBlock, thenBlock);
4010
            try sealBlock(self, thenBlock);
4011
4012
            // Emit `unreachable` in the failure block.
4013
            switchToBlock(self, thenBlock);
4014
            emit(self, il::Instr::Unreachable);
4015
4016
            // Continue after the assert.
4017
            try switchToAndSeal(self, endBlock);
4018
        }
4019
        else => {
4020
            // Treat as expression statement, discard result.
4021
            let _ = try lowerExpr(self, node);
4022
        }
4023
    }
4024
}
4025
4026
/// Lower a code block.
4027
fn lowerBlock(self: *mut FnLowerer, node: *ast::Node) throws (LowerError) {
4028
    let case ast::NodeValue::Block(blk) = node.value else {
4029
        throw LowerError::ExpectedBlock(node);
4030
    };
4031
    let savedVarsLen = enterVarScope(self);
4032
    for stmt in blk.statements {
4033
        try lowerNode(self, stmt);
4034
4035
        // If the statement diverges, further statements are unreachable.
4036
        if blockHasTerminator(self) {
4037
            exitVarScope(self, savedVarsLen);
4038
            return;
4039
        }
4040
    }
4041
    exitVarScope(self, savedVarsLen);
4042
}
4043
4044
///////////////////////////////////////
4045
// Record and Aggregate Type Helpers //
4046
///////////////////////////////////////
4047
4048
/// Extract the nominal record info from a resolver type.
4049
fn recordInfoFromType(typ: resolver::Type) -> ?resolver::RecordType {
4050
    let case resolver::Type::Nominal(resolver::NominalType::Record(recInfo)) = typ
4051
        else return nil;
4052
4053
    return recInfo;
4054
}
4055
4056
/// Extract the nominal union info from a resolver type.
4057
fn unionInfoFromType(typ: resolver::Type) -> ?resolver::UnionType {
4058
    let case resolver::Type::Nominal(resolver::NominalType::Union(unionInfo)) = typ
4059
        else return nil;
4060
4061
    return unionInfo;
4062
}
4063
4064
/// Return the effective type of a node after any coercion applied by
4065
/// the resolver. `lowerExpr` already materializes the coercion in the
4066
/// IL value, so the lowerer must use the post-coercion type when
4067
/// choosing how to compare or store that value.
4068
fn effectiveType(self: *mut FnLowerer, node: *ast::Node) -> resolver::Type throws (LowerError) {
4069
    let ty = try typeOf(self, node);
4070
    if let coerce = resolver::coercionFor(self.low.resolver, node) {
4071
        if let case resolver::Coercion::OptionalLift(optTy) = coerce {
4072
            return optTy;
4073
        }
4074
    }
4075
    return ty;
4076
}
4077
4078
/// Check if a resolver type lowers to an aggregate in memory.
4079
fn isAggregateType(typ: resolver::Type) -> bool {
4080
    match typ {
4081
        case resolver::Type::Slice { .. },
4082
             resolver::Type::TraitObject { .. } => return true,
4083
        case resolver::Type::Optional(resolver::Type::Pointer { .. }) => {
4084
            // Optional pointers are scalar due to NPO.
4085
            return false;
4086
        }
4087
        case resolver::Type::Optional(_) => {
4088
            // All other optionals, including optional slices, are aggregates.
4089
            return true;
4090
        }
4091
        case resolver::Type::Nominal(_) => {
4092
            // Void unions are small enough to pass by value.
4093
            return not resolver::isVoidUnion(typ);
4094
        }
4095
        case resolver::Type::Array(_),
4096
             resolver::Type::Nil => return true,
4097
        else => return false,
4098
    }
4099
}
4100
4101
/// Check if a resolver type is a small aggregate that can be
4102
/// passed or returned by value in a register.
4103
fn isSmallAggregate(typ: resolver::Type) -> bool {
4104
    match typ {
4105
        case resolver::Type::Nominal(_) => {
4106
            if resolver::isVoidUnion(typ) {
4107
                return false;
4108
            }
4109
            let layout = resolver::getTypeLayout(typ);
4110
            return layout.size <= resolver::PTR_SIZE;
4111
        }
4112
        else => return false,
4113
    }
4114
}
4115
4116
/// Whether a function needs a hidden return parameter.
4117
///
4118
/// This is the case for throwing functions, which return a result aggregate,
4119
/// and for functions returning large aggregates that cannot be passed in
4120
/// registers.
4121
fn requiresReturnParam(fnType: *resolver::FnType) -> bool {
4122
    return fnType.throwList.len > 0
4123
        or (isAggregateType(*fnType.returnType)
4124
        and not isSmallAggregate(*fnType.returnType));
4125
}
4126
4127
/// Check if a node is a void union variant literal (e.g. `Color::Red`).
4128
/// If so, returns the variant's tag index. This enables optimized comparisons
4129
/// that only check the tag instead of doing full aggregate comparison.
4130
fn voidVariantIndex(res: *resolver::Resolver, node: *ast::Node) -> ?i64 {
4131
    let data = resolver::nodeData(res, node);
4132
    let sym = data.sym else {
4133
        return nil;
4134
    };
4135
    let case resolver::SymbolData::Variant { type: payloadType, index, .. } = sym.data else {
4136
        return nil;
4137
    };
4138
    // Only void variants can use tag-only comparison.
4139
    if payloadType <> resolver::Type::Void {
4140
        return nil;
4141
    }
4142
    return index as i64;
4143
}
4144
4145
/// Reserve stack storage for a value of the given type.
4146
fn emitReserve(self: *mut FnLowerer, typ: resolver::Type) -> il::Reg throws (LowerError) {
4147
    let layout = resolver::getTypeLayout(typ);
4148
    return emitReserveLayout(self, layout);
4149
}
4150
4151
/// Reserve stack storage with an explicit layout.
4152
fn emitReserveLayout(self: *mut FnLowerer, layout: resolver::Layout) -> il::Reg {
4153
    let dst = nextReg(self);
4154
4155
    emit(self, il::Instr::Reserve {
4156
        dst,
4157
        size: il::Val::Imm(layout.size as i64),
4158
        alignment: layout.alignment,
4159
    });
4160
    return dst;
4161
}
4162
4163
/// Store a value into an address.
4164
fn emitStore(self: *mut FnLowerer, base: il::Reg, offset: i32, typ: resolver::Type, src: il::Val) throws (LowerError) {
4165
    // `undefined` values need no store.
4166
    if let case il::Val::Undef = src {
4167
        return;
4168
    }
4169
    if isAggregateType(typ) {
4170
        let dst = emitPtrOffset(self, base, offset);
4171
        let src = emitValToReg(self, src);
4172
        let layout = resolver::getTypeLayout(typ);
4173
4174
        emit(self, il::Instr::Blit { dst, src, size: il::Val::Imm(layout.size as i64) });
4175
    } else {
4176
        emit(self, il::Instr::Store {
4177
            typ: ilType(self.low, typ),
4178
            src,
4179
            dst: base,
4180
            offset,
4181
        });
4182
    }
4183
}
4184
4185
/// Allocate stack space for a value and store it. Returns a pointer to the value.
4186
fn emitStackVal(self: *mut FnLowerer, typ: resolver::Type, val: il::Val) -> il::Val throws (LowerError) {
4187
    let ptr = try emitReserve(self, typ);
4188
    try emitStore(self, ptr, 0, typ, val);
4189
    return il::Val::Reg(ptr);
4190
}
4191
4192
/// Generic helper to build any tagged aggregate.
4193
/// Reserves space based on the provided layout, stores the tag, and optionally
4194
/// stores the payload value at `valOffset`.
4195
fn buildTagged(
4196
    self: *mut FnLowerer,
4197
    layout: resolver::Layout,
4198
    tag: i64,
4199
    payload: ?il::Val,
4200
    payloadType: resolver::Type,
4201
    tagSize: u32,
4202
    valOffset: i32
4203
) -> il::Val throws (LowerError) {
4204
    let dst = nextReg(self);
4205
    emit(self, il::Instr::Reserve {
4206
        dst,
4207
        size: il::Val::Imm(layout.size as i64),
4208
        alignment: layout.alignment,
4209
    });
4210
    if tagSize == 1 {
4211
        emitStoreW8At(self, il::Val::Imm(tag), dst, TVAL_TAG_OFFSET);
4212
    } else {
4213
        emitStoreW64At(self, il::Val::Imm(tag), dst, TVAL_TAG_OFFSET);
4214
    }
4215
4216
    if let val = payload {
4217
        if payloadType <> resolver::Type::Void {
4218
            try emitStore(self, dst, valOffset, payloadType, val);
4219
        }
4220
    }
4221
    return il::Val::Reg(dst);
4222
}
4223
4224
/// Wrap a value in an optional type.
4225
///
4226
/// For optional pointers (`?*T`), the value is returned as-is since pointers
4227
/// use zero to represent `nil`. For other optionals, builds a tagged aggregate.
4228
/// with the tag set to `1`, and the value as payload.
4229
fn wrapInOptional(self: *mut FnLowerer, val: il::Val, optType: resolver::Type) -> il::Val throws (LowerError) {
4230
    let case resolver::Type::Optional(inner) = optType else {
4231
        throw LowerError::ExpectedOptional;
4232
    };
4233
    // Null-pointer-optimized (NPO) types are used as-is -- valid values are never null.
4234
    if resolver::isNullableType(*inner) {
4235
        return val;
4236
    }
4237
    let layout = resolver::getTypeLayout(optType);
4238
    let valOffset = resolver::getOptionalValOffset(*inner) as i32;
4239
4240
    return try buildTagged(self, layout, 1, val, *inner, 1, valOffset);
4241
}
4242
4243
/// Build a `nil` value for an optional type.
4244
///
4245
/// For optional pointers (`?*T`), returns an immediate `0` (null pointer).
4246
/// For other optionals, builds a tagged aggregate with tag set to `0` (absent).
4247
fn buildNilOptional(self: *mut FnLowerer, optType: resolver::Type) -> il::Val throws (LowerError) {
4248
    let case resolver::Type::Optional(inner) = optType
4249
        else throw LowerError::ExpectedOptional;
4250
    if let case resolver::Type::Pointer { .. } = *inner {
4251
        return il::Val::Imm(0);
4252
    }
4253
    if let case resolver::Type::Slice { item, mutable, .. } = *inner {
4254
        return try buildSliceValue(
4255
            self, item, mutable, il::Val::Imm(0), il::Val::Imm(0), il::Val::Imm(0)
4256
        );
4257
    }
4258
    let valOffset = resolver::getOptionalValOffset(*inner) as i32;
4259
    return try buildTagged(self, resolver::getTypeLayout(optType), 0, nil, *inner, 1, valOffset);
4260
}
4261
4262
/// Build a result value for throwing functions.
4263
fn buildResult(
4264
    self: *mut FnLowerer,
4265
    tag: i64,
4266
    payload: ?il::Val,
4267
    payloadType: resolver::Type
4268
) -> il::Val throws (LowerError) {
4269
    let successType = *self.fnType.returnType;
4270
    let layout = resolver::getResultLayout(
4271
        successType, self.fnType.throwList
4272
    );
4273
    return try buildTagged(self, layout, tag, payload, payloadType, resolver::PTR_SIZE as i32, RESULT_VAL_OFFSET);
4274
}
4275
4276
/// Build a slice aggregate from a data pointer, length and capacity.
4277
fn buildSliceValue(
4278
    self: *mut FnLowerer,
4279
    elemTy: *resolver::Type,
4280
    mutable: bool,
4281
    ptrVal: il::Val,
4282
    lenVal: il::Val,
4283
    capVal: il::Val
4284
) -> il::Val throws (LowerError) {
4285
    let sliceType = resolver::Type::Slice {
4286
        class: types::PointerClass::Unsafe,
4287
        item: elemTy,
4288
        mutable,
4289
    };
4290
    let dst = try emitReserve(self, sliceType);
4291
    let ptrTy = resolver::Type::Pointer {
4292
        class: types::PointerClass::Unsafe,
4293
        target: elemTy,
4294
        mutable,
4295
    };
4296
4297
    try emitStore(self, dst, SLICE_PTR_OFFSET, ptrTy, ptrVal);
4298
    try emitStore(self, dst, SLICE_LEN_OFFSET, resolver::Type::U32, lenVal);
4299
    try emitStore(self, dst, SLICE_CAP_OFFSET, resolver::Type::U32, capVal);
4300
4301
    return il::Val::Reg(dst);
4302
}
4303
4304
/// Build a trait object fat pointer from a data pointer and a v-table.
4305
fn buildTraitObject(
4306
    self: *mut FnLowerer,
4307
    dataVal: il::Val,
4308
    traitInfo: *resolver::TraitType,
4309
    inst: *resolver::InstanceEntry
4310
) -> il::Val throws (LowerError) {
4311
    let vName = vtableName(self.low, inst.moduleId, inst.concreteTypeName, traitInfo.name);
4312
4313
    // Reserve space for the trait object on the stack.
4314
    let slot = emitReserveLayout(self, resolver::Layout {
4315
        size: resolver::PTR_SIZE * 2,
4316
        alignment: resolver::PTR_SIZE,
4317
    });
4318
4319
    // Store data pointer.
4320
    emit(self, il::Instr::Store {
4321
        typ: il::Type::W64,
4322
        src: dataVal,
4323
        dst: slot,
4324
        offset: TRAIT_OBJ_DATA_OFFSET,
4325
    });
4326
4327
    // Store v-table address.
4328
    emit(self, il::Instr::Store {
4329
        typ: il::Type::W64,
4330
        src: il::Val::DataSym(vName),
4331
        dst: slot,
4332
        offset: TRAIT_OBJ_VTABLE_OFFSET,
4333
    });
4334
    return il::Val::Reg(slot);
4335
}
4336
4337
/// Compute a field pointer by adding a byte offset to a base address.
4338
fn emitPtrOffset(self: *mut FnLowerer, base: il::Reg, offset: i32) -> il::Reg {
4339
    if offset == 0 {
4340
        return base;
4341
    }
4342
    let dst = nextReg(self);
4343
4344
    emit(self, il::Instr::BinOp {
4345
        op: il::BinOp::Add,
4346
        typ: il::Type::W64,
4347
        dst,
4348
        a: il::Val::Reg(base),
4349
        b: il::Val::Imm(offset as i64),
4350
    });
4351
    return dst;
4352
}
4353
4354
/// Emit an element address computation for array/slice indexing.
4355
/// Computes: `base + idx * stride`.
4356
fn emitElem(self: *mut FnLowerer, stride: u32, base: il::Reg, idx: il::Val) -> il::Reg {
4357
    // If index is zero, return base directly.
4358
    if idx == il::Val::Imm(0) {
4359
        return base;
4360
    }
4361
    // If stride is `1`, skip the multiply.
4362
    if stride == 1 {
4363
        let dst = nextReg(self);
4364
4365
        emit(self, il::Instr::BinOp {
4366
            op: il::BinOp::Add,
4367
            typ: il::Type::W64,
4368
            dst,
4369
            a: il::Val::Reg(base),
4370
            b: idx
4371
        });
4372
        return dst;
4373
    }
4374
    // Compute `offset = idx * stride`.
4375
    let offset = nextReg(self);
4376
4377
    emit(self, il::Instr::BinOp {
4378
        op: il::BinOp::Mul,
4379
        typ: il::Type::W64,
4380
        dst: offset,
4381
        a: idx,
4382
        b: il::Val::Imm(stride as i64)
4383
    });
4384
    // Compute `dst = base + offset`.
4385
    let dst = nextReg(self);
4386
    emit(self, il::Instr::BinOp {
4387
        op: il::BinOp::Add,
4388
        typ: il::Type::W64,
4389
        dst,
4390
        a: il::Val::Reg(base),
4391
        b: il::Val::Reg(offset)
4392
    });
4393
    return dst;
4394
}
4395
4396
/// Emit a typed binary operation, returning the result as a value.
4397
fn emitTypedBinOp(self: *mut FnLowerer, op: il::BinOp, typ: il::Type, a: il::Val, b: il::Val) -> il::Val {
4398
    let dst = nextReg(self);
4399
    emit(self, il::Instr::BinOp { op, typ, dst, a, b });
4400
    return il::Val::Reg(dst);
4401
}
4402
4403
/// Emit a tag comparison for void variant equality/inequality.
4404
fn emitTagCmp(self: *mut FnLowerer, op: ast::BinaryOp, val: il::Val, tagIdx: i64, valType: resolver::Type) -> il::Val
4405
    throws (LowerError)
4406
{
4407
    let reg = emitValToReg(self, val);
4408
4409
    // For all-void unions, the value *is* the tag, not a pointer.
4410
    let mut tag: il::Val = undefined;
4411
    if resolver::isVoidUnion(valType) {
4412
        set tag = il::Val::Reg(reg);
4413
    } else {
4414
        set tag = loadTag(self, reg, TVAL_TAG_OFFSET, il::Type::W8);
4415
    }
4416
    let binOp = il::BinOp::Eq if op == ast::BinaryOp::Eq else il::BinOp::Ne;
4417
    return emitTypedBinOp(self, binOp, il::Type::W8, tag, il::Val::Imm(tagIdx));
4418
}
4419
4420
/// Logical "and" between two values. Returns the result in a register.
4421
fn emitLogicalAnd(self: *mut FnLowerer, left: ?il::Val, right: il::Val) -> il::Val {
4422
    let prev = left else {
4423
        return right;
4424
    };
4425
    return emitTypedBinOp(self, il::BinOp::And, il::Type::W32, prev, right);
4426
}
4427
4428
//////////////////////////
4429
// Aggregate Comparison //
4430
//////////////////////////
4431
4432
/// Emit an equality test for values at an offset of the given base registers.
4433
fn emitEqAtOffset(
4434
    self: *mut FnLowerer,
4435
    left: il::Reg,
4436
    right: il::Reg,
4437
    offset: i32,
4438
    fieldType: resolver::Type
4439
) -> il::Val throws (LowerError) {
4440
    // For aggregate types, pass offset through and compare recursively.
4441
    if isAggregateType(fieldType) {
4442
        return try lowerAggregateEq(self, fieldType, left, right, offset);
4443
    }
4444
    // For scalar types, load and compare directly.
4445
    let a = emitLoad(self, left, offset, fieldType);
4446
    let b = emitLoad(self, right, offset, fieldType);
4447
    let dst = nextReg(self);
4448
    emit(self, il::Instr::BinOp { op: il::BinOp::Eq, typ: ilType(self.low, fieldType), dst, a, b });
4449
4450
    return il::Val::Reg(dst);
4451
}
4452
4453
/// Compare two record values for equality.
4454
fn lowerRecordEq(
4455
    self: *mut FnLowerer,
4456
    recInfo: resolver::RecordType,
4457
    a: il::Reg,
4458
    b: il::Reg,
4459
    offset: i32
4460
) -> il::Val throws (LowerError) {
4461
    let mut result: ?il::Val = nil;
4462
4463
    for field in recInfo.fields {
4464
        let cmp = try emitEqAtOffset(self, a, b, offset + field.offset, field.fieldType);
4465
4466
        set result = emitLogicalAnd(self, result, cmp);
4467
    }
4468
    if let r = result {
4469
        return r;
4470
    }
4471
    return il::Val::Imm(1);
4472
}
4473
4474
/// Compare two slice values for equality.
4475
fn lowerSliceEq(
4476
    self: *mut FnLowerer,
4477
    elemTy: *resolver::Type,
4478
    mutable: bool,
4479
    a: il::Reg,
4480
    b: il::Reg,
4481
    offset: i32
4482
) -> il::Val throws (LowerError) {
4483
    let ptrTy = resolver::Type::Pointer {
4484
        class: types::PointerClass::Unsafe,
4485
        target: elemTy,
4486
        mutable,
4487
    };
4488
    let ptrEq = try emitEqAtOffset(self, a, b, offset + SLICE_PTR_OFFSET, ptrTy);
4489
    let lenEq = try emitEqAtOffset(self, a, b, offset + SLICE_LEN_OFFSET, resolver::Type::U32);
4490
4491
    return emitTypedBinOp(self, il::BinOp::And, il::Type::W32, ptrEq, lenEq);
4492
}
4493
4494
/// Compare two optional aggregate values for equality.
4495
///
4496
/// Two optionals are equal when their tags match and either both are `nil` or
4497
/// their payloads are equal.
4498
///
4499
/// For inner types that are safe to compare even when uninitialised, we use a
4500
/// branchless formulation: `tagEq AND (tagNil OR payloadEq)`
4501
///
4502
/// For inner types that may contain uninitialized data when `nil` (unions,
4503
/// nested optionals), the payload comparison is guarded behind a branch
4504
/// so that `nil` payloads are never inspected.
4505
fn lowerOptionalEq(
4506
    self: *mut FnLowerer,
4507
    inner: resolver::Type,
4508
    a: il::Reg,
4509
    b: il::Reg,
4510
    offset: i32
4511
) -> il::Val throws (LowerError) {
4512
    let valOffset = resolver::getOptionalValOffset(inner) as i32;
4513
4514
    // Load tags.
4515
    let tagA = loadTag(self, a, offset + TVAL_TAG_OFFSET, il::Type::W8);
4516
    let tagB = loadTag(self, b, offset + TVAL_TAG_OFFSET, il::Type::W8);
4517
4518
    // For simple inner types (no unions/nested optionals), use branchless comparison.
4519
    // Unions and nested optionals may contain uninitialized payload bytes
4520
    // when nil, so they need a guarded comparison.
4521
    let isUnion = unionInfoFromType(inner) <> nil;
4522
    let mut isOptional = false;
4523
    if let case resolver::Type::Optional(_) = inner {
4524
        set isOptional = true;
4525
    }
4526
    if not isUnion and not isOptional {
4527
        let tagEq = emitTypedBinOp(self, il::BinOp::Eq, il::Type::W8, tagA, tagB);
4528
        let tagNil = emitTypedBinOp(self, il::BinOp::Eq, il::Type::W8, tagA, il::Val::Imm(0));
4529
        let payloadEq = try emitEqAtOffset(self, a, b, offset + valOffset, inner);
4530
4531
        return emitTypedBinOp(self, il::BinOp::And, il::Type::W32, tagEq,
4532
            emitTypedBinOp(self, il::BinOp::Or, il::Type::W32, tagNil, payloadEq));
4533
    }
4534
4535
    // For complex inner types, use branching comparison to avoid inspecting
4536
    // uninitialized payload bytes.
4537
    let resultReg = nextReg(self);
4538
    let mergeBlock = try createBlockWithParam(self, "opteq#merge", il::Param {
4539
        value: resultReg, type: il::Type::W8
4540
    });
4541
    let nilCheck = try createBlock(self, "opteq#nil");
4542
    let payloadCmp = try createBlock(self, "opteq#payload");
4543
4544
    let falseArgs = try allocVal(self, il::Val::Imm(0));
4545
    let trueArgs = try allocVal(self, il::Val::Imm(1));
4546
4547
    // Check if tags differ.
4548
    emit(self, il::Instr::Br {
4549
        op: il::CmpOp::Eq, typ: il::Type::W8, a: tagA, b: tagB,
4550
        thenTarget: *nilCheck, thenArgs: &mut [],
4551
        elseTarget: *mergeBlock, elseArgs: falseArgs,
4552
    });
4553
    addPredecessor(self, nilCheck, currentBlock(self));
4554
    addPredecessor(self, mergeBlock, currentBlock(self));
4555
4556
    // Check if both are `nil`.
4557
    try switchToAndSeal(self, nilCheck);
4558
    emit(self, il::Instr::Br {
4559
        op: il::CmpOp::Ne, typ: il::Type::W8, a: tagA, b: il::Val::Imm(0),
4560
        thenTarget: *payloadCmp, thenArgs: &mut [],
4561
        elseTarget: *mergeBlock, elseArgs: trueArgs,
4562
    });
4563
    addPredecessor(self, payloadCmp, currentBlock(self));
4564
    addPredecessor(self, mergeBlock, currentBlock(self));
4565
4566
    // Both are non-`nil`, compare payloads.
4567
    try switchToAndSeal(self, payloadCmp);
4568
    let payloadEq = try emitEqAtOffset(self, a, b, offset + valOffset, inner);
4569
    try emitJmpWithArg(self, mergeBlock, payloadEq);
4570
    try switchToAndSeal(self, mergeBlock);
4571
4572
    return il::Val::Reg(resultReg);
4573
}
4574
4575
/// Compare two union values for equality.
4576
///
4577
/// Two unions are equal iff their tags match and, for non-void variants,
4578
/// their payloads are also equal. The comparison proceeds as follows.
4579
///
4580
/// First, compare the tags. If they differ, the unions are not equal, so
4581
/// jump to the merge block with `false`. If they match, jump to the tag
4582
/// block to determine which variant we're dealing with.
4583
///
4584
/// The tag block uses a switch on the tag value to dispatch to the appropriate
4585
/// comparison block. Void variants jump directly to merge with `true`.
4586
/// Non-void variants each have their own payload block that compares the
4587
/// payload and jumps to the merge block with the result.
4588
///
4589
/// The merge block collects results from all paths via a block parameter
4590
/// and returns the final equality result.
4591
///
4592
/// For all-void unions, we skip the control flow entirely and just compare
4593
/// the tags directly.
4594
///
4595
/// TODO: Could be optimized to branchless when all non-void variants share
4596
/// the same payload type: `tagEq AND (isVoidVariant OR payloadEq)`.
4597
fn lowerUnionEq(
4598
    self: *mut FnLowerer,
4599
    unionInfo: resolver::UnionType,
4600
    a: il::Reg,
4601
    b: il::Reg,
4602
    offset: i32
4603
) -> il::Val throws (LowerError) {
4604
    // Compare tags.
4605
    let tagA = loadTag(self, a, offset + TVAL_TAG_OFFSET, il::Type::W8);
4606
    let tagB = loadTag(self, b, offset + TVAL_TAG_OFFSET, il::Type::W8);
4607
4608
    // Fast path: all-void union just needs tag comparison.
4609
    if unionInfo.isAllVoid {
4610
        return emitTypedBinOp(self, il::BinOp::Eq, il::Type::W8, tagA, tagB);
4611
    }
4612
    // Holds the equality result.
4613
    let resultReg = nextReg(self);
4614
4615
    // Where control flow continues after equality check is done. Receives
4616
    // the result as a parameter.
4617
    let mergeBlock = try createBlockWithParam(self, "eq#merge", il::Param {
4618
        value: resultReg, type: il::Type::W8
4619
    });
4620
    // Where we switch on the tag to compare payloads.
4621
    let tagBlock = try createBlock(self, "eq#tag");
4622
4623
    // Compare tags: if they differ, jump to merge with `false`; otherwise check payloads.
4624
    let falseArgs = try allocVal(self, il::Val::Imm(0));
4625
4626
    assert tagBlock <> mergeBlock;
4627
4628
    // TODO: Use the helper once the compiler supports more than eight function params.
4629
    emit(self, il::Instr::Br {
4630
        op: il::CmpOp::Eq, typ: il::Type::W8, a: tagA, b: tagB,
4631
        thenTarget: *tagBlock, thenArgs: &mut [],
4632
        elseTarget: *mergeBlock, elseArgs: falseArgs,
4633
    });
4634
    addPredecessor(self, tagBlock, currentBlock(self));
4635
    addPredecessor(self, mergeBlock, currentBlock(self));
4636
4637
    // Create comparison blocks for each non-void variant and build switch cases.
4638
    // Void variants jump directly to merge with `true`.
4639
    let trueArgs = try allocVal(self, il::Val::Imm(1));
4640
    let cases = try! alloc::allocSlice(
4641
        self.low.fnArena, @sizeOf(il::SwitchCase), @alignOf(il::SwitchCase), unionInfo.variants.len as u32
4642
    ) as *mut [il::SwitchCase];
4643
4644
    let mut caseBlocks: [?BlockId; resolver::MAX_UNION_VARIANTS] = undefined;
4645
    for variant, i in unionInfo.variants {
4646
        if variant.valueType == resolver::Type::Void {
4647
            set cases[i] = il::SwitchCase {
4648
                value: i as i64,
4649
                target: *mergeBlock,
4650
                args: trueArgs
4651
            };
4652
            set caseBlocks[i] = nil;
4653
        } else {
4654
            let payloadBlock = try createBlock(self, "eq#payload");
4655
            set cases[i] = il::SwitchCase {
4656
                value: i as i64,
4657
                target: *payloadBlock,
4658
                args: &mut []
4659
            };
4660
            set caseBlocks[i] = payloadBlock;
4661
        }
4662
    }
4663
4664
    // Emit switch in @tag block. Default arm is unreachable since we cover all variants.
4665
    let unreachableBlock = try createBlock(self, "eq#unreachable");
4666
    try switchToAndSeal(self, tagBlock);
4667
    emit(self, il::Instr::Switch {
4668
        val: tagA,
4669
        defaultTarget: *unreachableBlock,
4670
        defaultArgs: &mut [],
4671
        cases
4672
    });
4673
4674
    // Add predecessor edges for switch targets.
4675
    addPredecessor(self, unreachableBlock, tagBlock);
4676
    for i in 0..unionInfo.variants.len {
4677
        if let caseBlock = caseBlocks[i] {
4678
            addPredecessor(self, caseBlock, tagBlock);
4679
        } else {
4680
            addPredecessor(self, mergeBlock, tagBlock);
4681
        }
4682
    }
4683
    let valOffset = unionInfo.valOffset as i32;
4684
4685
    // Emit payload comparison blocks for non-void variants.
4686
    for variant, i in unionInfo.variants {
4687
        if let caseBlock = caseBlocks[i] {
4688
            try switchToAndSeal(self, caseBlock);
4689
            let payloadEq = try emitEqAtOffset(
4690
                self, a, b, offset + valOffset, variant.valueType
4691
            );
4692
            try emitJmpWithArg(self, mergeBlock, payloadEq);
4693
        }
4694
    }
4695
    // Emit unreachable block.
4696
    try switchToAndSeal(self, unreachableBlock);
4697
    emit(self, il::Instr::Unreachable);
4698
4699
    try switchToAndSeal(self, mergeBlock);
4700
    return il::Val::Reg(resultReg);
4701
}
4702
4703
/// Compare two array values for equality, element by element.
4704
fn lowerArrayEq(
4705
    self: *mut FnLowerer,
4706
    arr: resolver::ArrayType,
4707
    a: il::Reg,
4708
    b: il::Reg,
4709
    offset: i32
4710
) -> il::Val throws (LowerError) {
4711
    let elemLayout = resolver::getTypeLayout(*arr.item);
4712
    let stride = elemLayout.size as i32;
4713
    let mut result: ?il::Val = nil;
4714
4715
    for i in 0..arr.length {
4716
        let elemOffset = offset + (i as i32) * stride;
4717
        let cmp = try emitEqAtOffset(self, a, b, elemOffset, *arr.item);
4718
        set result = emitLogicalAnd(self, result, cmp);
4719
    }
4720
    if let r = result {
4721
        return r;
4722
    }
4723
    // Empty arrays are always equal.
4724
    return il::Val::Imm(1);
4725
}
4726
4727
/// Compare two aggregate values for equality.
4728
fn lowerAggregateEq(
4729
    self: *mut FnLowerer,
4730
    typ: resolver::Type,
4731
    a: il::Reg,
4732
    b: il::Reg,
4733
    offset: i32
4734
) -> il::Val throws (LowerError) {
4735
    match typ {
4736
        case resolver::Type::Slice { item, mutable, .. } =>
4737
            return try lowerSliceEq(self, item, mutable, a, b, offset),
4738
        case resolver::Type::Optional(inner) => {
4739
            if let case resolver::Type::Slice { item, mutable, .. } = *inner {
4740
                // Optional slices use null pointer optimization.
4741
                return try lowerSliceEq(self, item, mutable, a, b, offset);
4742
            }
4743
            return try lowerOptionalEq(self, *inner, a, b, offset);
4744
        }
4745
        case resolver::Type::Array(arr) =>
4746
            return try lowerArrayEq(self, arr, a, b, offset),
4747
        case resolver::Type::Nominal(resolver::NominalType::Record(recInfo)) =>
4748
            return try lowerRecordEq(self, recInfo, a, b, offset),
4749
        case resolver::Type::Nominal(resolver::NominalType::Union(unionInfo)) =>
4750
            return try lowerUnionEq(self, unionInfo, a, b, offset),
4751
        else => {
4752
            let recInfo = recordInfoFromType(typ) else {
4753
                throw LowerError::ExpectedRecord;
4754
            };
4755
            return try lowerRecordEq(self, recInfo, a, b, offset);
4756
        }
4757
    }
4758
}
4759
4760
/// Lower a record literal expression. Handles both plain records and union variant
4761
/// record literals like `Union::Variant { field: value }`.
4762
fn lowerRecordLit(self: *mut FnLowerer, node: *ast::Node, lit: ast::RecordLit) -> il::Val throws (LowerError) {
4763
    let typ = try typeOf(self, node);
4764
    match typ {
4765
        case resolver::Type::Nominal(resolver::NominalType::Record(recInfo)) => {
4766
            let dst = try emitReserve(self, typ);
4767
            try lowerRecordFields(self, dst, &recInfo, lit.fields, 0);
4768
4769
            return il::Val::Reg(dst);
4770
        }
4771
        case resolver::Type::Nominal(resolver::NominalType::Union(_)) => {
4772
            let typeName = lit.typeName else {
4773
                throw LowerError::ExpectedVariant;
4774
            };
4775
            let sym = try symOf(self, typeName);
4776
            let case resolver::SymbolData::Variant { type: payloadType, index, .. } = sym.data else {
4777
                throw LowerError::ExpectedVariant;
4778
            };
4779
            let recInfo = recordInfoFromType(payloadType) else {
4780
                throw LowerError::ExpectedRecord;
4781
            };
4782
            let unionInfo = unionInfoFromType(typ) else {
4783
                throw LowerError::MissingMetadata;
4784
            };
4785
            let valOffset = unionInfo.valOffset as i32;
4786
            let dst = try emitReserve(self, typ);
4787
4788
            emitStoreW8At(self, il::Val::Imm(index as i64), dst, TVAL_TAG_OFFSET);
4789
            try lowerRecordFields(self, dst, &recInfo, lit.fields, valOffset);
4790
4791
            return il::Val::Reg(dst);
4792
        }
4793
        else => throw LowerError::UnexpectedType(&typ),
4794
    }
4795
}
4796
4797
/// Lower fields of a record literal into a destination register.
4798
/// The `offset` is added to each field's offset when storing.
4799
fn lowerRecordFields(
4800
    self: *mut FnLowerer,
4801
    dst: il::Reg,
4802
    recInfo: *resolver::RecordType,
4803
    fields: *mut [*ast::Node],
4804
    offset: i32
4805
) throws (LowerError) {
4806
    for fieldNode, i in fields {
4807
        let case ast::NodeValue::RecordLitField(field) = fieldNode.value else {
4808
            throw LowerError::UnexpectedNodeValue(fieldNode);
4809
        };
4810
        let mut fieldIdx: u32 = i;
4811
        if recInfo.labeled {
4812
            let idx = resolver::recordFieldIndexFor(self.low.resolver, fieldNode) else {
4813
                throw LowerError::MissingMetadata;
4814
            };
4815
            set fieldIdx = idx;
4816
        }
4817
        // Skip `undefined` fields, they need no initialization.
4818
        // Emitting a blit from an uninitialised reserve produces a
4819
        // phantom SSA source value that the backend cannot handle.
4820
        if not isUndef(field.value) {
4821
            let fieldTy = recInfo.fields[fieldIdx].fieldType;
4822
            let fieldVal = try lowerExpr(self, field.value);
4823
            try emitStore(self, dst, offset + recInfo.fields[fieldIdx].offset, fieldTy, fieldVal);
4824
        }
4825
    }
4826
}
4827
4828
/// Lower an unlabeled record constructor call.
4829
fn lowerRecordCtor(self: *mut FnLowerer, nominal: *resolver::NominalType, args: *mut [*ast::Node]) -> il::Val throws (LowerError) {
4830
    let case resolver::NominalType::Record(recInfo) = *nominal else {
4831
        throw LowerError::ExpectedRecord;
4832
    };
4833
    let typ = resolver::Type::Nominal(nominal);
4834
    let dst = try emitReserve(self, typ);
4835
4836
    for argNode, i in args {
4837
        // Skip `undefined` arguments.
4838
        if not isUndef(argNode) {
4839
            let fieldTy = recInfo.fields[i].fieldType;
4840
            let argVal = try lowerExpr(self, argNode);
4841
            try emitStore(self, dst, recInfo.fields[i].offset, fieldTy, argVal);
4842
        }
4843
    }
4844
    return il::Val::Reg(dst);
4845
}
4846
4847
/// Lower an array literal expression like `[1, 2, 3]`.
4848
fn lowerArrayLit(self: *mut FnLowerer, node: *ast::Node, elements: *mut [*ast::Node]) -> il::Val
4849
    throws (LowerError)
4850
{
4851
    let typ = try typeOf(self, node);
4852
    let case resolver::Type::Array(arrInfo) = typ else {
4853
        throw LowerError::ExpectedArray;
4854
    };
4855
    let elemTy = *arrInfo.item;
4856
    let elemLayout = resolver::getTypeLayout(elemTy);
4857
    let dst = try emitReserve(self, typ);
4858
4859
    for elemNode, i in elements {
4860
        let elemVal = try lowerExpr(self, elemNode);
4861
        let offset = i * elemLayout.size;
4862
4863
        try emitStore(self, dst, offset as i32, elemTy, elemVal);
4864
    }
4865
    return il::Val::Reg(dst);
4866
}
4867
4868
/// Lower an array repeat literal expression like `[42; 3]`.
4869
/// Unrolls the initialization at compile time.
4870
// TODO: Beyond a certain length, lower this to a loop.
4871
fn lowerArrayRepeatLit(self: *mut FnLowerer, node: *ast::Node, repeat: ast::ArrayRepeatLit) -> il::Val
4872
    throws (LowerError)
4873
{
4874
    let typ = try typeOf(self, node);
4875
    let case resolver::Type::Array(arrInfo) = typ else {
4876
        throw LowerError::ExpectedArray;
4877
    };
4878
    let elemTy = *arrInfo.item;
4879
    let length = arrInfo.length;
4880
    let elemLayout = resolver::getTypeLayout(elemTy);
4881
    let dst = try emitReserve(self, typ);
4882
4883
    // Evaluate the repeated item once.
4884
    let repeatVal = try lowerExpr(self, repeat.item);
4885
4886
    // Unroll: store at each offset.
4887
    for i in 0..length {
4888
        let offset = i * elemLayout.size;
4889
        try emitStore(self, dst, offset as i32, elemTy, repeatVal);
4890
    }
4891
    return il::Val::Reg(dst);
4892
}
4893
4894
/// Lower a union constructor call like `Union::Variant(...)`.
4895
fn lowerUnionCtor(self: *mut FnLowerer, node: *ast::Node, sym: *mut resolver::Symbol, call: ast::Call) -> il::Val
4896
    throws (LowerError)
4897
{
4898
    let unionTy = try typeOf(self, node);
4899
    let case resolver::SymbolData::Variant { type: payloadType, index, .. } = sym.data else {
4900
        throw LowerError::ExpectedVariant;
4901
    };
4902
    let unionInfo = unionInfoFromType(unionTy) else {
4903
        throw LowerError::MissingMetadata;
4904
    };
4905
    let valOffset = unionInfo.valOffset as i32;
4906
    let mut payloadVal: ?il::Val = nil;
4907
    if payloadType <> resolver::Type::Void {
4908
        let case resolver::Type::Nominal(payloadNominal) = payloadType else {
4909
            throw LowerError::MissingMetadata;
4910
        };
4911
        set payloadVal = try lowerRecordCtor(self, payloadNominal, call.args);
4912
    }
4913
    return try buildTagged(self, resolver::getTypeLayout(unionTy), index as i64, payloadVal, payloadType, 1, valOffset);
4914
}
4915
4916
/// Lower a field access into a pointer to the field.
4917
fn lowerFieldRef(self: *mut FnLowerer, access: ast::Access) -> FieldRef throws (LowerError) {
4918
    let parentTy = try typeOf(self, access.parent);
4919
    let subjectTy = resolver::autoDeref(parentTy);
4920
    let fieldIdx = resolver::recordFieldIndexFor(self.low.resolver, access.child) else {
4921
        throw LowerError::MissingMetadata;
4922
    };
4923
    let fieldInfo = resolver::getRecordField(subjectTy, fieldIdx) else {
4924
        throw LowerError::FieldNotFound;
4925
    };
4926
    let baseVal = try lowerExpr(self, access.parent);
4927
    let baseReg = emitValToReg(self, baseVal);
4928
4929
    return FieldRef {
4930
        base: baseReg,
4931
        offset: fieldInfo.offset,
4932
        fieldType: fieldInfo.fieldType,
4933
    };
4934
}
4935
4936
/// Lower a field access expression.
4937
fn lowerFieldAccess(self: *mut FnLowerer, access: ast::Access) -> il::Val throws (LowerError) {
4938
    let fieldRef = try lowerFieldRef(self, access);
4939
    return emitRead(self, fieldRef.base, fieldRef.offset, fieldRef.fieldType);
4940
}
4941
4942
/// Compute data pointer and element count for a range into a container.
4943
/// Used by both slice range expressions (`&a[start..end]`) and slice
4944
/// assignments (`a[start..end] = value`).
4945
fn resolveSliceRangePtr(
4946
    self: *mut FnLowerer,
4947
    container: *ast::Node,
4948
    range: ast::Range,
4949
    info: resolver::SliceRangeInfo
4950
) -> SliceRangeResult throws (LowerError) {
4951
    let baseVal = try lowerExpr(self, container);
4952
    let baseReg = emitValToReg(self, baseVal);
4953
4954
    // Extract data pointer and container length.
4955
    let mut dataReg = baseReg;
4956
    let mut containerLen: il::Val = undefined;
4957
    if let cap = info.capacity { // Slice from array.
4958
        set containerLen = il::Val::Imm(cap as i64);
4959
    } else { // Slice from slice.
4960
        set dataReg = loadSlicePtr(self, baseReg);
4961
        set containerLen = loadSliceLen(self, baseReg);
4962
    }
4963
4964
    // Compute range bounds.
4965
    let mut startVal: il::Val = il::Val::Imm(0);
4966
    if let start = range.start {
4967
        set startVal = try lowerExpr(self, start);
4968
    }
4969
    let mut endVal = containerLen;
4970
    if let end = range.end {
4971
        set endVal = try lowerExpr(self, end);
4972
    }
4973
4974
    // Runtime slice bounds checks for dynamic range expressions.
4975
    if not isLtEq(startVal, containerLen) {
4976
        try emitTrapIfLt(self, il::Type::W32, containerLen, startVal);
4977
    }
4978
    if not isLtEq(endVal, containerLen) {
4979
        try emitTrapIfLt(self, il::Type::W32, containerLen, endVal);
4980
    }
4981
    if startVal <> il::Val::Imm(0) and endVal <> containerLen and not isLtEq(startVal, endVal) {
4982
        try emitTrapIfLt(self, il::Type::W32, endVal, startVal);
4983
    }
4984
4985
    // If the start value is known to be zero, the count is just the end
4986
    // value. Otherwise, we have to compute it.
4987
    let mut count = endVal;
4988
4989
    // Only compute range offset and count if the start value is not
4990
    // statically known to be zero.
4991
    if startVal <> il::Val::Imm(0) {
4992
        // Offset the data pointer by the start value.
4993
        set dataReg = emitElem(
4994
            self, resolver::getTypeLayout(*info.itemType).size, dataReg, startVal
4995
        );
4996
        // Compute the count as `end - start`.
4997
        let lenReg = nextReg(self);
4998
        emit(self, il::Instr::BinOp {
4999
            op: il::BinOp::Sub,
5000
            typ: il::Type::W32,
5001
            dst: lenReg,
5002
            a: endVal,
5003
            b: startVal,
5004
        });
5005
        set count = il::Val::Reg(lenReg);
5006
    }
5007
    return SliceRangeResult { dataReg, count };
5008
}
5009
5010
/// Lower a slice range expression into a slice header value.
5011
fn lowerSliceRange(
5012
    self: *mut FnLowerer,
5013
    container: *ast::Node,
5014
    range: ast::Range,
5015
    sliceNode: *ast::Node
5016
) -> il::Val throws (LowerError) {
5017
    let info = resolver::sliceRangeInfoFor(self.low.resolver, sliceNode) else {
5018
        throw LowerError::MissingMetadata;
5019
    };
5020
    let r = try resolveSliceRangePtr(self, container, range, info);
5021
    return try buildSliceValue(
5022
        self, info.itemType, info.mutable, il::Val::Reg(r.dataReg), r.count, r.count
5023
    );
5024
}
5025
5026
/// Lower an address-of (`&x`) expression.
5027
fn lowerAddressOf(self: *mut FnLowerer, node: *ast::Node, addr: ast::AddressOf) -> il::Val throws (LowerError) {
5028
    // Handle subscript: `&ary[i]` or `&ary[start..end]`.
5029
    if let case ast::NodeValue::Subscript { container, index } = addr.target.value {
5030
        if let case ast::NodeValue::Range(range) = index.value {
5031
            return try lowerSliceRange(self, container, range, node);
5032
        }
5033
        let result = try lowerElemPtr(self, container, index);
5034
5035
        return il::Val::Reg(result.elemReg);
5036
    }
5037
    // Handle field address: `&x.field`.
5038
    if let case ast::NodeValue::FieldAccess(access) = addr.target.value {
5039
        let fieldRef = try lowerFieldRef(self, access);
5040
        let ptr = emitPtrOffset(self, fieldRef.base, fieldRef.offset);
5041
5042
        return il::Val::Reg(ptr);
5043
    }
5044
    // Handle variable address: `&x`
5045
    if let case ast::NodeValue::Ident(_) = addr.target.value {
5046
        if let v = lookupLocalVar(self, addr.target) {
5047
            let val = try useVar(self, v);
5048
            let typ = try typeOf(self, addr.target);
5049
            // For aggregates, the value is already a pointer.
5050
            if isAggregateType(typ) {
5051
                return val;
5052
            }
5053
            // For scalars, if we've already materialized a stack slot for this
5054
            // variable, the SSA value is that slot pointer.
5055
            if self.vars[*v].addressTaken {
5056
                // Already address-taken; return existing stack pointer.
5057
                return val;
5058
            }
5059
            // Materialize a stack slot using the declaration's resolved
5060
            // layout so `align(N)` on locals is honored.
5061
            let layout = resolver::getLayout(self.low.resolver, addr.target, typ);
5062
            let slot = emitReserveLayout(self, layout);
5063
            try emitStore(self, slot, 0, typ, val);
5064
            let stackVal = il::Val::Reg(slot);
5065
5066
            set self.vars[*v].addressTaken = true;
5067
            defVar(self, v, stackVal);
5068
5069
            return stackVal;
5070
        }
5071
        // Fall back to symbol lookup for constants/statics.
5072
        if let sym = resolver::nodeData(self.low.resolver, addr.target).sym {
5073
            return il::Val::Reg(emitDataAddr(self, sym));
5074
        } else {
5075
            throw LowerError::MissingSymbol(node);
5076
        }
5077
    }
5078
    // Handle dereference address: `&(*ptr) = ptr`.
5079
    if let case ast::NodeValue::Deref(target) = addr.target.value {
5080
        return try lowerExpr(self, target);
5081
    }
5082
    // Array literals become slices when their address is taken.
5083
    match addr.target.value {
5084
        case ast::NodeValue::ArrayLit(_),
5085
             ast::NodeValue::ArrayRepeatLit(_) =>
5086
        {
5087
            return try lowerArrayLiteralSlice(self, node, addr.target);
5088
        }
5089
        else => {}
5090
    }
5091
    throw LowerError::UnexpectedNodeValue(addr.target);
5092
}
5093
5094
/// Lower an addressed array literal as a slice.
5095
fn lowerArrayLiteralSlice(
5096
    self: *mut FnLowerer,
5097
    sliceNode: *ast::Node,
5098
    arrayNode: *ast::Node
5099
) -> il::Val throws (LowerError) {
5100
    let sliceTy = try typeOf(self, sliceNode);
5101
    let case resolver::Type::Slice { item, mutable, .. } = sliceTy else {
5102
        throw LowerError::UnexpectedType(&sliceTy);
5103
    };
5104
    let arrayTy = try typeOf(self, arrayNode);
5105
    let case resolver::Type::Array(arrayInfo) = arrayTy else {
5106
        throw LowerError::ExpectedArray;
5107
    };
5108
    let length = arrayInfo.length;
5109
    if length == 0 {
5110
        return try buildSliceValue(
5111
            self, item, mutable, il::Val::Imm(0), il::Val::Imm(0), il::Val::Imm(0)
5112
        );
5113
    }
5114
    if resolver::isConstExpr(self.low.resolver, arrayNode) {
5115
        let mut b = dataBuilder(self.low.allocator);
5116
        match arrayNode.value {
5117
            case ast::NodeValue::ArrayLit(elements) =>
5118
                try lowerConstArrayLitInto(self.low, elements, arrayTy, self.fnName, &mut b),
5119
            case ast::NodeValue::ArrayRepeatLit(repeat) =>
5120
                try lowerConstArrayRepeatInto(self.low, repeat, arrayTy, self.fnName, &mut b),
5121
            else => throw LowerError::UnexpectedNodeValue(arrayNode),
5122
        }
5123
        let result = dataBuilderFinish(&b);
5124
        let alignment = resolver::getTypeLayout(*item).alignment;
5125
        return try lowerConstDataAsSlice(
5126
            self, result.values, alignment, not mutable,
5127
            item, mutable, length
5128
        );
5129
    }
5130
    let data = try lowerExpr(self, arrayNode);
5131
    let count = il::Val::Imm(length as i64);
5132
    return try buildSliceValue(self, item, mutable, data, count, count);
5133
}
5134
5135
/// Lower the common element pointer computation for subscript operations.
5136
/// Handles both arrays and slices by resolving the container type, extracting
5137
/// the data pointer (for slices), and emitting an [`il::Instr::Elem`] to compute
5138
/// the element address.
5139
fn lowerElemPtr(
5140
    self: *mut FnLowerer, container: *ast::Node, index: *ast::Node
5141
) -> ElemPtrResult throws (LowerError) {
5142
    let containerTy = try typeOf(self, container);
5143
    let subjectTy = resolver::autoDeref(containerTy);
5144
    let baseVal = try lowerExpr(self, container);
5145
    let indexVal = try lowerExpr(self, index);
5146
    let baseReg = emitValToReg(self, baseVal);
5147
5148
    let mut dataReg = baseReg;
5149
    let mut elemType: resolver::Type = undefined;
5150
5151
    match subjectTy {
5152
        case resolver::Type::Slice { item, .. } => {
5153
            set elemType = *item;
5154
            let sliceLen = loadSliceLen(self, baseReg);
5155
            // Runtime safety check: index must be strictly less than slice length.
5156
            try emitTrapUnlessCmp(self, il::CmpOp::Ult, il::Type::W32, indexVal, sliceLen);
5157
5158
            set dataReg = loadSlicePtr(self, baseReg);
5159
        }
5160
        case resolver::Type::Array(arrInfo) => {
5161
            set elemType = *arrInfo.item;
5162
            // Runtime safety check: index must be strictly less than array length.
5163
            // Skip when the index is a compile-time constant, since we check
5164
            // that in the resolver.
5165
            if not resolver::isConstExpr(self.low.resolver, index) {
5166
                let arrLen = il::Val::Imm(arrInfo.length as i64);
5167
                try emitTrapUnlessCmp(self, il::CmpOp::Ult, il::Type::W32, indexVal, arrLen);
5168
            }
5169
        }
5170
        else => throw LowerError::ExpectedSliceOrArray,
5171
    }
5172
    let elemLayout = resolver::getTypeLayout(elemType);
5173
    let elemReg = emitElem(self, elemLayout.size, dataReg, indexVal);
5174
5175
    return ElemPtrResult { elemReg, elemType };
5176
}
5177
5178
/// Lower a dereference expression.
5179
/// Handles both pointer deref (`*ptr`) and record deref (`*r` on single-field
5180
/// unlabeled record). Both read at offset 0 using the resolver-assigned type.
5181
fn lowerDeref(self: *mut FnLowerer, node: *ast::Node, target: *ast::Node) -> il::Val throws (LowerError) {
5182
    let type = try typeOf(self, node);
5183
    let ptrVal = try lowerExpr(self, target);
5184
    let ptrReg = emitValToReg(self, ptrVal);
5185
5186
    return emitRead(self, ptrReg, 0, type);
5187
}
5188
5189
/// Lower a subscript expression.
5190
fn lowerSubscript(self: *mut FnLowerer, node: *ast::Node, container: *ast::Node, index: *ast::Node) -> il::Val
5191
    throws (LowerError)
5192
{
5193
    if let case ast::NodeValue::Range(_) = index.value {
5194
        panic "lowerSubscript: range subscript must use address-of (&)";
5195
    }
5196
    let result = try lowerElemPtr(self, container, index);
5197
5198
    return emitRead(self, result.elemReg, 0, result.elemType);
5199
}
5200
5201
/// Lower a let binding.
5202
fn lowerLet(self: *mut FnLowerer, node: *ast::Node, l: ast::Let) throws (LowerError) {
5203
    // Evaluate value.
5204
    let val = try lowerExpr(self, l.value);
5205
    // Handle placeholder pattern: `let _ = expr;`
5206
    if let case ast::NodeValue::Placeholder = l.ident.value {
5207
        return;
5208
    }
5209
    let case ast::NodeValue::Ident(name) = l.ident.value else {
5210
        throw LowerError::ExpectedIdentifier;
5211
    };
5212
    let typ = try typeOf(self, l.value);
5213
    let ilType = ilType(self.low, typ);
5214
    let mut varVal = val;
5215
5216
    // Aggregates with persistent storage need a local copy to avoid aliasing.
5217
    // Temporaries such as literals or call results can be adopted directly.
5218
    // This is because aggregates are represented as memory addresses
5219
    // internally, even though they have value semantics, so without an explicit
5220
    // copy, only the address is is written. Function calls on the other hand
5221
    // reserve their own local stack space, so copying would be redundant.
5222
    // Void variant literals (e.g. `Option::None`) use scope access syntax and
5223
    // are flagged as place expressions, but they are freshly constructed
5224
    // temporaries with no persistent storage.
5225
    if isAggregateType(typ) and
5226
        ast::isPlaceExpr(l.value) and
5227
        voidVariantIndex(self.low.resolver, l.value) == nil {
5228
        set varVal = try emitStackVal(self, typ, val);
5229
    }
5230
5231
    // If the resolver determined that this variable's address is taken
5232
    // anywhere in the function, allocate a stack slot immediately so the
5233
    // SSA value is always a pointer. This avoids mixing integer and pointer
5234
    // values in loop phis when `&var` or `&mut var` appears inside a loop.
5235
    if not isAggregateType(typ) {
5236
        if let sym = resolver::nodeData(self.low.resolver, node).sym {
5237
            if let case resolver::SymbolData::Value { addressTaken, .. } = sym.data; addressTaken {
5238
                let layout = resolver::getLayout(self.low.resolver, node, typ);
5239
                let slot = emitReserveLayout(self, layout);
5240
                try emitStore(self, slot, 0, typ, varVal);
5241
5242
                let v = newVar(self, name, ilType, l.mutable, il::Val::Reg(slot));
5243
                set self.vars[*v].addressTaken = true;
5244
5245
                return;
5246
            }
5247
        }
5248
    }
5249
    let _ = newVar(self, name, ilType, l.mutable, varVal);
5250
}
5251
5252
/// Lower an if statement: `if <cond> { <then> } else { <else> }`.
5253
///
5254
/// With else branch:
5255
///
5256
///     @entry -> (true)  @then ---> @merge <--.
5257
///         |                                   )
5258
///         `---> (false) @else ---------------'
5259
///
5260
/// Without else branch:
5261
///
5262
///     @entry -> (true)  @then ---> @end <--.
5263
///         |                                 )
5264
///         `---- (false) -------------------'
5265
///
5266
fn lowerIf(self: *mut FnLowerer, i: ast::If) throws (LowerError) {
5267
    let thenBlock = try createBlock(self, "then");
5268
5269
    if let elseNode = i.elseBranch { // If-else case.
5270
        let elseBlock = try createBlock(self, "else");
5271
        try emitCondBranch(self, i.condition, thenBlock, elseBlock);
5272
5273
        // Both @then and @else have exactly one predecessor (@entry), so we can
5274
        // seal them immediately.
5275
        try sealBlock(self, thenBlock);
5276
        try sealBlock(self, elseBlock);
5277
5278
        // The merge block is created lazily by [`emitMergeIfUnterminated`]. We
5279
        // only need it if at least one branch doesn't diverge (i.e., needs to
5280
        // continue execution after the `if`). If both branches diverge (eg.
5281
        // both `return`), no merge block is created and control flow
5282
        // doesn't continue past the `if` statement.
5283
        let mut mergeBlock: ?BlockId = nil;
5284
5285
        // Lower the @then block: switch to it, emit its code, then jump to
5286
        // merge if the block doesn't diverge.
5287
        switchToBlock(self, thenBlock);
5288
        try lowerBlock(self, i.thenBranch);
5289
        try emitMergeIfUnterminated(self, &mut mergeBlock);
5290
5291
        // Lower the @else block similarly.
5292
        switchToBlock(self, elseBlock);
5293
        try lowerBlock(self, elseNode);
5294
        try emitMergeIfUnterminated(self, &mut mergeBlock);
5295
5296
        // If a merge block was created (at least one branch flows into it),
5297
        // switch to it for subsequent code. The merge block's predecessors
5298
        // are the branches that jumped to it, so we seal it now.
5299
        // If the merge block is `nil`, both branches diverged and there's no
5300
        // continuation point.
5301
        if let blk = mergeBlock {
5302
            try switchToAndSeal(self, blk);
5303
        }
5304
    } else { // If without `else`.
5305
        // The false branch goes directly to @end, which also serves as the
5306
        // merge point after @then completes.
5307
        let endBlock = try createBlock(self, "merge");
5308
5309
        try emitCondBranch(self, i.condition, thenBlock, endBlock);
5310
5311
        // @then has one predecessor (@entry), seal it immediately.
5312
        // @end is not sealed yet because @then might also jump to it.
5313
        try sealBlock(self, thenBlock);
5314
5315
        // Lower the @then block, then jump to @end and seal it.
5316
        // Unlike the if-else case, @end is always created because there is no
5317
        // else branch that can diverge.
5318
        switchToBlock(self, thenBlock);
5319
        try lowerBlock(self, i.thenBranch);
5320
        try emitJmpAndSeal(self, endBlock);
5321
5322
        // Continue execution at @end.
5323
        try switchToAndSeal(self, endBlock);
5324
    }
5325
}
5326
5327
/// Lower an assignment target that designates a memory location, and return
5328
/// the address to store through. Returns `nil` without emitting anything for
5329
/// targets that aren't memory-backed, such as locals tracked in SSA.
5330
fn lowerPlace(self: *mut FnLowerer, target: *ast::Node) -> ?FieldRef throws (LowerError) {
5331
    match target.value {
5332
        case ast::NodeValue::FieldAccess(access) => {
5333
            return try lowerFieldRef(self, access);
5334
        }
5335
        case ast::NodeValue::Deref(pointer) => {
5336
            // Dereference: `*ptr` or `*r` on a single-field unlabeled record.
5337
            // Both address offset 0 using the resolver-assigned type.
5338
            let base = emitValToReg(self, try lowerExpr(self, pointer));
5339
            return FieldRef { base, offset: 0, fieldType: try typeOf(self, target) };
5340
        }
5341
        case ast::NodeValue::Subscript { container, index } => {
5342
            // Array or slice element: `arr[i]`.
5343
            let elem = try lowerElemPtr(self, container, index);
5344
            return FieldRef { base: elem.elemReg, offset: 0, fieldType: elem.elemType };
5345
        }
5346
        else => return nil,
5347
    }
5348
}
5349
5350
/// Lower a compound assignment whose target is memory-backed, and report
5351
/// whether it was handled. Nothing is emitted when it isn't.
5352
///
5353
/// Compound assignments share their target node with the left operand of the
5354
/// desugared binary expression. Resolve that place once so side effects in a
5355
/// dereference, field parent, or subscript index are not repeated for the store.
5356
fn lowerCompoundAssign(
5357
    self: *mut FnLowerer, expr: *ast::Node, binop: ast::BinOp
5358
) -> bool throws (LowerError) {
5359
    let place = try lowerPlace(self, binop.left) else return false;
5360
    let current = emitRead(self, place.base, place.offset, place.fieldType);
5361
    let left = try applyCoercion(self, binop.left, current);
5362
    let right = try lowerExpr(self, binop.right);
5363
    let exprType = try typeOf(self, expr);
5364
    let result = emitScalarBinOp(
5365
        self, binop.op, ilType(self.low, exprType), left, right, isUnsignedType(exprType)
5366
    );
5367
    let assigned = try applyCoercion(self, expr, result);
5368
    try emitStore(self, place.base, place.offset, place.fieldType, assigned);
5369
5370
    return true;
5371
}
5372
5373
/// Lower an assignment statement.
5374
fn lowerAssign(self: *mut FnLowerer, node: *ast::Node, a: ast::Assign) throws (LowerError) {
5375
    // Slice assignment: `slice[range] = value`.
5376
    if let info = resolver::sliceRangeInfoFor(self.low.resolver, node) {
5377
        let case ast::NodeValue::Subscript { container, index } = a.left.value
5378
            else panic "lowerAssign: slice assign without subscript";
5379
        let case ast::NodeValue::Range(range) = index.value
5380
            else panic "lowerAssign: slice assign without range";
5381
        try lowerSliceAssign(self, a.right, container, range, info);
5382
5383
        return;
5384
    }
5385
    // Compound assignments are represented as `target = target op rhs`, with
5386
    // the exact same target node used in both places. Memory-backed targets
5387
    // must be resolved once so calls in the target are evaluated once.
5388
    if let case ast::NodeValue::BinOp(binop) = a.right.value {
5389
        if binop.left == a.left and try lowerCompoundAssign(self, a.right, binop) {
5390
            return;
5391
        }
5392
    }
5393
    // Evaluate assignment value.
5394
    let rhs = try lowerExpr(self, a.right);
5395
5396
    match a.left.value {
5397
        case ast::NodeValue::Ident(_) => {
5398
            // First try local variable lookup.
5399
            if let v = lookupLocalVar(self, a.left) {
5400
                if not getVar(self, v).mutable {
5401
                    throw LowerError::ImmutableAssignment;
5402
                }
5403
                let leftTy = try typeOf(self, a.left);
5404
                if isAggregateType(leftTy) or getVar(self, v).addressTaken {
5405
                    // Aggregates and address-taken scalars are represented as
5406
                    // pointers to stack memory. Store through the pointer.
5407
                    let val = try useVar(self, v);
5408
                    let dst = emitValToReg(self, val);
5409
5410
                    try emitStore(self, dst, 0, leftTy, rhs);
5411
                } else {
5412
                    // Scalars are tracked directly in SSA. Each assignment
5413
                    // records a new SSA value.
5414
                    defVar(self, v, rhs);
5415
                }
5416
            } else {
5417
                // Fall back to static variable assignment.
5418
                try lowerStaticAssign(self, a.left, rhs);
5419
            }
5420
        }
5421
        else => {
5422
            let place = try lowerPlace(self, a.left) else {
5423
                throw LowerError::UnexpectedNodeValue(a.left);
5424
            };
5425
            try emitStore(self, place.base, place.offset, place.fieldType, rhs);
5426
        }
5427
    }
5428
}
5429
5430
/// Lower `slice[range] = value`.
5431
fn lowerSliceAssign(
5432
    self: *mut FnLowerer,
5433
    rhs: *ast::Node,
5434
    container: *ast::Node,
5435
    range: ast::Range,
5436
    info: resolver::SliceRangeInfo
5437
) throws (LowerError) {
5438
    let r = try resolveSliceRangePtr(self, container, range, info);
5439
    let elemSize = resolver::getTypeLayout(*info.itemType).size;
5440
    let rhsTy = try typeOf(self, rhs);
5441
5442
    if let case resolver::Type::Slice { .. } = rhsTy {
5443
        // Copy from source slice.
5444
        let srcReg = emitValToReg(self, try lowerExpr(self, rhs));
5445
        let srcData = loadSlicePtr(self, srcReg);
5446
        let srcLen = loadSliceLen(self, srcReg);
5447
5448
        // Trap if source and destination lengths differ.
5449
        try emitTrapUnlessCmp(self, il::CmpOp::Eq, il::Type::W32, r.count, srcLen);
5450
5451
        let bytes = emitTypedBinOp(
5452
            self, il::BinOp::Mul, il::Type::W32, r.count, il::Val::Imm(elemSize as i64)
5453
        );
5454
        try emitByteCopyLoop(self, r.dataReg, srcData, bytes, "copy");
5455
    } else {
5456
        // Fill with scalar value.
5457
        let fillVal = try lowerExpr(self, rhs);
5458
        try emitFillLoop(self, r.dataReg, fillVal, r.count, *info.itemType, elemSize);
5459
    }
5460
}
5461
5462
/// Emit a typed fill loop: `for i in 0..count { dst[i * stride] = value; }`.
5463
fn emitFillLoop(
5464
    self: *mut FnLowerer,
5465
    dst: il::Reg,
5466
    value: il::Val,
5467
    count: il::Val,
5468
    elemType: resolver::Type,
5469
    elemSize: u32
5470
) throws (LowerError) {
5471
    let iReg = nextReg(self);
5472
    let header = try createBlockWithParam(
5473
        self, "fill", il::Param { value: iReg, type: il::Type::W32 }
5474
    );
5475
    let body = try createBlock(self, "fill");
5476
    let done = try createBlock(self, "fill");
5477
5478
    try emitJmpWithArg(self, header, il::Val::Imm(0));
5479
    switchToBlock(self, header);
5480
    try emitBrCmp(self, il::CmpOp::Ult, il::Type::W32, il::Val::Reg(iReg), count, body, done);
5481
5482
    try switchToAndSeal(self, body);
5483
    let dstElem = emitElem(self, elemSize, dst, il::Val::Reg(iReg));
5484
    try emitStore(self, dstElem, 0, elemType, value);
5485
5486
    let nextI = emitTypedBinOp(
5487
        self, il::BinOp::Add, il::Type::W32, il::Val::Reg(iReg), il::Val::Imm(1)
5488
    );
5489
    try emitJmpWithArg(self, header, nextI);
5490
    try sealBlock(self, header);
5491
    try switchToAndSeal(self, done);
5492
}
5493
5494
///////////////////
5495
// Loop Lowering //
5496
///////////////////
5497
5498
// All loop forms are lowered to a common structure:
5499
//
5500
// - Loop header block: evaluates condition if any, branches to body or exit.
5501
// - Body block: executes loop body, may contain break/continue.
5502
// - Step block (for `for` loops): increments counter, jumps back to header.
5503
// - Exit block: target for break statements and normal loop exit.
5504
//
5505
// The loop stack tracks break/continue targets for nested loops.
5506
5507
/// Lower an infinite loop: `loop { <body> }`.
5508
///
5509
///   @entry -> @loop -> @loop
5510
///               |
5511
///               `----> @end
5512
///
5513
fn lowerLoop(self: *mut FnLowerer, body: *ast::Node) throws (LowerError) {
5514
    let loopBlock = try createBlock(self, "loop");
5515
    let endBlock = try createBlock(self, "merge");
5516
5517
    // Enter the loop with the given break and continue targets.
5518
    // `break` jumps to `endBlock`,
5519
    // `continue` jumps to `loopBlock`.
5520
    enterLoop(self, endBlock, loopBlock);
5521
    // Switch to and jump to the loop block, then lower all loop body statements into it.
5522
    try switchAndJumpTo(self, loopBlock);
5523
    try lowerBlock(self, body);
5524
5525
    // If the loop body doesn't diverge, jump back to the start.
5526
    // This creates the infinite loop.
5527
    // All predecessors are known, we can seal the loop block.
5528
    try emitJmpAndSeal(self, loopBlock);
5529
    // Exit the loop.
5530
    exitLoop(self);
5531
5532
    // Only seal end block if it's actually reachable (ie. has predecessors).
5533
    // If the loop has no breaks and only exits via return, the end block
5534
    // remains unreachable and isn't added to the CFG.
5535
    if getBlock(self, endBlock).preds.len > 0 {
5536
        try switchToAndSeal(self, endBlock);
5537
    }
5538
}
5539
5540
/// Lower a while loop: `while <cond> { <body> }`.
5541
///
5542
///   @entry -> @loop -> (true)  @body -> @loop
5543
///               |
5544
///               `----> (false) @end
5545
///
5546
fn lowerWhile(self: *mut FnLowerer, w: ast::While) throws (LowerError) {
5547
    let whileBlock = try createBlock(self, "while");
5548
    let bodyBlock = try createBlock(self, "body");
5549
    let endBlock = try createBlock(self, "merge");
5550
5551
    enterLoop(self, endBlock, whileBlock);
5552
5553
    // Loop condition.
5554
    try switchAndJumpTo(self, whileBlock);
5555
5556
    // Based on the condition, either jump to the body,
5557
    // or to the end of the loop.
5558
    try emitCondBranch(self, w.condition, bodyBlock, endBlock);
5559
5560
    // Lower loop body and jump back to loop condition check.
5561
    try switchToAndSeal(self, bodyBlock);
5562
    try lowerBlock(self, w.body);
5563
    try emitJmpAndSeal(self, whileBlock);
5564
5565
    try switchToAndSeal(self, endBlock);
5566
    exitLoop(self);
5567
}
5568
5569
/// Emit an increment of a variable by `1`.
5570
fn emitIncrement(self: *mut FnLowerer, v: Var, typ: il::Type) throws (LowerError) {
5571
    let cur = try useVar(self, v);
5572
    let next = nextReg(self);
5573
5574
    emit(self, il::Instr::BinOp { op: il::BinOp::Add, typ, dst: next, a: cur, b: il::Val::Imm(1) });
5575
    defVar(self, v, il::Val::Reg(next));
5576
}
5577
5578
/// Common for-loop lowering for both range and collection iterators.
5579
///
5580
/// The step block is created lazily (after the loop body) so that it gets
5581
/// a block index higher than all body blocks. This ensures the register
5582
/// allocator processes definitions before uses in forward block order,
5583
/// avoiding stale assignments when a value defined deep in the body flows
5584
/// through the step block as a block argument.
5585
fn lowerForLoop(self: *mut FnLowerer, iter: *ForIter, body: *ast::Node) throws (LowerError) {
5586
    let loopBlock = try createBlock(self, "loop");
5587
    let bodyBlock = try createBlock(self, "body");
5588
    let endBlock = try createBlock(self, "merge");
5589
5590
    enterLoop(self, endBlock, nil);
5591
    try switchAndJumpTo(self, loopBlock);
5592
5593
    // Emit condition check.
5594
    match *iter {
5595
        case ForIter::Range { valVar, endVal, valType, unsigned, .. } => {
5596
            let curVal = try useVar(self, valVar);
5597
            let cmp = il::CmpOp::Ult if unsigned else il::CmpOp::Slt;
5598
            try emitBrCmp(self, cmp, valType, curVal, endVal, bodyBlock, endBlock);
5599
        }
5600
        case ForIter::Collection { idxVar, lengthVal, .. } => {
5601
            let curIdx = try useVar(self, idxVar);
5602
            try emitBrCmp(self, il::CmpOp::Slt, il::Type::W32, curIdx, lengthVal, bodyBlock, endBlock);
5603
        }
5604
    }
5605
    // Switch to loop body.
5606
    try switchToAndSeal(self, bodyBlock);
5607
5608
    // Emit element binding, only for collections.
5609
    // Reads the element at the current index.
5610
    if let case ForIter::Collection { valVar, idxVar, dataReg, elemType, .. } = *iter {
5611
        if let v = valVar {
5612
            let curIdx = try useVar(self, idxVar);
5613
            let elemReg = emitElem(self, resolver::getTypeLayout(*elemType).size, dataReg, curIdx);
5614
            let val = emitRead(self, elemReg, 0, *elemType);
5615
5616
            defVar(self, v, val);
5617
        }
5618
    }
5619
    // Lower the loop body.
5620
    try lowerBlock(self, body);
5621
5622
    // Check if a `continue` statement created a step block.
5623
    let ctx = currentLoop(self) else panic;
5624
    if let stepBlock = ctx.continueTarget {
5625
        // Body has `continue` statements: jump to step block, emit increment there.
5626
        try emitJmpAndSeal(self, stepBlock);
5627
        switchToBlock(self, stepBlock);
5628
    }
5629
    // Otherwise, emit increment directly in the current block,
5630
    // saving the jump to a separate step block.
5631
    if not blockHasTerminator(self) {
5632
        match *iter {
5633
            case ForIter::Range { valVar, valType, indexVar, .. } => {
5634
                try emitIncrement(self, valVar, valType);
5635
                if let idxVar = indexVar {
5636
                    try emitIncrement(self, idxVar, il::Type::W32);
5637
                }
5638
            }
5639
            case ForIter::Collection { idxVar, .. } => {
5640
                try emitIncrement(self, idxVar, il::Type::W32);
5641
            }
5642
        }
5643
        try emitJmp(self, loopBlock);
5644
    }
5645
    exitLoop(self);
5646
5647
    try sealBlock(self, loopBlock);
5648
    try sealBlock(self, endBlock);
5649
5650
    switchToBlock(self, endBlock);
5651
}
5652
5653
/// Lower a `for` loop over a range, array, or slice.
5654
fn lowerFor(self: *mut FnLowerer, node: *ast::Node, f: ast::For) throws (LowerError) {
5655
    let savedVarsLen = enterVarScope(self);
5656
    let info = resolver::forLoopInfoFor(self.low.resolver, node) else {
5657
        throw LowerError::MissingMetadata;
5658
    };
5659
    match info {
5660
        case resolver::ForLoopInfo::Range { valType, range, bindingName, indexName } => {
5661
            let endExpr = range.end else {
5662
                throw LowerError::MissingMetadata;
5663
            };
5664
            let mut startVal = il::Val::Imm(0);
5665
            if let start = range.start {
5666
                set startVal = try lowerExpr(self, start);
5667
            }
5668
            let endVal = try lowerExpr(self, endExpr);
5669
            let iterType = ilType(self.low, *valType);
5670
            let valVar = newVar(self, bindingName, iterType, false, startVal);
5671
5672
            let mut indexVar: ?Var = nil;
5673
            if indexName <> nil { // Optional index always starts at zero.
5674
                set indexVar = newVar(self, indexName, il::Type::W32, false, il::Val::Imm(0));
5675
            }
5676
            let iter = ForIter::Range {
5677
                valVar, indexVar, endVal, valType: iterType,
5678
                unsigned: isUnsignedType(*valType),
5679
            };
5680
5681
            try lowerForLoop(self, &iter, f.body);
5682
        }
5683
        case resolver::ForLoopInfo::Collection { elemType, length, bindingName, indexName } => {
5684
            let containerVal = try lowerExpr(self, f.iterable);
5685
            let containerReg = emitValToReg(self, containerVal);
5686
5687
            let mut dataReg = containerReg;
5688
            let mut lengthVal: il::Val = undefined;
5689
            if let len = length { // Array (length is known).
5690
                set lengthVal = il::Val::Imm(len as i64);
5691
            } else { // Slice (length must be loaded).
5692
                set lengthVal = loadSliceLen(self, containerReg);
5693
                set dataReg = loadSlicePtr(self, containerReg);
5694
            }
5695
            // Declare index value binidng.
5696
            let idxVar = newVar(self, indexName, il::Type::W32, false, il::Val::Imm(0));
5697
5698
            // Declare element value binding.
5699
            let mut valVar: ?Var = nil;
5700
            if bindingName <> nil {
5701
                set valVar = newVar(
5702
                    self,
5703
                    bindingName,
5704
                    ilType(self.low, *elemType),
5705
                    false,
5706
                    il::Val::Undef
5707
                );
5708
            }
5709
            let iter = ForIter::Collection { valVar, idxVar, dataReg, lengthVal, elemType };
5710
5711
            try lowerForLoop(self, &iter, f.body);
5712
        }
5713
    }
5714
    exitVarScope(self, savedVarsLen);
5715
}
5716
5717
/// Lower a break statement.
5718
fn lowerBreak(self: *mut FnLowerer) throws (LowerError) {
5719
    let ctx = currentLoop(self) else {
5720
        throw LowerError::OutsideOfLoop;
5721
    };
5722
    try emitJmp(self, ctx.breakTarget);
5723
}
5724
5725
/// Lower a continue statement.
5726
fn lowerContinue(self: *mut FnLowerer) throws (LowerError) {
5727
    let block = try getOrCreateContinueBlock(self);
5728
    try emitJmp(self, block);
5729
}
5730
5731
/// Emit a return, blitting into the caller's return buffer if needed.
5732
///
5733
/// When the function has a return buffer parameter, the value is blitted
5734
/// into the buffer and the buffer pointer is returned. Otherwise, the value is
5735
/// returned directly.
5736
fn emitRetVal(self: *mut FnLowerer, val: il::Val) throws (LowerError) {
5737
    if let retReg = self.returnReg {
5738
        let src = emitValToReg(self, val);
5739
        let size = resolver::getResultLayout(*self.fnType.returnType, self.fnType.throwList).size
5740
            if self.fnType.throwList.len > 0
5741
            else resolver::getTypeLayout(*self.fnType.returnType).size;
5742
5743
        emit(self, il::Instr::Blit { dst: retReg, src, size: il::Val::Imm(size as i64) });
5744
        emit(self, il::Instr::Ret { val: il::Val::Reg(retReg) });
5745
    } else if isSmallAggregate(*self.fnType.returnType) {
5746
        let src = emitValToReg(self, val);
5747
        let dst = nextReg(self);
5748
5749
        emit(self, il::Instr::Load { typ: il::Type::W64, dst, src, offset: 0 });
5750
        emit(self, il::Instr::Ret { val: il::Val::Reg(dst) });
5751
    } else {
5752
        emit(self, il::Instr::Ret { val });
5753
    }
5754
}
5755
5756
/// Lower a return statement.
5757
fn lowerReturnStmt(self: *mut FnLowerer, node: *ast::Node, value: ?*ast::Node) throws (LowerError) {
5758
    let mut val = il::Val::Undef;
5759
    if let expr = value {
5760
        set val = try lowerExpr(self, expr);
5761
    }
5762
    set val = try applyCoercion(self, node, val);
5763
    try emitRetVal(self, val);
5764
}
5765
5766
/// Lower a throw statement.
5767
fn lowerThrowStmt(self: *mut FnLowerer, expr: *ast::Node) throws (LowerError) {
5768
    assert self.fnType.throwList.len > 0;
5769
5770
    let errType = *self.fnType.throwList[0] if self.fnType.throwList.len == 1
5771
        else try typeOf(self, expr);
5772
    let tag = getOrAssignErrorTag(self.low, errType) as i64;
5773
    let errVal = try lowerExpr(self, expr);
5774
    let resultVal = try buildResult(self, tag, errVal, errType);
5775
5776
    try emitRetVal(self, resultVal);
5777
}
5778
5779
/// Ensure a value is in a register (eg. for branch conditions).
5780
fn emitValToReg(self: *mut FnLowerer, val: il::Val) -> il::Reg {
5781
    match val {
5782
        case il::Val::Reg(r) => return r,
5783
        case il::Val::Imm(_), il::Val::DataSym(_), il::Val::FnAddr(_) => {
5784
            let dst = nextReg(self);
5785
            emit(self, il::Instr::Copy { dst, val });
5786
            return dst;
5787
        }
5788
        case il::Val::Undef => {
5789
            // TODO: We shouldn't hit this case, right? A register shouldn't be needed
5790
            // if the value is undefined.
5791
            return nextReg(self);
5792
        }
5793
    }
5794
}
5795
5796
/// Lower a logical `and`/`or` with short-circuit evaluation.
5797
///
5798
/// Short-circuit evaluation skips evaluating the right operand when the left
5799
/// operand already determines the result:
5800
///
5801
/// - In `a and b`, if `a` is false, result is false without evaluating `b`.
5802
/// - In `a or b`, if `a` is true, result is true without evaluating `b`.
5803
///
5804
/// This matters when `b` has side effects, or is expensive to evaluate.
5805
///
5806
/// Example: `a and b`
5807
///
5808
///     @entry
5809
///       br %a @then @else;
5810
///     @then
5811
///       // Evaluate b into %b
5812
///       // ...
5813
///       jmp @end(%b);
5814
///     @else
5815
///       jmp @end(0);                  // Skip evaluating b, result is false
5816
///     @end(w8 %result)
5817
///       ret %result;
5818
///
5819
/// Example: `a or b`
5820
///
5821
///     @entry
5822
///       br %a @then @else;
5823
///     @then
5824
///       jmp @end(1);                  // Skip evaluating b, result is true
5825
///     @else
5826
///       // Evaluate b into %b
5827
///       // ...
5828
///       jmp @end(%b);
5829
///     @end(w8 %result)
5830
///       ret %result;
5831
///
5832
fn lowerLogicalOp(
5833
    self: *mut FnLowerer,
5834
    binop: ast::BinOp,
5835
    thenLabel: *[u8],
5836
    elseLabel: *[u8],
5837
    mergeLabel: *[u8],
5838
    op: LogicalOp
5839
) -> il::Val throws (LowerError) {
5840
    let thenBlock = try createBlock(self, thenLabel);
5841
    let elseBlock = try createBlock(self, elseLabel);
5842
5843
    let resultReg = nextReg(self);
5844
    let mergeBlock = try createBlockWithParam(
5845
        self, mergeLabel, il::Param { value: resultReg, type: il::Type::W8 }
5846
    );
5847
    // Evaluate left operand and branch.
5848
    try emitCondBranch(self, binop.left, thenBlock, elseBlock);
5849
5850
    // Block that skips evaluating `b`.
5851
    let mut shortCircuitBlock: BlockId = undefined;
5852
    // Block that evaluates `b`.
5853
    let mut evalBlock: BlockId = undefined;
5854
    // Result when short-circuiting (`0` or `1`).
5855
    let mut shortCircuitVal: i64 = undefined;
5856
5857
    match op {
5858
        case LogicalOp::And => {
5859
            set shortCircuitBlock = elseBlock;
5860
            set evalBlock = thenBlock;
5861
            set shortCircuitVal = 0;
5862
        }
5863
        case LogicalOp::Or => {
5864
            set shortCircuitBlock = thenBlock;
5865
            set evalBlock = elseBlock;
5866
            set shortCircuitVal = 1;
5867
        }
5868
    }
5869
    // Emit short-circuit branch: jump to merge with constant result.
5870
    try switchToAndSeal(self, shortCircuitBlock);
5871
    try emitJmpWithArg(self, mergeBlock, il::Val::Imm(shortCircuitVal));
5872
5873
    // Emit evaluation branch: evaluate right operand and jump to merge.
5874
    try switchToAndSeal(self, evalBlock);
5875
    try emitJmpWithArg(self, mergeBlock, try lowerExpr(self, binop.right));
5876
5877
    try switchToAndSeal(self, mergeBlock);
5878
    return il::Val::Reg(resultReg);
5879
}
5880
5881
/// Lower a conditional expression (`thenExpr if condition else elseExpr`).
5882
fn lowerCondExpr(self: *mut FnLowerer, node: *ast::Node, cond: ast::CondExpr) -> il::Val
5883
    throws (LowerError)
5884
{
5885
    let typ = try typeOf(self, node);
5886
    let thenBlock = try createBlock(self, "cond#then");
5887
    let elseBlock = try createBlock(self, "cond#else");
5888
5889
    if isAggregateType(typ) {
5890
        let dst = try emitReserve(self, typ);
5891
        let layout = resolver::getTypeLayout(typ);
5892
        try emitCondBranch(self, cond.condition, thenBlock, elseBlock);
5893
5894
        let mergeBlock = try createBlock(self, "cond#merge");
5895
        try switchToAndSeal(self, thenBlock);
5896
5897
        let thenVal = emitValToReg(self, try lowerExpr(self, cond.thenExpr));
5898
        emit(self, il::Instr::Blit { dst, src: thenVal, size: il::Val::Imm(layout.size as i64) });
5899
5900
        try emitJmp(self, mergeBlock);
5901
        try switchToAndSeal(self, elseBlock);
5902
5903
        let elseVal = emitValToReg(self, try lowerExpr(self, cond.elseExpr));
5904
        emit(self, il::Instr::Blit { dst, src: elseVal, size: il::Val::Imm(layout.size as i64) });
5905
5906
        try emitJmp(self, mergeBlock);
5907
        try switchToAndSeal(self, mergeBlock);
5908
5909
        return il::Val::Reg(dst);
5910
    } else {
5911
        try emitCondBranch(self, cond.condition, thenBlock, elseBlock);
5912
5913
        let resultType = ilType(self.low, typ);
5914
        let resultReg = nextReg(self);
5915
        let mergeBlock = try createBlockWithParam(
5916
            self, "cond#merge", il::Param { value: resultReg, type: resultType }
5917
        );
5918
        try switchToAndSeal(self, thenBlock);
5919
        try emitJmpWithArg(self, mergeBlock, try lowerExpr(self, cond.thenExpr));
5920
        try switchToAndSeal(self, elseBlock);
5921
        try emitJmpWithArg(self, mergeBlock, try lowerExpr(self, cond.elseExpr));
5922
        try switchToAndSeal(self, mergeBlock);
5923
5924
        return il::Val::Reg(resultReg);
5925
    }
5926
}
5927
5928
/// Select the concrete operand type for a scalar comparison.
5929
fn scalarComparisonType(left: resolver::Type, right: resolver::Type) -> resolver::Type {
5930
    return right if left == resolver::Type::Int else left;
5931
}
5932
5933
/// Convert a binary operator to a comparison op, if applicable.
5934
/// For `Gt`, caller must swap operands: `a > b = b < a`.
5935
/// For `Gte`/`Lte`, caller must swap branch labels: `a >= b = !(a < b)`.
5936
/// For `Lte`, caller must also swap operands: `a <= b = !(b < a)`.
5937
fn cmpOpFrom(op: ast::BinaryOp, unsigned: bool) -> ?il::CmpOp {
5938
    match op {
5939
        case ast::BinaryOp::Eq => return il::CmpOp::Eq,
5940
        case ast::BinaryOp::Ne => return il::CmpOp::Ne,
5941
        case ast::BinaryOp::Lt, ast::BinaryOp::Gt,
5942
             ast::BinaryOp::Gte, ast::BinaryOp::Lte =>
5943
            return il::CmpOp::Ult if unsigned else il::CmpOp::Slt,
5944
        else => return nil,
5945
    }
5946
}
5947
5948
/// Lower a binary operation.
5949
fn lowerBinOp(self: *mut FnLowerer, node: *ast::Node, binop: ast::BinOp) -> il::Val throws (LowerError) {
5950
    // Short-circuit logical operators don't evaluate both operands eagerly.
5951
    if binop.op == ast::BinaryOp::And {
5952
        return try lowerLogicalOp(self, binop, "and#then", "and#else", "and#end", LogicalOp::And);
5953
    } else if binop.op == ast::BinaryOp::Or {
5954
        return try lowerLogicalOp(self, binop, "or#then", "or#else", "or#end", LogicalOp::Or);
5955
    }
5956
5957
    // Handle comparison with a `nil` literal: just check the tag/pointer instead of
5958
    // building a `nil` aggregate and doing full comparison.
5959
    if binop.op == ast::BinaryOp::Eq or binop.op == ast::BinaryOp::Ne {
5960
        let isEq = binop.op == ast::BinaryOp::Eq;
5961
        let leftIsNil = binop.left.value == ast::NodeValue::Nil;
5962
        let rightIsNil = binop.right.value == ast::NodeValue::Nil;
5963
5964
        if leftIsNil {
5965
            return try lowerNilCheck(self, binop.right, isEq);
5966
        } else if rightIsNil {
5967
            return try lowerNilCheck(self, binop.left, isEq);
5968
        }
5969
    }
5970
    // Lower operands.
5971
    let a = try lowerExpr(self, binop.left);
5972
    let b = try lowerExpr(self, binop.right);
5973
    let isComparison = cmpOpFrom(binop.op, false) <> nil;
5974
5975
    // The result type for comparisons is always `bool`, while for arithmetic
5976
    // operations, it's the operand type. We set this appropriately here.
5977
    let nodeTy = try typeOf(self, node);
5978
    let mut resultTy = nodeTy;
5979
5980
    if isComparison {
5981
        let leftTy = try effectiveType(self, binop.left);
5982
        let rightTy = try effectiveType(self, binop.right);
5983
        // Optimize: comparing with a void variant just needs tag comparison.
5984
        if let idx = voidVariantIndex(self.low.resolver, binop.left) {
5985
            return try emitTagCmp(self, binop.op, b, idx, rightTy);
5986
        } else if let idx = voidVariantIndex(self.low.resolver, binop.right) {
5987
            return try emitTagCmp(self, binop.op, a, idx, leftTy);
5988
        }
5989
        // Aggregate types require element-wise comparison.
5990
        // When comparing `?T` with `T`, wrap the scalar side.
5991
        if isAggregateType(leftTy) {
5992
            let mut rhs = b;
5993
            if not isAggregateType(rightTy) {
5994
                set rhs = try wrapInOptional(self, rhs, leftTy);
5995
            }
5996
            return try emitAggregateEqOp(self, binop.op, leftTy, a, rhs);
5997
        }
5998
        if isAggregateType(rightTy) {
5999
            let lhs = try wrapInOptional(self, a, rightTy);
6000
            return try emitAggregateEqOp(self, binop.op, rightTy, lhs, b);
6001
        }
6002
        set resultTy = scalarComparisonType(leftTy, rightTy);
6003
    }
6004
    return emitScalarBinOp(self, binop.op, ilType(self.low, resultTy), a, b, isUnsignedType(resultTy));
6005
}
6006
6007
/// Emit an aggregate equality or inequality comparison.
6008
fn emitAggregateEqOp(
6009
    self: *mut FnLowerer,
6010
    op: ast::BinaryOp,
6011
    typ: resolver::Type,
6012
    a: il::Val,
6013
    b: il::Val
6014
) -> il::Val throws (LowerError) {
6015
    let regA = emitValToReg(self, a);
6016
    let regB = emitValToReg(self, b);
6017
    let result = try lowerAggregateEq(self, typ, regA, regB, 0);
6018
6019
    if op == ast::BinaryOp::Ne {
6020
        return emitTypedBinOp(self, il::BinOp::Eq, il::Type::W32, result, il::Val::Imm(0));
6021
    }
6022
    return result;
6023
}
6024
6025
/// Emit a scalar binary operation instruction.
6026
fn emitScalarBinOp(
6027
    self: *mut FnLowerer,
6028
    op: ast::BinaryOp,
6029
    typ: il::Type,
6030
    a: il::Val,
6031
    b: il::Val,
6032
    unsigned: bool
6033
) -> il::Val {
6034
    let dst = nextReg(self);
6035
    let mut needsExt: bool = false;
6036
    match op {
6037
        case ast::BinaryOp::Add => {
6038
            emit(self, il::Instr::BinOp { op: il::BinOp::Add, typ, dst, a, b });
6039
            set needsExt = true;
6040
        }
6041
        case ast::BinaryOp::Sub => {
6042
            emit(self, il::Instr::BinOp { op: il::BinOp::Sub, typ, dst, a, b });
6043
            set needsExt = true;
6044
        }
6045
        case ast::BinaryOp::Mul => {
6046
            emit(self, il::Instr::BinOp { op: il::BinOp::Mul, typ, dst, a, b });
6047
            set needsExt = true;
6048
        }
6049
        case ast::BinaryOp::Div => {
6050
            let op = il::BinOp::Udiv if unsigned else il::BinOp::Sdiv;
6051
            emit(self, il::Instr::BinOp { op, typ, dst, a, b });
6052
            set needsExt = true;
6053
        }
6054
        case ast::BinaryOp::Mod => {
6055
            let op = il::BinOp::Urem if unsigned else il::BinOp::Srem;
6056
            emit(self, il::Instr::BinOp { op, typ, dst, a, b });
6057
            set needsExt = true;
6058
        }
6059
        case ast::BinaryOp::BitAnd => emit(self, il::Instr::BinOp { op: il::BinOp::And, typ, dst, a, b }),
6060
        case ast::BinaryOp::BitOr => emit(self, il::Instr::BinOp { op: il::BinOp::Or, typ, dst, a, b }),
6061
        case ast::BinaryOp::BitXor => emit(self, il::Instr::BinOp { op: il::BinOp::Xor, typ, dst, a, b }),
6062
        case ast::BinaryOp::Shl => {
6063
            emit(self, il::Instr::BinOp { op: il::BinOp::Shl, typ, dst, a, b });
6064
            set needsExt = true;
6065
        }
6066
        case ast::BinaryOp::Shr => {
6067
            let op = il::BinOp::Ushr if unsigned else il::BinOp::Sshr;
6068
            emit(self, il::Instr::BinOp { op, typ, dst, a, b });
6069
        }
6070
        case ast::BinaryOp::Eq => emit(self, il::Instr::BinOp { op: il::BinOp::Eq, typ, dst, a, b }),
6071
        case ast::BinaryOp::Ne => emit(self, il::Instr::BinOp { op: il::BinOp::Ne, typ, dst, a, b }),
6072
        case ast::BinaryOp::Lt => {
6073
            let op = il::BinOp::Ult if unsigned else il::BinOp::Slt;
6074
            emit(self, il::Instr::BinOp { op, typ, dst, a, b });
6075
        }
6076
        case ast::BinaryOp::Gt => { // `a > b` = `b < a`
6077
            let op = il::BinOp::Ult if unsigned else il::BinOp::Slt;
6078
            emit(self, il::Instr::BinOp { op, typ, dst, a: b, b: a });
6079
        }
6080
        case ast::BinaryOp::Lte => { // `a <= b` = `b >= a`
6081
            let op = il::BinOp::Uge if unsigned else il::BinOp::Sge;
6082
            emit(self, il::Instr::BinOp { op, typ, dst, a: b, b: a });
6083
        }
6084
        case ast::BinaryOp::Gte => {
6085
            let op = il::BinOp::Uge if unsigned else il::BinOp::Sge;
6086
            emit(self, il::Instr::BinOp { op, typ, dst, a, b });
6087
        }
6088
        // Logical xor on booleans is equivalent to not equal.
6089
        case ast::BinaryOp::Xor => emit(self, il::Instr::BinOp { op: il::BinOp::Ne, typ, dst, a, b }),
6090
        // Short-circuit ops are handled elsewhere.
6091
        case ast::BinaryOp::And, ast::BinaryOp::Or => panic,
6092
    }
6093
    // Normalize sub-word arithmetic results so high bits are well-defined.
6094
    // The lowering knows signedness, so it can pick the right extension.
6095
    // [`il::Type::W32`] is handled in the backend via 32-bit instructions.
6096
    if needsExt {
6097
        return normalizeSubword(self, typ, unsigned, il::Val::Reg(dst));
6098
    }
6099
    return il::Val::Reg(dst);
6100
}
6101
6102
/// Normalize sub-word values to well-defined high bits.
6103
fn normalizeSubword(self: *mut FnLowerer, typ: il::Type, unsigned: bool, val: il::Val) -> il::Val {
6104
    if typ == il::Type::W8 or typ == il::Type::W16 {
6105
        let extDst: il::Reg = nextReg(self);
6106
        if unsigned {
6107
            emit(self, il::Instr::Zext { typ, dst: extDst, val });
6108
        } else {
6109
            emit(self, il::Instr::Sext { typ, dst: extDst, val });
6110
        }
6111
        return il::Val::Reg(extDst);
6112
    }
6113
    return val;
6114
}
6115
6116
/// Lower a unary operation.
6117
fn lowerUnOp(self: *mut FnLowerer, node: *ast::Node, unop: ast::UnOp) -> il::Val throws (LowerError) {
6118
    if unop.op == ast::UnaryOp::Neg {
6119
        if let case ast::NodeValue::Number(lit) = unop.value.value {
6120
            return il::Val::Imm((0 - lit.magnitude) as i64);
6121
        }
6122
    }
6123
    let val = try lowerExpr(self, unop.value);
6124
    let t = try typeOf(self, node);
6125
    let typ = ilType(self.low, t);
6126
    let dst = nextReg(self);
6127
    let mut needsExt: bool = false;
6128
6129
    match unop.op {
6130
        case ast::UnaryOp::Not => {
6131
            emit(self, il::Instr::BinOp { op: il::BinOp::Eq, typ, dst, a: val, b: il::Val::Imm(0) });
6132
        }
6133
        case ast::UnaryOp::Neg => {
6134
            emit(self, il::Instr::UnOp { op: il::UnOp::Neg, typ, dst, a: val });
6135
            set needsExt = true;
6136
        }
6137
        case ast::UnaryOp::BitNot => {
6138
            emit(self, il::Instr::UnOp { op: il::UnOp::Not, typ, dst, a: val });
6139
            set needsExt = true;
6140
        }
6141
    }
6142
    if needsExt {
6143
        return normalizeSubword(self, typ, isUnsignedType(t), il::Val::Reg(dst));
6144
    }
6145
    return il::Val::Reg(dst);
6146
}
6147
6148
/// Lower a cast expression (`x as T`).
6149
fn lowerCast(self: *mut FnLowerer, node: *ast::Node, cast: ast::As) -> il::Val throws (LowerError) {
6150
    let val = try lowerExpr(self, cast.value);
6151
6152
    let srcType = try typeOf(self, cast.value);
6153
    let dstType = try typeOf(self, node);
6154
    if resolver::typesEqual(srcType, dstType) {
6155
        return val;
6156
    }
6157
    return lowerNumericCast(self, val, srcType, dstType);
6158
}
6159
6160
/// Check whether a resolver type is a signed integer type.
6161
fn isSignedType(t: resolver::Type) -> bool {
6162
    match t {
6163
        case resolver::Type::I8, resolver::Type::I16, resolver::Type::I32, resolver::Type::I64,
6164
             resolver::Type::Int => return true,
6165
        else => return false,
6166
    }
6167
}
6168
6169
/// Check whether a resolver type is an unsigned integer type.
6170
fn isUnsignedType(t: resolver::Type) -> bool {
6171
    match t {
6172
        case resolver::Type::U8, resolver::Type::U16, resolver::Type::U32, resolver::Type::U64 => return true,
6173
        else => return false,
6174
    }
6175
}
6176
6177
/// Lower a string literal to a slice value.
6178
///
6179
/// String literals are stored as global data and the result is a slice
6180
/// pointing to the data with the appropriate length.
6181
fn lowerStringLit(self: *mut FnLowerer, node: *ast::Node, s: *[u8]) -> il::Val throws (LowerError) {
6182
    // Get the slice type from the node.
6183
    let sliceTy = try typeOf(self, node);
6184
    let case resolver::Type::Slice { item, mutable, .. } = sliceTy
6185
        else throw LowerError::ExpectedSliceOrArray;
6186
    // Build the string data value.
6187
    let ptr = try! alloc::alloc(
6188
        self.low.arena, @sizeOf(il::DataValue), @alignOf(il::DataValue)
6189
    ) as *mut il::DataValue;
6190
6191
    set *ptr = il::DataValue { item: il::DataItem::Str(s), count: 1 };
6192
6193
    return try lowerConstDataAsSlice(
6194
        self, @sliceOf(ptr, 1), 1, true, item, mutable, s.len
6195
    );
6196
}
6197
6198
/// Lower a builtin call expression.
6199
fn lowerBuiltinCall(self: *mut FnLowerer, node: *ast::Node, kind: ast::Builtin, args: *mut [*ast::Node]) -> il::Val throws (LowerError) {
6200
    match kind {
6201
        case ast::Builtin::SliceOf => return try lowerSliceOf(self, node, args),
6202
        case ast::Builtin::SizeOf, ast::Builtin::AlignOf => {
6203
            let constVal = resolver::constValueEntry(self.low.resolver, node) else {
6204
                throw LowerError::MissingConst(node);
6205
            };
6206
            return try constValueToVal(self, constVal, node);
6207
        }
6208
    }
6209
}
6210
6211
/// Lower a `@sliceOf(ptr, len)` or `@sliceOf(ptr, len, cap)` builtin call.
6212
fn lowerSliceOf(self: *mut FnLowerer, node: *ast::Node, args: *mut [*ast::Node]) -> il::Val throws (LowerError) {
6213
    if args.len <> 2 and args.len <> 3 {
6214
        throw LowerError::InvalidArgCount;
6215
    }
6216
    let sliceTy = try typeOf(self, node);
6217
    let case resolver::Type::Slice { item, mutable, .. } = sliceTy
6218
        else throw LowerError::ExpectedSliceOrArray;
6219
    let ptrVal = try lowerExpr(self, args[0]);
6220
    let lenVal = try lowerExpr(self, args[1]);
6221
    let mut capVal = lenVal;
6222
    if args.len == 3 {
6223
        set capVal = try lowerExpr(self, args[2]);
6224
    }
6225
    if not isLtEq(lenVal, capVal) {
6226
        try emitTrapIfLt(self, il::Type::W32, capVal, lenVal);
6227
    }
6228
    return try buildSliceValue(self, item, mutable, ptrVal, lenVal, capVal);
6229
}
6230
6231
/// Lower a `try` expression.
6232
fn lowerTry(self: *mut FnLowerer, node: *ast::Node, t: ast::Try) -> il::Val throws (LowerError) {
6233
    let case ast::NodeValue::Call(callExpr) = t.expr.value else {
6234
        throw LowerError::ExpectedCall;
6235
    };
6236
    let calleeTy = try typeOf(self, callExpr.callee);
6237
    let case resolver::Type::Fn(calleeInfo) = calleeTy else {
6238
        throw LowerError::ExpectedFunction;
6239
    };
6240
    let okValueTy = *calleeInfo.returnType; // The type of the success payload.
6241
6242
    // Type of the try expression, which is either the return type of the function
6243
    // if successful, or an optional of it, if using `try?`.
6244
    let tryExprTy = try typeOf(self, node);
6245
    // Check for trait method dispatch or standalone method call.
6246
    let mut resVal: il::Val = undefined;
6247
    let callNodeExtra = resolver::nodeData(self.low.resolver, t.expr).extra;
6248
    if let case resolver::NodeExtra::TraitMethodCall {
6249
        traitInfo, methodIndex
6250
    } = callNodeExtra {
6251
        set resVal = try lowerTraitMethodCall(self, t.expr, callExpr, traitInfo, methodIndex);
6252
    } else if let case resolver::NodeExtra::MethodCall { method } = callNodeExtra {
6253
        set resVal = try lowerMethodCall(self, t.expr, callExpr, method);
6254
    } else {
6255
        set resVal = try lowerCall(self, t.expr, callExpr);
6256
    }
6257
    let base = emitValToReg(self, resVal); // The result value.
6258
    let tagReg = resultTagReg(self, base); // The result tag.
6259
6260
    let okBlock = try createBlock(self, "ok"); // Block if success.
6261
    let errBlock = try createBlock(self, "err"); // Block if failure.
6262
6263
    let mut mergeBlock: ?BlockId = nil;
6264
    let mut resultSlot: ?il::Reg = nil; // `try` result value will be stored here.
6265
6266
    // Check if the `try` returns a success value or not. If so, reserve
6267
    // space for it.
6268
    let isVoid = tryExprTy == resolver::Type::Void;
6269
    if not isVoid {
6270
        set resultSlot = try emitReserve(self, tryExprTy);
6271
    }
6272
    // Branch on tag: zero means ok, non-zero means error.
6273
    try emitBr(self, tagReg, errBlock, okBlock);
6274
6275
    // We can now seal the blocks since all predecessors are known.
6276
    try sealBlock(self, okBlock);
6277
    try sealBlock(self, errBlock);
6278
6279
    // Success path: extract the successful value from the result and store it
6280
    // in the result slot for later use after the merge point.
6281
    switchToBlock(self, okBlock);
6282
6283
    if let slot = resultSlot {
6284
        // Extract the success payload. If the result type differs from the payload
6285
        // type (e.g. `try?` wrapping `T` into `?T`), wrap the value.
6286
        let payloadVal = tvalPayloadVal(self, base, okValueTy, RESULT_VAL_OFFSET);
6287
        let mut okVal = payloadVal;
6288
6289
        if t.returnsOptional and tryExprTy <> okValueTy {
6290
            set okVal = try wrapInOptional(self, payloadVal, tryExprTy);
6291
        }
6292
        try emitStore(self, slot, 0, tryExprTy, okVal);
6293
    }
6294
    // Jump to merge block if unterminated.
6295
    try emitMergeIfUnterminated(self, &mut mergeBlock);
6296
6297
    // Error path: handle the failure case based on the try expression variant.
6298
    switchToBlock(self, errBlock);
6299
6300
    if t.returnsOptional {
6301
        // `try?` converts errors to `nil` -- store the `nil` and continue.
6302
        if let slot = resultSlot {
6303
            let errVal = try buildNilOptional(self, tryExprTy);
6304
            try emitStore(self, slot, 0, tryExprTy, errVal);
6305
        }
6306
        try emitMergeIfUnterminated(self, &mut mergeBlock);
6307
    } else if t.catches.len > 0 {
6308
        // `try ... catch` -- handle the error.
6309
        let firstNode = t.catches[0];
6310
        let case ast::NodeValue::CatchClause(first) = firstNode.value
6311
            else panic "lowerTry: expected CatchClause";
6312
6313
        if first.typeNode <> nil or t.catches.len > 1 {
6314
            // Typed multi-catch: switch on global error tag.
6315
            try lowerMultiCatch(self, t.catches, calleeInfo, base, tagReg, &mut mergeBlock);
6316
        } else {
6317
            // Single untyped catch clause.
6318
            let savedVarsLen = enterVarScope(self);
6319
            if let binding = first.binding {
6320
                let case ast::NodeValue::Ident(name) = binding.value else {
6321
                    throw LowerError::ExpectedIdentifier;
6322
                };
6323
                let errTy = *calleeInfo.throwList[0];
6324
                let errVal = tvalPayloadVal(self, base, errTy, RESULT_VAL_OFFSET);
6325
                let _ = newVar(self, name, ilType(self.low, errTy), false, errVal);
6326
            }
6327
            try lowerBlock(self, first.body);
6328
            try emitMergeIfUnterminated(self, &mut mergeBlock);
6329
            exitVarScope(self, savedVarsLen);
6330
        }
6331
    } else if t.shouldPanic {
6332
        // `try!` -- panic on error, emit unreachable since control won't continue.
6333
        // TODO: We should have some kind of `panic` instruction?
6334
        emit(self, il::Instr::Unreachable);
6335
    } else {
6336
        // Plain `try` -- propagate the error to the caller by returning early.
6337
        // Forward the callee's global error tag and payload directly.
6338
        let callerLayout = resolver::getResultLayout(
6339
            *self.fnType.returnType, self.fnType.throwList
6340
        );
6341
        let calleeErrSize = maxErrSize(calleeInfo.throwList);
6342
        let dst = emitReserveLayout(self, callerLayout);
6343
6344
        emitStoreW64At(self, il::Val::Reg(tagReg), dst, TVAL_TAG_OFFSET);
6345
        let srcPayload = emitPtrOffset(self, base, RESULT_VAL_OFFSET);
6346
        let dstPayload = emitPtrOffset(self, dst, RESULT_VAL_OFFSET);
6347
        emit(self, il::Instr::Blit { dst: dstPayload, src: srcPayload, size: il::Val::Imm(calleeErrSize as i64) });
6348
6349
        try emitRetVal(self, il::Val::Reg(dst));
6350
    }
6351
6352
    // Switch to the merge block if one was created. If all paths diverged
6353
    // (e.g both success and error returned), there's no merge block.
6354
    if let blk = mergeBlock {
6355
        try switchToAndSeal(self, blk);
6356
    } else {
6357
        return il::Val::Undef;
6358
    }
6359
    // Return the result value. For `void` expressions, return undefined.
6360
    // For aggregates, return the slot pointer; for scalars, load the value.
6361
    if let slot = resultSlot {
6362
        if isAggregateType(tryExprTy) {
6363
            return il::Val::Reg(slot);
6364
        }
6365
        return emitLoad(self, slot, 0, tryExprTy);
6366
    } else { // Void return.
6367
        return il::Val::Undef;
6368
    }
6369
}
6370
6371
/// Lower typed multi-catch clauses.
6372
///
6373
/// Emits a switch on the global error tag to dispatch to the correct catch
6374
/// clause. Each typed clause extracts the error payload for its specific type
6375
/// and binds it to the clause's identifier.
6376
fn lowerMultiCatch(
6377
    self: *mut FnLowerer,
6378
    catches: *mut [*ast::Node],
6379
    calleeInfo: *resolver::FnType,
6380
    base: il::Reg,
6381
    tagReg: il::Reg,
6382
    mergeBlock: *mut ?BlockId
6383
) throws (LowerError) {
6384
    let entry = currentBlock(self);
6385
6386
    // First pass: create blocks, resolve error types, and build switch cases.
6387
    let mut blocks: [BlockId; MAX_CATCH_CLAUSES] = undefined;
6388
    let mut errTypes: [?resolver::Type; MAX_CATCH_CLAUSES] = undefined;
6389
    let mut cases: *mut [il::SwitchCase] = &mut [];
6390
    let mut defaultIdx: ?u32 = nil;
6391
6392
    for clauseNode, i in catches {
6393
        let case ast::NodeValue::CatchClause(clause) = clauseNode.value
6394
            else panic "lowerMultiCatch: expected CatchClause";
6395
6396
        set blocks[i] = try createBlock(self, "catch");
6397
        addPredecessor(self, blocks[i], entry);
6398
6399
        if let typeNode = clause.typeNode {
6400
            let errTy = try typeOf(self, typeNode);
6401
            set errTypes[i] = errTy;
6402
6403
            cases.append(il::SwitchCase {
6404
                value: getOrAssignErrorTag(self.low, errTy) as i64,
6405
                target: *blocks[i],
6406
                args: &mut []
6407
            }, self.allocator);
6408
        } else {
6409
            set errTypes[i] = nil;
6410
            set defaultIdx = i;
6411
        }
6412
    }
6413
6414
    // Emit switch. Default target is the catch-all block, or an unreachable block.
6415
    let mut defaultTarget: BlockId = undefined;
6416
    if let idx = defaultIdx {
6417
        set defaultTarget = blocks[idx];
6418
    } else {
6419
        set defaultTarget = try createBlock(self, "unreachable");
6420
        addPredecessor(self, defaultTarget, entry);
6421
    }
6422
    emit(self, il::Instr::Switch {
6423
        val: il::Val::Reg(tagReg),
6424
        defaultTarget: *defaultTarget,
6425
        defaultArgs: &mut [],
6426
        cases
6427
    });
6428
6429
    // Second pass: emit each catch clause body.
6430
    for clauseNode, i in catches {
6431
        let case ast::NodeValue::CatchClause(clause) = clauseNode.value
6432
            else panic "lowerMultiCatch: expected CatchClause";
6433
6434
        try switchToAndSeal(self, blocks[i]);
6435
        let savedVarsLen = enterVarScope(self);
6436
6437
        if let binding = clause.binding {
6438
            let case ast::NodeValue::Ident(name) = binding.value else {
6439
                throw LowerError::ExpectedIdentifier;
6440
            };
6441
            let errTy = errTypes[i] else panic "lowerMultiCatch: catch-all with binding";
6442
            let errVal = tvalPayloadVal(self, base, errTy, RESULT_VAL_OFFSET);
6443
6444
            newVar(self, name, ilType(self.low, errTy), false, errVal);
6445
        }
6446
        try lowerBlock(self, clause.body);
6447
        try emitMergeIfUnterminated(self, mergeBlock);
6448
6449
        exitVarScope(self, savedVarsLen);
6450
    }
6451
6452
    // Emit unreachable block if no catch-all.
6453
    if defaultIdx == nil {
6454
        try switchToAndSeal(self, defaultTarget);
6455
        emit(self, il::Instr::Unreachable);
6456
    }
6457
}
6458
6459
/// Emit a byte-copy loop: `for i in 0..size { dst[i] = src[i]; }`.
6460
///
6461
/// Used when `blit` cannot be used because the copy size is dynamic.
6462
/// Terminates the current block and leaves the builder positioned
6463
/// after the loop.
6464
fn emitByteCopyLoop(
6465
    self: *mut FnLowerer,
6466
    dst: il::Reg,
6467
    src: il::Reg,
6468
    size: il::Val,
6469
    label: *[u8]
6470
) throws (LowerError) {
6471
    let iReg = nextReg(self);
6472
    let header = try createBlockWithParam(
6473
        self, label, il::Param { value: iReg, type: il::Type::W32 }
6474
    );
6475
    let body = try createBlock(self, label);
6476
    let done = try createBlock(self, label);
6477
6478
    // Jump to header with initial counter is zero.
6479
    try emitJmpWithArg(self, header, il::Val::Imm(0));
6480
6481
    // Don't seal header yet -- the body will add another predecessor.
6482
    switchToBlock(self, header);
6483
    try emitBrCmp(self, il::CmpOp::Ult, il::Type::W32, il::Val::Reg(iReg), size, body, done);
6484
6485
    // Body: load byte from source, store to destination, increment counter.
6486
    try switchToAndSeal(self, body);
6487
6488
    let srcElem = emitElem(self, 1, src, il::Val::Reg(iReg));
6489
    let byteReg = nextReg(self);
6490
    emit(self, il::Instr::Load { typ: il::Type::W8, dst: byteReg, src: srcElem, offset: 0 });
6491
6492
    let dstElem = emitElem(self, 1, dst, il::Val::Reg(iReg));
6493
    emit(self, il::Instr::Store { typ: il::Type::W8, src: il::Val::Reg(byteReg), dst: dstElem, offset: 0 });
6494
6495
    let nextI = emitTypedBinOp(self, il::BinOp::Add, il::Type::W32, il::Val::Reg(iReg), il::Val::Imm(1));
6496
    // Jump back to header -- this adds body as a predecessor.
6497
    try emitJmpWithArg(self, header, nextI);
6498
6499
    // Now all predecessors of header are known, seal it.
6500
    try sealBlock(self, header);
6501
    try switchToAndSeal(self, done);
6502
}
6503
6504
/// Lower `slice.append(val, allocator)`.
6505
///
6506
/// Emits inline grow-if-needed logic:
6507
///
6508
///     load len, cap from slice header
6509
///     if len < cap: jmp @store
6510
///     else:         jmp @grow
6511
///
6512
///     @grow:
6513
///       newCap = max(cap * 2, 1)
6514
///       call allocator.func(allocator.ctx, newCap * stride, alignment)
6515
///       copy old data to new pointer
6516
///       update slice ptr and cap
6517
///       jmp @store
6518
///
6519
///     @store:
6520
///       store element at ptr + len * stride
6521
///       increment len
6522
///
6523
fn lowerSliceAppend(self: *mut FnLowerer, call: ast::Call, elemType: *resolver::Type) -> il::Val throws (LowerError) {
6524
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
6525
        else throw LowerError::MissingMetadata;
6526
6527
    // Get the address of the slice header.
6528
    let sliceVal = try lowerExpr(self, access.parent);
6529
    let sliceReg = emitValToReg(self, sliceVal);
6530
6531
    // Lower the value to append and the allocator.
6532
    let elemVal = try lowerExpr(self, call.args[0]);
6533
    let allocVal = try lowerExpr(self, call.args[1]);
6534
    let allocReg = emitValToReg(self, allocVal);
6535
6536
    let elemLayout = resolver::getTypeLayout(*elemType);
6537
    let stride = elemLayout.size;
6538
    let alignment = elemLayout.alignment;
6539
6540
    // Load current length and capacity.
6541
    let lenVal = loadSliceLen(self, sliceReg);
6542
    let capVal = loadSliceCap(self, sliceReg);
6543
6544
    // Branch: if length is smaller than capacity, go to @store else @grow.
6545
    let storeBlock = try createBlock(self, "append.store");
6546
    let growBlock = try createBlock(self, "append.grow");
6547
    try emitBrCmp(self, il::CmpOp::Ult, il::Type::W32, lenVal, capVal, storeBlock, growBlock);
6548
    try switchToAndSeal(self, growBlock);
6549
6550
    // -- @grow block ----------------------------------------------------------
6551
6552
    // `newCap = max(cap * 2, 1)`.
6553
    // We are only here when at capacity, so we use `or` with `1` to ensure at least capacity `1`.
6554
    let doubledVal = emitTypedBinOp(self, il::BinOp::Shl, il::Type::W32, capVal, il::Val::Imm(1));
6555
    let newCapVal = emitTypedBinOp(self, il::BinOp::Or, il::Type::W32, doubledVal, il::Val::Imm(1));
6556
6557
    // Call allocator: `a.func(a.ctx, newCap * stride, alignment)`.
6558
    let allocFnReg = nextReg(self);
6559
    emitLoadW64At(self, allocFnReg, allocReg, 0);
6560
6561
    let allocCtxReg = nextReg(self);
6562
    emitLoadW64At(self, allocCtxReg, allocReg, 8);
6563
6564
    let byteSize = emitTypedBinOp(self, il::BinOp::Mul, il::Type::W32, newCapVal, il::Val::Imm(stride as i64));
6565
    let args = try allocVals(self, 3);
6566
6567
    set args[0] = il::Val::Reg(allocCtxReg);
6568
    set args[1] = byteSize;
6569
    set args[2] = il::Val::Imm(alignment as i64);
6570
6571
    let newPtrReg = nextReg(self);
6572
    emit(self, il::Instr::Call {
6573
        retTy: il::Type::W64,
6574
        dst: newPtrReg,
6575
        func: il::Val::Reg(allocFnReg),
6576
        args,
6577
    });
6578
6579
    // Copy old data byte-by-byte.
6580
    let oldPtrReg = loadSlicePtr(self, sliceReg);
6581
    let copyBytes = emitTypedBinOp(self, il::BinOp::Mul, il::Type::W32, lenVal, il::Val::Imm(stride as i64));
6582
    try emitByteCopyLoop(self, newPtrReg, oldPtrReg, copyBytes, "append");
6583
6584
    // Update slice header.
6585
    emitStoreW64At(self, il::Val::Reg(newPtrReg), sliceReg, SLICE_PTR_OFFSET);
6586
    emitStoreW32At(self, newCapVal, sliceReg, SLICE_CAP_OFFSET);
6587
6588
    try emitJmp(self, storeBlock);
6589
    try switchToAndSeal(self, storeBlock);
6590
6591
    // -- @store block ---------------------------------------------------------
6592
6593
    // Store element at `ptr + len * stride`.
6594
    let ptrReg = loadSlicePtr(self, sliceReg);
6595
    let elemDst = emitElem(self, stride, ptrReg, lenVal);
6596
    try emitStore(self, elemDst, 0, *elemType, elemVal);
6597
6598
    // Increment len.
6599
    let newLen = emitTypedBinOp(self, il::BinOp::Add, il::Type::W32, lenVal, il::Val::Imm(1));
6600
    emitStoreW32At(self, newLen, sliceReg, SLICE_LEN_OFFSET);
6601
6602
    return il::Val::Reg(sliceReg);
6603
}
6604
6605
/// Lower `slice.delete(index)`.
6606
///
6607
/// Bounds-check the index, shift elements after it by one stride
6608
/// via a byte-copy loop, and decrement `len`.
6609
fn lowerSliceDelete(self: *mut FnLowerer, call: ast::Call, elemType: *resolver::Type) throws (LowerError) {
6610
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
6611
        else throw LowerError::MissingMetadata;
6612
6613
    let elemLayout = resolver::getTypeLayout(*elemType);
6614
    let stride = elemLayout.size;
6615
6616
    // Get slice header address.
6617
    let sliceVal = try lowerExpr(self, access.parent);
6618
    let sliceReg = emitValToReg(self, sliceVal);
6619
6620
    // Lower the index argument.
6621
    let indexVal = try lowerExpr(self, call.args[0]);
6622
6623
    // Load len and bounds-check: index must be smaller than length.
6624
    let lenVal = loadSliceLen(self, sliceReg);
6625
    try emitTrapUnlessCmp(self, il::CmpOp::Ult, il::Type::W32, indexVal, lenVal);
6626
6627
    // Compute the destination and source for the shift.
6628
    let ptrReg = loadSlicePtr(self, sliceReg);
6629
    let dst = emitElem(self, stride, ptrReg, indexVal);
6630
6631
    // `src = dst + stride`.
6632
    let src = emitPtrOffset(self, dst, stride as i32);
6633
6634
    // Move `(len - index - 1) * stride`.
6635
    let tailLen = emitTypedBinOp(self, il::BinOp::Sub, il::Type::W32, lenVal, indexVal);
6636
    let tailLenMinusOne = emitTypedBinOp(self, il::BinOp::Sub, il::Type::W32, tailLen, il::Val::Imm(1));
6637
    let moveBytes = emitTypedBinOp(self, il::BinOp::Mul, il::Type::W32, tailLenMinusOne, il::Val::Imm(stride as i64));
6638
6639
    // Shift elements left via byte-copy loop.
6640
    // When deleting the last element, the loop is a no-op.
6641
    try emitByteCopyLoop(self, dst, src, moveBytes, "delete");
6642
    // Decrement length.
6643
    let newLen = emitTypedBinOp(self, il::BinOp::Sub, il::Type::W32, lenVal, il::Val::Imm(1));
6644
6645
    emitStoreW32At(self, newLen, sliceReg, SLICE_LEN_OFFSET);
6646
}
6647
6648
/// Lower a call expression, which may be a function call or type constructor.
6649
fn lowerCallOrCtor(self: *mut FnLowerer, node: *ast::Node, call: ast::Call) -> il::Val throws (LowerError) {
6650
    let nodeData = resolver::nodeData(self.low.resolver, node).extra;
6651
6652
    // Check for slice method dispatch.
6653
    if let case resolver::NodeExtra::SliceAppend { elemType } = nodeData {
6654
        return try lowerSliceAppend(self, call, elemType);
6655
    }
6656
    if let case resolver::NodeExtra::SliceDelete { elemType } = nodeData {
6657
        try lowerSliceDelete(self, call, elemType);
6658
        return il::Val::Undef;
6659
    }
6660
    // Check for trait method dispatch.
6661
    if let case resolver::NodeExtra::TraitMethodCall { traitInfo, methodIndex } = nodeData {
6662
        return try lowerTraitMethodCall(self, node, call, traitInfo, methodIndex);
6663
    }
6664
    // Check for standalone method call.
6665
    if let case resolver::NodeExtra::MethodCall { method } = nodeData {
6666
        return try lowerMethodCall(self, node, call, method);
6667
    }
6668
    if let sym = resolver::nodeData(self.low.resolver, call.callee).sym {
6669
        if let case resolver::SymbolData::Type(nominal) = sym.data {
6670
            let case resolver::NominalType::Record(_) = *nominal else {
6671
                throw LowerError::ExpectedRecord;
6672
            };
6673
            return try lowerRecordCtor(self, nominal, call.args);
6674
        }
6675
        if let case resolver::SymbolData::Variant { .. } = sym.data {
6676
            return try lowerUnionCtor(self, node, sym, call);
6677
        }
6678
    }
6679
    return try lowerCall(self, node, call);
6680
}
6681
6682
/// Lower a trait method call through v-table dispatch.
6683
///
6684
/// Given `obj.method(args)` where `obj` is a trait object, emits:
6685
///
6686
///     load w64 %data %obj 0          // data pointer
6687
///     load w64 %vtable %obj 8        // v-table pointer
6688
///     load w64 %fn %vtable <slot>    // function pointer
6689
///     call <retTy> %ret %fn(%data, args...)
6690
///
6691
fn lowerTraitMethodCall(
6692
    self: *mut FnLowerer,
6693
    node: *ast::Node,
6694
    call: ast::Call,
6695
    traitInfo: *resolver::TraitType,
6696
    methodIndex: u32
6697
) -> il::Val throws (LowerError) {
6698
    // Method calls look like field accesses.
6699
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
6700
        else throw LowerError::MissingMetadata;
6701
6702
    // Lower the trait object expression.
6703
    let traitObjVal = try lowerExpr(self, access.parent);
6704
    let traitObjReg = emitValToReg(self, traitObjVal);
6705
6706
    // Load data pointer from trait object.
6707
    let dataReg = nextReg(self);
6708
    emit(self, il::Instr::Load {
6709
        typ: il::Type::W64,
6710
        dst: dataReg,
6711
        src: traitObjReg,
6712
        offset: TRAIT_OBJ_DATA_OFFSET,
6713
    });
6714
6715
    // Load v-table pointer from trait object.
6716
    let vtableReg = nextReg(self);
6717
    emit(self, il::Instr::Load {
6718
        typ: il::Type::W64,
6719
        dst: vtableReg,
6720
        src: traitObjReg,
6721
        offset: TRAIT_OBJ_VTABLE_OFFSET,
6722
    });
6723
6724
    // Load function pointer from v-table at the method's slot offset.
6725
    let fnPtrReg = nextReg(self);
6726
    let slotOffset = (methodIndex * resolver::PTR_SIZE) as i32;
6727
6728
    emit(self, il::Instr::Load {
6729
        typ: il::Type::W64,
6730
        dst: fnPtrReg,
6731
        src: vtableReg,
6732
        offset: slotOffset,
6733
    });
6734
    let methodFnType = traitInfo.methods[methodIndex].fnType;
6735
6736
    // Build args: optional return param slot + data pointer (receiver) + user args.
6737
    let argOffset: u32 = 1 if requiresReturnParam(methodFnType) else 0;
6738
    let args = try allocVals(self, call.args.len + 1 + argOffset);
6739
    set args[argOffset] = il::Val::Reg(dataReg);
6740
6741
    for arg, i in call.args {
6742
        set args[i + 1 + argOffset] = try lowerCallArg(
6743
            self, arg, i + 1 < call.args.len
6744
        );
6745
    }
6746
    return try emitCallValue(self, il::Val::Reg(fnPtrReg), methodFnType, args);
6747
}
6748
6749
/// Lower a call argument, snapshotting aggregate place expressions before
6750
/// evaluating later arguments. Aggregates are represented by addresses in the
6751
/// IL, so retaining the original address would let a later argument mutation
6752
/// change the value already supplied for this argument.
6753
fn lowerCallArg(self: *mut FnLowerer, arg: *ast::Node, hasLater: bool) -> il::Val
6754
    throws (LowerError)
6755
{
6756
    let val = try lowerExpr(self, arg);
6757
6758
    if hasLater and ast::isPlaceExpr(arg) {
6759
        let argType = try effectiveType(self, arg);
6760
        if isAggregateType(argType) {
6761
            return try emitStackVal(self, argType, val);
6762
        }
6763
    }
6764
    return val;
6765
}
6766
6767
/// Emit a function call with return-parameter and small-aggregate handling.
6768
///
6769
/// All call lowering paths (regular, trait method, standalone method) converge
6770
/// here after preparing the callee value, function type, and argument array.
6771
/// The `args` slice must already include a slot at index zero for the hidden
6772
/// return parameter; that slot is filled by this function.
6773
fn emitCallValue(
6774
    self: *mut FnLowerer,
6775
    callee: il::Val,
6776
    fnInfo: *resolver::FnType,
6777
    args: *mut [il::Val],
6778
) -> il::Val throws (LowerError) {
6779
    let retTy = *fnInfo.returnType;
6780
6781
    if requiresReturnParam(fnInfo) {
6782
        if fnInfo.throwList.len > 0 {
6783
            let layout = resolver::getResultLayout(retTy, fnInfo.throwList);
6784
            set args[0] = il::Val::Reg(emitReserveLayout(self, layout));
6785
        } else {
6786
            set args[0] = il::Val::Reg(try emitReserve(self, retTy));
6787
        }
6788
        let dst = nextReg(self);
6789
6790
        emit(self, il::Instr::Call {
6791
            retTy: il::Type::W64,
6792
            dst,
6793
            func: callee,
6794
            args,
6795
        });
6796
        return il::Val::Reg(dst);
6797
    }
6798
    let mut dst: ?il::Reg = nil;
6799
    if retTy <> resolver::Type::Void {
6800
        set dst = nextReg(self);
6801
    }
6802
    emit(self, il::Instr::Call {
6803
        retTy: ilType(self.low, retTy),
6804
        dst,
6805
        func: callee,
6806
        args,
6807
    });
6808
6809
    if let d = dst {
6810
        if isSmallAggregate(retTy) {
6811
            let slot = emitReserveLayout(self, resolver::Layout {
6812
                size: resolver::PTR_SIZE,
6813
                alignment: resolver::PTR_SIZE,
6814
            });
6815
            emit(self, il::Instr::Store {
6816
                typ: il::Type::W64,
6817
                src: il::Val::Reg(d),
6818
                dst: slot,
6819
                offset: 0,
6820
            });
6821
            return il::Val::Reg(slot);
6822
        }
6823
        return il::Val::Reg(d);
6824
    }
6825
    return il::Val::Undef;
6826
}
6827
6828
/// Lower a method receiver expression to a pointer value.
6829
///
6830
/// If the parent is already a pointer type, the value is used directly.
6831
/// If the parent is a value type (eg. a local record), its address is taken.
6832
fn lowerReceiver(self: *mut FnLowerer, parent: *ast::Node, parentTy: resolver::Type) -> il::Val
6833
    throws (LowerError)
6834
{
6835
    if let case resolver::Type::Pointer { .. } = parentTy {
6836
        // Already a pointer: lower and use directly.
6837
        return try lowerExpr(self, parent);
6838
    }
6839
    // Value type: take its address by lowering it and returning the slot pointer.
6840
    // Aggregate types are already lowered as pointers to stack slots.
6841
    let val = try lowerExpr(self, parent);
6842
    if isAggregateType(parentTy) {
6843
        return val;
6844
    }
6845
    // Scalar value: store to a stack slot and return the slot pointer.
6846
    let layout = resolver::getLayout(self.low.resolver, parent, parentTy);
6847
    let slot = emitReserveLayout(self, layout);
6848
    try emitStore(self, slot, 0, parentTy, val);
6849
6850
    return il::Val::Reg(slot);
6851
}
6852
6853
/// Lower a standalone method call via direct dispatch.
6854
///
6855
/// Given `obj.method(args)` where `method` is a standalone method on a concrete type,
6856
/// emits a direct call with the receiver address as the first argument:
6857
///
6858
///     call <retTy> %ret @Type::method(&obj, args...)
6859
///
6860
fn lowerMethodCall(
6861
    self: *mut FnLowerer,
6862
    node: *ast::Node,
6863
    call: ast::Call,
6864
    method: *resolver::MethodEntry,
6865
) -> il::Val throws (LowerError) {
6866
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
6867
        else throw LowerError::MissingMetadata;
6868
6869
    // Get the receiver as a pointer.
6870
    let parentTy = try typeOf(self, access.parent);
6871
    let receiverVal = try lowerReceiver(self, access.parent, parentTy);
6872
6873
    let qualName = instanceMethodName(self.low, nil, method.concreteTypeName, method.name);
6874
    let case resolver::SymbolData::Value { type: resolver::Type::Fn(fnInfo), .. } = method.symbol.data
6875
        else panic "lowerMethodCall: expected Fn type on method symbol";
6876
6877
    // Build args: optional return param slot + receiver + user args.
6878
    let argOffset: u32 = 1 if requiresReturnParam(fnInfo) else 0;
6879
    let args = try allocVals(self, call.args.len + 1 + argOffset);
6880
    set args[argOffset] = receiverVal;
6881
    for arg, i in call.args {
6882
        set args[i + 1 + argOffset] = try lowerCallArg(
6883
            self, arg, i + 1 < call.args.len
6884
        );
6885
    }
6886
    return try emitCallValue(self, il::Val::FnAddr(qualName), fnInfo, args);
6887
}
6888
6889
/// Check if a call is to a compiler intrinsic and lower it directly.
6890
fn lowerIntrinsicCall(self: *mut FnLowerer, call: ast::Call) -> ?il::Val throws (LowerError) {
6891
    // Get the callee symbol and check if it's marked as an intrinsic.
6892
    let sym = resolver::nodeData(self.low.resolver, call.callee).sym else {
6893
        // Expressions or function pointers may not have an associated symbol.
6894
        return nil;
6895
    };
6896
    if not ast::hasAttribute(sym.attrs, ast::Attribute::Intrinsic) {
6897
        return nil;
6898
    }
6899
    // Check for known intrinsic names.
6900
    if mem::eq(sym.name, "ecall") {
6901
        return try lowerEcall(self, call);
6902
    } else if mem::eq(sym.name, "ebreak") {
6903
        return try lowerEbreak(self, call);
6904
    } else if mem::eq(sym.name, "memoryFence") {
6905
        return try lowerMemoryFence(self, call);
6906
    } else {
6907
        throw LowerError::UnknownIntrinsic;
6908
    }
6909
}
6910
6911
/// Lower an ecall intrinsic: `ecall(num, a0, a1, a2, a3) -> i64`.
6912
fn lowerEcall(self: *mut FnLowerer, call: ast::Call) -> il::Val throws (LowerError) {
6913
    if call.args.len <> 5 {
6914
        throw LowerError::InvalidArgCount;
6915
    }
6916
    let num = try lowerExpr(self, call.args[0]);
6917
    let a0 = try lowerExpr(self, call.args[1]);
6918
    let a1 = try lowerExpr(self, call.args[2]);
6919
    let a2 = try lowerExpr(self, call.args[3]);
6920
    let a3 = try lowerExpr(self, call.args[4]);
6921
    let dst = nextReg(self);
6922
6923
    emit(self, il::Instr::Ecall { dst, num, a0, a1, a2, a3 });
6924
6925
    return il::Val::Reg(dst);
6926
}
6927
6928
/// Lower an ebreak intrinsic: `ebreak()`.
6929
fn lowerEbreak(self: *mut FnLowerer, call: ast::Call) -> il::Val throws (LowerError) {
6930
    if call.args.len <> 0 {
6931
        throw LowerError::InvalidArgCount;
6932
    }
6933
    emit(self, il::Instr::Ebreak);
6934
6935
    return il::Val::Undef;
6936
}
6937
6938
/// Lower `memoryFence()`.
6939
fn lowerMemoryFence(self: *mut FnLowerer, call: ast::Call) -> il::Val throws (LowerError) {
6940
    if call.args.len <> 0 {
6941
        throw LowerError::InvalidArgCount;
6942
    }
6943
    emit(self, il::Instr::MemoryFence);
6944
    return il::Val::Undef;
6945
}
6946
6947
/// Resolve callee to an IL value. For direct function calls, use the symbol name.
6948
/// For variables holding function pointers or complex expressions (eg. `array[i]()`),
6949
/// lower the callee expression.
6950
fn lowerCallee(self: *mut FnLowerer, callee: *ast::Node) -> il::Val throws (LowerError) {
6951
    if let sym = resolver::nodeData(self.low.resolver, callee).sym {
6952
        if let case ast::NodeValue::FnDecl(_) = sym.node.value {
6953
            // First try to look up the symbol in our registered functions.
6954
            // This handles cross-package calls correctly, since packages are
6955
            // lowered in dependency order.
6956
            if let qualName = lookupFnSym(self.low, sym) {
6957
                return il::Val::FnAddr(qualName);
6958
            }
6959
            // Fall back to computing the qualified name from the module graph.
6960
            // This works for functions in the current package.
6961
            let modId = resolver::moduleIdForSymbol(self.low.resolver, sym) else {
6962
                throw LowerError::MissingMetadata;
6963
            };
6964
            return il::Val::FnAddr(qualifyName(self.low, modId, sym.name));
6965
        }
6966
    }
6967
    return try lowerExpr(self, callee);
6968
}
6969
6970
/// Lower a function call expression.
6971
fn lowerCall(self: *mut FnLowerer, node: *ast::Node, call: ast::Call) -> il::Val throws (LowerError) {
6972
    // Check for intrinsic calls before normal call lowering.
6973
    if let intrinsicVal = try lowerIntrinsicCall(self, call) {
6974
        return intrinsicVal;
6975
    }
6976
    let calleeTy = try typeOf(self, call.callee);
6977
    let case resolver::Type::Fn(fnInfo) = calleeTy else {
6978
        throw LowerError::ExpectedFunction;
6979
    };
6980
    let callee = try lowerCallee(self, call.callee);
6981
    let offset: u32 = 1 if requiresReturnParam(fnInfo) else 0;
6982
    let args = try allocVals(self, call.args.len + offset);
6983
    for arg, i in call.args {
6984
        set args[i + offset] = try lowerCallArg(
6985
            self, arg, i + 1 < call.args.len
6986
        );
6987
    }
6988
6989
    return try emitCallValue(self, callee, fnInfo, args);
6990
}
6991
6992
/// Apply coercions requested by the resolver.
6993
fn applyCoercion(self: *mut FnLowerer, node: *ast::Node, val: il::Val) -> il::Val throws (LowerError) {
6994
    let coerce = resolver::coercionFor(self.low.resolver, node) else {
6995
        return val;
6996
    };
6997
    match coerce {
6998
        case resolver::Coercion::OptionalLift(optType) => {
6999
            if let case ast::NodeValue::Nil = node.value {
7000
                return try buildNilOptional(self, optType);
7001
            }
7002
            return try wrapInOptional(self, val, optType);
7003
        }
7004
        case resolver::Coercion::NumericCast { from, to } => {
7005
            return lowerNumericCast(self, val, from, to);
7006
        }
7007
        case resolver::Coercion::ResultWrap => {
7008
            let payloadType = *self.fnType.returnType;
7009
            return try buildResult(self, 0, val, payloadType);
7010
        }
7011
        case resolver::Coercion::TraitObject { traitInfo, inst } => {
7012
            return try buildTraitObject(self, val, traitInfo, inst);
7013
        }
7014
        case resolver::Coercion::Identity => return val,
7015
    }
7016
}
7017
7018
/// Lower an implicit numeric cast coercion.
7019
///
7020
/// Handles widening conversions between integer types. Uses sign-extension
7021
/// for signed source types and zero-extension for unsigned source types.
7022
fn lowerNumericCast(self: *mut FnLowerer, val: il::Val, srcType: resolver::Type, dstType: resolver::Type) -> il::Val {
7023
    let srcLayout = resolver::getTypeLayout(srcType);
7024
    let dstLayout = resolver::getTypeLayout(dstType);
7025
7026
    if srcLayout.size == dstLayout.size {
7027
        // Same size: bit pattern is unchanged, value is returned as-is.
7028
        return val;
7029
    }
7030
    // Widening: extend based on source signedness.
7031
    // Narrowing: truncate and normalize to destination width.
7032
    let widening = srcLayout.size < dstLayout.size;
7033
    let extType = ilType(self.low, srcType) if widening else ilType(self.low, dstType);
7034
    let signed = isSignedType(srcType) if widening else isSignedType(dstType);
7035
    let dst = nextReg(self);
7036
7037
    if signed {
7038
        emit(self, il::Instr::Sext { typ: extType, dst, val });
7039
    } else {
7040
        emit(self, il::Instr::Zext { typ: extType, dst, val });
7041
    }
7042
    return il::Val::Reg(dst);
7043
}
7044
7045
/// Lower a global value symbol.
7046
fn lowerGlobalValue(self: *mut FnLowerer, sym: *resolver::Symbol, ty: resolver::Type) -> il::Val {
7047
    // Function pointer reference: return the function's address directly.
7048
    // Functions have no separate storage cell in the data section.
7049
    if let case resolver::Type::Fn(_) = ty {
7050
        return il::Val::Reg(emitFnAddr(self, sym));
7051
    }
7052
    let src = emitDataAddr(self, sym);
7053
7054
    return emitRead(self, src, 0, ty);
7055
}
7056
7057
/// Lower an identifier that refers to a global symbol.
7058
fn lowerGlobalSymbol(self: *mut FnLowerer, node: *ast::Node) -> il::Val throws (LowerError) {
7059
    // First try to get a compile-time constant value.
7060
    if let constVal = resolver::constValueEntry(self.low.resolver, node) {
7061
        return try constValueToVal(self, constVal, node);
7062
    }
7063
    // Otherwise get the symbol.
7064
    let sym = try symOf(self, node);
7065
7066
    match sym.data {
7067
        case resolver::SymbolData::Constant { type, .. } => {
7068
            let src = emitDataAddr(self, sym);
7069
7070
            return emitRead(self, src, 0, type);
7071
        }
7072
        case resolver::SymbolData::Value { type, .. } =>
7073
            return lowerGlobalValue(self, sym, type),
7074
        else => throw LowerError::UnexpectedNodeValue(node),
7075
    }
7076
}
7077
7078
/// Lower an assignment to a static variable.
7079
fn lowerStaticAssign(self: *mut FnLowerer, target: *ast::Node, val: il::Val) throws (LowerError) {
7080
    let sym = try symOf(self, target);
7081
    let case resolver::SymbolData::Value { type, .. } = sym.data else {
7082
        throw LowerError::ImmutableAssignment;
7083
    };
7084
    let dst = emitDataAddr(self, sym);
7085
7086
    try emitStore(self, dst, 0, type, val);
7087
}
7088
7089
/// Lower a scope access expression like `Module::Const` or `Union::Variant`.
7090
/// This doesn't handle record literal variants.
7091
fn lowerScopeAccess(self: *mut FnLowerer, node: *ast::Node) -> il::Val throws (LowerError) {
7092
    // First try to get a compile-time constant value.
7093
    if let constVal = resolver::constValueEntry(self.low.resolver, node) {
7094
        return try constValueToVal(self, constVal, node);
7095
    }
7096
    // Otherwise get the associated symbol.
7097
    let data = resolver::nodeData(self.low.resolver, node);
7098
    let sym = data.sym else {
7099
        throw LowerError::MissingSymbol(node);
7100
    };
7101
    match sym.data {
7102
        case resolver::SymbolData::Variant { index, .. } => {
7103
            let mut indexValue = index as i64;
7104
            if let idx = voidVariantIndex(self.low.resolver, node) {
7105
                set indexValue = idx;
7106
            }
7107
            // Void union variant like `Option::None`.
7108
            if data.ty == resolver::Type::Unknown {
7109
                throw LowerError::MissingType(node);
7110
            }
7111
            // All-void unions are passed as scalars (the tag byte).
7112
            // Return an immediate instead of building a tagged aggregate.
7113
            if resolver::isVoidUnion(data.ty) {
7114
                return il::Val::Imm(indexValue);
7115
            }
7116
            let unionInfo = unionInfoFromType(data.ty) else {
7117
                throw LowerError::MissingMetadata;
7118
            };
7119
            let valOffset = unionInfo.valOffset as i32;
7120
            return try buildTagged(self, resolver::getTypeLayout(data.ty), indexValue, nil, resolver::Type::Void, 1, valOffset);
7121
        }
7122
        case resolver::SymbolData::Constant { type, .. } => {
7123
            // Constant without compile-time value (e.g. record constant);
7124
            // load from data section.
7125
            let src = emitDataAddr(self, sym);
7126
7127
            // Aggregate constants live in read-only memory.  Return a
7128
            // mutable copy so that callers that assign through the
7129
            // resulting pointer do not fault.
7130
            if isAggregateType(type) {
7131
                let layout = resolver::getTypeLayout(type);
7132
                let dst = emitReserveLayout(self, layout);
7133
                emit(self, il::Instr::Blit { dst, src, size: il::Val::Imm(layout.size as i64) });
7134
7135
                return il::Val::Reg(dst);
7136
            }
7137
            return emitRead(self, src, 0, type);
7138
        }
7139
        case resolver::SymbolData::Value { type, .. } =>
7140
            return lowerGlobalValue(self, sym, type),
7141
        else =>
7142
            throw LowerError::UnexpectedNodeValue(node),
7143
    }
7144
}
7145
7146
/// Lower an expression AST node to an IL value.
7147
/// This is the main expression dispatch, all expression nodes go through here.
7148
fn lowerExpr(self: *mut FnLowerer, node: *ast::Node) -> il::Val throws (LowerError) {
7149
    if self.low.options.debug {
7150
        set self.srcLoc.offset = node.span.offset;
7151
    }
7152
    let mut val: il::Val = undefined;
7153
7154
    match node.value {
7155
        case ast::NodeValue::Ident(_) => {
7156
            // First try local variable lookup.
7157
            // Otherwise fall back to global symbol lookup.
7158
            if let v = lookupLocalVar(self, node) {
7159
                set val = try useVar(self, v);
7160
                if self.vars[*v].addressTaken {
7161
                    let typ = try typeOf(self, node);
7162
                    let ptr = emitValToReg(self, val);
7163
                    set val = emitRead(self, ptr, 0, typ);
7164
                }
7165
            } else {
7166
                set val = try lowerGlobalSymbol(self, node);
7167
            }
7168
        }
7169
        case ast::NodeValue::ScopeAccess(_) => {
7170
            set val = try lowerScopeAccess(self, node);
7171
        }
7172
        case ast::NodeValue::Number(lit) => {
7173
            set val = il::Val::Imm(lit.magnitude as i64);
7174
        }
7175
        case ast::NodeValue::Bool(b) => {
7176
            set val = il::Val::Imm(1) if b else il::Val::Imm(0);
7177
        }
7178
        case ast::NodeValue::Char(c) => {
7179
            set val = il::Val::Imm(c as i64);
7180
        }
7181
        case ast::NodeValue::Nil => {
7182
            let typ = try typeOf(self, node);
7183
            if let case resolver::Type::Optional(_) = typ {
7184
                set val = try buildNilOptional(self, typ);
7185
            } else if let case resolver::Type::Nil = typ {
7186
                // Standalone `nil` without a concrete optional type. We can't
7187
                // generate a proper value representation.
7188
                throw LowerError::MissingType(node);
7189
            } else {
7190
                throw LowerError::NilInNonOptional;
7191
            }
7192
        }
7193
        case ast::NodeValue::RecordLit(lit) => {
7194
            set val = try lowerRecordLit(self, node, lit);
7195
        }
7196
        case ast::NodeValue::AddressOf(addr) => {
7197
            set val = try lowerAddressOf(self, node, addr);
7198
        }
7199
        case ast::NodeValue::Deref(target) => {
7200
            set val = try lowerDeref(self, node, target);
7201
        }
7202
        case ast::NodeValue::BinOp(binop) => {
7203
            set val = try lowerBinOp(self, node, binop);
7204
        }
7205
        case ast::NodeValue::UnOp(unop) => {
7206
            set val = try lowerUnOp(self, node, unop);
7207
        }
7208
        case ast::NodeValue::Subscript { container, index } => {
7209
            set val = try lowerSubscript(self, node, container, index);
7210
        }
7211
        case ast::NodeValue::BuiltinCall { kind, args } => {
7212
            set val = try lowerBuiltinCall(self, node, kind, args);
7213
        }
7214
        case ast::NodeValue::Call(call) => {
7215
            set val = try lowerCallOrCtor(self, node, call);
7216
        }
7217
        case ast::NodeValue::Try(t) => {
7218
            set val = try lowerTry(self, node, t);
7219
        }
7220
        case ast::NodeValue::FieldAccess(access) => {
7221
            // Check for compile-time constant (e.g., `arr.len` on fixed-size arrays).
7222
            if let constVal = resolver::constValueEntry(self.low.resolver, node) {
7223
                match constVal {
7224
                    // TODO: Handle `u32` values that don't fit in an `i32`.
7225
                    //       Perhaps just store the `ConstInt`.
7226
                    case resolver::ConstValue::Int(i) => set val = il::Val::Imm(constIntToI64(i)),
7227
                    else => set val = try lowerFieldAccess(self, access),
7228
                }
7229
            } else {
7230
                set val = try lowerFieldAccess(self, access);
7231
            }
7232
        }
7233
        case ast::NodeValue::ArrayLit(elements) => {
7234
            set val = try lowerArrayLit(self, node, elements);
7235
        }
7236
        case ast::NodeValue::ArrayRepeatLit(repeat) => {
7237
            set val = try lowerArrayRepeatLit(self, node, repeat);
7238
        }
7239
        case ast::NodeValue::As(cast) => {
7240
            set val = try lowerCast(self, node, cast);
7241
        }
7242
        case ast::NodeValue::CondExpr(cond) => {
7243
            set val = try lowerCondExpr(self, node, cond);
7244
        }
7245
        case ast::NodeValue::String(s) => {
7246
            set val = try lowerStringLit(self, node, s);
7247
        }
7248
        case ast::NodeValue::Undef => {
7249
            let typ = try typeOf(self, node);
7250
            if isAggregateType(typ) {
7251
                // When `undefined` appears as a stand-alone expression,
7252
                /// we need a stack slot for reads and writes.
7253
                let slot = try emitReserve(self, typ);
7254
                set val = il::Val::Reg(slot);
7255
            } else {
7256
                set val = il::Val::Undef;
7257
            }
7258
        }
7259
        case ast::NodeValue::Panic { .. } => {
7260
            // Panic in expression context (e.g. match arm). Emit unreachable
7261
            // and return a dummy value since control won't continue.
7262
            emit(self, il::Instr::Unreachable);
7263
            set val = il::Val::Undef;
7264
        }
7265
        case ast::NodeValue::Assert { .. } => {
7266
            // Assert in expression context. Lower as statement, return `void`.
7267
            try lowerNode(self, node);
7268
            set val = il::Val::Undef;
7269
        }
7270
        case ast::NodeValue::Block(_) => {
7271
            try lowerBlock(self, node);
7272
            set val = il::Val::Undef;
7273
        }
7274
        case ast::NodeValue::Unsafe(body) => {
7275
            set val = try lowerExpr(self, body);
7276
        }
7277
        case ast::NodeValue::ExprStmt(expr) => {
7278
            let _ = expr;
7279
            set val = il::Val::Undef;
7280
        }
7281
        // Lower these as statements.
7282
        case ast::NodeValue::ConstDecl(decl) => {
7283
            try registerLocalDataDeclName(self, node);
7284
            try lowerDataDecl(self.low, node, decl.value, true);
7285
            set val = il::Val::Undef;
7286
        }
7287
        case ast::NodeValue::StaticDecl(decl) => {
7288
            try registerLocalDataDeclName(self, node);
7289
            try lowerDataDecl(self.low, node, decl.value, false);
7290
            set val = il::Val::Undef;
7291
        }
7292
        case ast::NodeValue::Throw { .. },
7293
             ast::NodeValue::Return { .. },
7294
             ast::NodeValue::Continue,
7295
             ast::NodeValue::Break => {
7296
            try lowerNode(self, node);
7297
            set val = il::Val::Undef;
7298
        }
7299
        else => {
7300
            panic "lowerExpr: node is not an expression";
7301
        }
7302
    }
7303
    return try applyCoercion(self, node, val);
7304
}
7305
7306
/// Translate a Radiance type to an IL type.
7307
///
7308
/// The IL type system is much simpler than Radiance's, only primitive types
7309
/// are used. If a Radiance type doesn't fit in a machine word, it is passed
7310
/// by reference.
7311
///
7312
/// The IL doesn't track signedness - that's encoded in the instructions
7313
/// (e.g., Slt vs Ult).
7314
fn ilType(self: *mut Lowerer, typ: resolver::Type) -> il::Type {
7315
    match typ {
7316
        case resolver::Type::Bool,
7317
             resolver::Type::I8,
7318
             resolver::Type::U8 => return il::Type::W8,
7319
        case resolver::Type::I16,
7320
             resolver::Type::U16 => return il::Type::W16,
7321
        case resolver::Type::I32,
7322
             resolver::Type::U32 => return il::Type::W32,
7323
        case resolver::Type::I64,
7324
             resolver::Type::U64,
7325
             resolver::Type::Pointer { .. },
7326
             resolver::Type::Slice { .. },
7327
             resolver::Type::TraitObject { .. },
7328
             resolver::Type::Array(_),
7329
             resolver::Type::Optional(_),
7330
             resolver::Type::Fn(_) => return il::Type::W64,
7331
        case resolver::Type::Nominal(_) => {
7332
            if resolver::isVoidUnion(typ) {
7333
                return il::Type::W8;
7334
            }
7335
            return il::Type::W64;
7336
        }
7337
        case resolver::Type::Void => return il::Type::W64,
7338
        // [`Type::Int`] is the type of unsuffixed integer literals and their
7339
        // compound expressions (e.g. `1 + 2`). It defaults to W64 (i64) here,
7340
        // matching the native word size on RV64. It cannot be resolved earlier
7341
        // because the resolver uses [`Type::Int`] to distinguish unsuffixed
7342
        // expressions from explicitly typed ones, which affects coercion
7343
        // behavior (e.g. implicit narrowing).
7344
        case resolver::Type::Int => return il::Type::W64,
7345
        case resolver::Type::Opaque => panic "ilType: opaque type must be behind a pointer",
7346
        else => panic "ilType: type cannot be lowered",
7347
    }
7348
}