dymokomi/luce-base
Source of release 0.41.0
0.41.0 / src / back / ir / lower / module.lucb
#==============================================================================================
#
# lower - The checked tree to the intermediate representation
#
# DESCRIPTION:
# The native backend's front half: every function instance of the program becomes an
# `ir.Function`. Locals live in stack slots; scalars move through temporaries; every
# aggregate (records, tuples, tagged optionals, results, arrays, text views, spans,
# interface views) lives in memory and is addressed, copied with `blit`, and passed
# to calls by address for the target to classify (base.md §19.2).
#
# The semantic decisions mirror the C backend's: monomorphisation from a worklist,
# conversions at the sites where the checker allowed them, cleanup of deferred calls
# at every exit, failure as a flag beside the value. Where the C backend leans on the
# host compiler, this one spells the operation out: a checked add is `addo`, a bounds
# check is `bounds`, a switch is a chain of compares.
#
# This fragment holds the `Lowerer` with its fields; each concern's methods are in a
# fragment of their own under `extend Lowerer:`, in the order `ORDER` lists them
# (§16.1), parallel to the C backend's.
#
#==============================================================================================
from back.effects import arguments_have_effect
import back.ir.ir
import back.exits
import back.instances
import back.isa
import back.names
import back.calls
import back.target as targets
import front.ast
import front.source as sources
import memory
import sema.check
import sema.types
import support.buffer
import support.decimal
import support.hashed
import support.list
import support.literals
## The native backend does not support the build's target (§19.5).
pub let native_unsupported: ErrorCode = ErrorCode.package(14)
## The function that gives a thread its `local var`s' initialisers (`thread_locals_initialiser`).
let thread_locals_function: str = "lb_init_thread_locals"
## The largest `memcpy` of a known size lowered to the copy itself (`small_copy`): the
## generators inline a block copy up to this size.
let small_copy_limit: u64 = 64
## The size of a `core.FormatBuffer`: its data, capacity, used count and growth.
let format_buffer_size: u32 = 32
type NodeRef = ast.Node*
type MaybeNode = ast.Node*?
## A witness table the program needs: one record viewed as one interface.
struct LowerWitness:
var record: u32
var iface: u32
## A binding of the body being lowered and the slot holding it.
struct LowerLocal:
var decl: ast.Node*
var slot: u32
## A supplied argument evaluated in source order, before ABI parameter ordering.
struct LowerCallArgument:
var node: ast.Node*
var value: ir.Arg
## An extern call's `out` parameters (§17.1): a slot for each, read after the call, and
## its type; at most eight.
struct LowerOuts:
var slots: u32[8]
var slot_types: u32[8]
var count: usize
## A loop `for i in 0..<count` being built (`count_up`, `count_on`): the index's slot, the
## labels of its test and its exit, and the index read at the top of the body.
struct Counting:
var counter: u32
var head: u32
var done: u32
var index: ir.Ref
## A `for` loop being lowered: the labels of its test, its body, its step (where
## `continue` goes), and its exit.
struct LowerLoop:
var head: u32
var body: u32
var step: u32
var exit: u32
## A walk of a `for` loop over a sequence: the slots of its data pointer, its count, its
## index, and the width of text's last scalar, which outlive the loop's blocks; its
## elements' type and stride; and, in the body, the data pointer, the count, the index, and
## the element's address read at its top.
struct LowerWalk:
var data_slot: u32
var count_slot: u32
var index_slot: u32
var width_slot: u32
var element_type: u32
var stride: u64
var base: ir.Ref
var count: ir.Ref
var index: ir.Ref
var address: ir.Ref
## A value: a scalar in `ref`, or the address of its bytes when `in_memory`.
pub struct LowerValue:
## The scalar value, or the address of the value's bytes when `in_memory`.
pub var ref: ir.Ref
## The value's type.
pub var type_id: u32
## Whether `ref` is the address of the value's bytes rather than the value itself.
pub var in_memory: bool
# mark: The lowerer ============================================================================
## `assert failed: condition`, and `: message` when one is given (§11.6), in an allocation
## of its own length; the position is the trap's (§11.5).
func assert_text(condition: str, message: str) -> str!:
var length = 32 + condition.length
if message.length > 0:
length += 2 + message.length
let room = try new u8[length] ---
if message.length > 0:
return try strings.format(room, f"assert failed: {condition}: {message}")
return try strings.format(room, f"assert failed: {condition}")
## The native backend's front half: it lowers each function instance to an `ir.Function`.
pub struct Lowerer:
var c: check.Checker*
## The lowered program, filled as functions are visited.
pub var program_unit: ir.Unit
## Per type, the shape recorded for it (1-based), 0 until asked.
var shape_cache: list.List[u32]
var f: ir.Function
var scratch: buffer.Buffer
var modules: list.List[NodeRef]
var entry: ast.Node*
var funcs: instances.Instances
## An open-addressing index over `funcs` by declaration, owner and type arguments: a
## slot holds 1 + the instance's index, 0 when free. A program asks for an instance at
## every call; a search through all of them made lowering grow with their square.
var tests: list.List[NodeRef]
var vtables: list.List[LowerWitness]
## `--debug`: describe every frame and call the `debug` module at every statement.
pub var debug: bool
## `--release --debug`: the program's functions carry lines and describe their locals
## without the debugger's hooks (`Function.symbols`).
pub var symbols: bool
var current_fn: ast.Node*?
## The source `set_position` found for `position_fn` while `src_file` was
## `position_file`: every statement of a function asks again.
var position_fn: ast.Node*? = none
var position_file: str = ""
var position_source: sources.Source? = none
## The project root, with its trailing slash, that positions name a source relative to,
## as the build cache's key does; empty to name sources as they were read.
pub var position_root: str = ""
var generic: instances.Generic
var locals: list.List[LowerLocal]
var scopes: list.List[exits.Scope]
var defers: list.List[NodeRef]
## The slot the function's result is built in before every `ret`.
var result_slot: u32
var self_slot: u32
var catch_slot: u32
var catch_done: u32
var catch_scope: usize
var catch_payload: u32
var catch_error_slot: u32
var in_catch: bool
## While evaluating a handled operand, propagation enters this local handler.
var failure_target: u32 = 0
var failure_slot: u32 = 0
var failure_scope: usize = 0
## While lowering the `error(...)` alternative of an `x else error(...)` over a fallible
## `x`: 1 + the slot holding the message of `x`'s error, which the new one replaces.
var else_replaced: u32 = 0
## The growing format buffers (`core.format_grows`) of the calls whose arguments are
## being lowered, by slot: each call releases its own once it returns, and an exit
## taken from inside the arguments releases those it leaves behind.
var grown: list.List[u32]
## How many of `grown` were there when the innermost `catch` began: a failure caught
## there releases only those after.
var failure_grown: usize = 0
var match_slot: u32
var match_type: u32
var src_file: str
## The statement being lowered, as a trap names it (§11.5): its mapped position, and
## the unit's text of it once one was needed (index + 1; 0 while none was)
var at_file: str
var at_line: u32
var at_column: u32
var at_text: u32
var mode: u32
## The format buffer a `Display` field writes into, while lowering its call.
var format_sink: ir.Ref
## The function's pool of 1024-byte format buffers (a `fmt` argument's, a streamed
## print's): the chars and buffer slots of each made so far, and how many the statement
## being lowered and those around it hold. A statement gives back what it took when it
## ends, so the f-strings of disjoint statements share one buffer, where each call site
## once had its own (luce-js COMPILER-REQUESTS item 6: a 3.4 KB frame for three).
var pool_chars: u32[16]
var pool_fb: u32[16]
var pool_count: usize = 0
var pool_used: usize = 0
## Whether this function's format buffers may live in the dynamic area (`memory.frame`
## and those levels do not mix).
var pooling: bool = true
## `--profile diagnostic`: `---` storage is filled with a pattern, the allocator quarantines.
pub var diagnostic: bool
## The target of the build (§19.5): which `asm` arms are taken and how a library
## initialises itself depend on it.
pub var target: targets.Target
## The line of the allocation being lowered, for the diagnostic profile's record.
var site_line: u32
## The globals whose initialiser was laid out as their bytes (`static_data`), by name:
## no initialiser function stores them.
var laid_out: hashed.Table[str]
## Lowering on demand (`lower_reached`): each instance's name, by index and by name;
## whether each was queued; the queue and how far it was lowered; how many of the
## unit's functions were scanned for what they name; the assembly texts seen.
var reach_names: list.List[str]
var reach_by_name: hashed.Table[str]
var reach_named: usize = 0
var reach_wanted: list.List[bool]
var reach_queue: list.List[usize]
var reach_next: usize = 0
var reach_scanned: usize = 0
var reach_asm: list.List[str]
## The witness tables by name, and whether each one's methods were reached.
var reach_tables: hashed.Table[str]
var reach_tables_done: list.List[bool]
## The standard globals' initialisers: by their own name, by their global's name, and
## those scanned once their global was named.
var reach_initialisers: hashed.Table[str]
var reach_global_inits: hashed.Table[str]
var reach_inits_done: hashed.Table[str]
## The checker's modules by name, for each function's package (`package_of`).
var module_packages: hashed.Table[str]
## A lowerer for `entry`, checked by `c`.
pub static func create(c: check.Checker*, entry: ast.Node*) -> Lowerer!:
return Lowerer(c = c, program_unit = try ir.Unit.create(), shape_cache = try list.List[u32].create(256), f = try ir.Function.create(""), scratch = try buffer.Buffer.create(256), debug = false, symbols = false, target = targets.Target.host(),
modules = try list.List[NodeRef].create(16), entry = entry,
funcs = try instances.Instances.create(), tests = try list.List[NodeRef].create(32),
vtables = try list.List[LowerWitness].create(16), current_fn = none,
generic = try instances.Generic.none_yet(),
locals = try list.List[LowerLocal].create(64), scopes = try list.List[exits.Scope].create(32),
defers = try list.List[NodeRef].create(32), result_slot = 0, self_slot = 0, catch_slot = 0,
catch_done = 0, catch_scope = 0, catch_payload = 0, catch_error_slot = 0, in_catch = false, match_slot = 0,
match_type = 0, src_file = entry.text, at_file = entry.text, at_line = 0, at_column = 0, at_text = 0, mode = 0, format_sink = ir.none_ref(), diagnostic = false, site_line = 0,
grown = try list.List[u32].create(8), laid_out = try hashed.Table[str].create(64),
reach_names = try list.List[str].create(256), reach_by_name = try hashed.Table[str].create(256),
reach_wanted = try list.List[bool].create(256), reach_queue = try list.List[usize].create(256),
reach_asm = try list.List[str].create(4), reach_tables = try hashed.Table[str].create(16),
reach_tables_done = try list.List[bool].create(16), reach_initialisers = try hashed.Table[str].create(64),
reach_global_inits = try hashed.Table[str].create(64), reach_inits_done = try hashed.Table[str].create(64),
module_packages = try hashed.Table[str].create(64))
## Stop lowering with a diagnostic naming the file and line of `node`, and its text when
## it has one.
func fail(node: ast.Node*, what: str) -> never!:
# the checker's scratch outlives the arena the tree lives in, so the report does too
let half = self.c.scratch.length // 2
let file = self.source_of_current()
if node.text.length == 0:
error(native_unsupported, try strings.format(self.c.scratch[..<half], f"{file}:{node.line}: {what}"))
error(native_unsupported, try strings.format(self.c.scratch[..<half], f"{file}:{node.line}: {what} `{node.text}`"))