Mapal · Architecture Map

The compiler as data

Mapal's compiler seen as the data that defines it: kinds of data (categories), the things and arrows inside them, and the transformations between them. 15 components, 17 categories, 294 objects, 207 arrows, 199 transformations, 42 guarantees, 151 algorithms, data structures and patterns. Every item links to the line of code that defines it.

The compiler as data

Each box is a category: a kind of data (text, tokens, the Flow graph, facts, machine code, a running program). Each arrow is a transformation: a stage of the compiler that turns one kind of data into another. Boxes are grouped by the component that defines them; click a box to see its objects.

Inside a category, the things are objects and the ways of getting from one to another are arrows (morphisms). A functor maps a whole category into another, a process is one step with inputs and outputs, and a guarantee (natural transformation) says that two routes between the same ends give the same result.

CategoryDefined underWhat it holdsSize
TextSyntaxSource text and positions in it: .mapal files, strings, spans, line tables.6 objects, 6 arrows
TokensSyntaxThe flat list of words and symbols the lexer cuts the text into.5 objects, 2 arrows
SyntaxSyntaxThe parse tree: items, functions, chains of stages, expressions.15 objects, 7 arrows
DiagnosticsSyntaxError and warning messages with the place they refer to, whichever stage found them.9 objects, 9 arrows
NamesLoweringWhat names mean while lowering: top-level values, effects, generic sizes.6 objects, 4 arrows
TypesFlow graphMapal's types and number formats, as lowering resolves them and the graph stores them.17 objects, 15 arrows
FlowFlow graphThe dataflow graph of a program: objects (values) and morphisms (operations) in sealed functions.20 objects, 28 arrows
DiagramFlow graphPictures of a graph (Mermaid text): the flow view, category diagrams and string diagrams.3 objects, 2 arrows
FactsFactsEverything the compiler has proven about a graph, stored on the graph and read by every later stage.30 objects, 7 arrows
ValuesInterpreterWhat a program computes: scalars, arrays and records, and the error bound of a result.11 objects, 5 arrows
TargetHardware facts and rulesA chip as measurable properties (SM count, cache sizes, rates) plus the calibration lines that measured them.13 objects, 14 arrows
MachineMachine modelThe abstract machine the placement search prices: levels of memory, rates, latencies.14 objects, 8 arrows
ScheduleMachine modelA way of running a piece of work: tile shapes, launch geometry, residency, placement picks.51 objects, 44 arrows
CodeLLVM backendGenerated programs: LLVM text, device modules, PTX, object files and executables.42 objects, 17 arrows
RunRuntimeA running program: host memory, tasks, device memory, output and exit code.32 objects, 28 arrows
DriverCommand lineHow the command line drives the stages: arguments, side files, sessions.5 objects, 2 arrows
EditorLanguage server and editorsWhat an editor sees: requests, answers, colors, plugin files.15 objects, 9 arrows

Where data lives

The same objects exist in different places as the program goes from text to a running kernel. Each box below holds the main objects that live there; click one for its definition.

PlaceWhat is kept thereMain objects (with where they are defined)
The compiler's memoryEverything the compiler builds while it runs: trees, graphs, facts, plans, generated text.Program crates/mapal-syntax/src/ast.rs:28
CategoryIr (sealed graph) crates/mapal-ir/src/graph.rs:288
FuncFacts / Facts (fact store) crates/mapal-ir/src/facts.rs:25
TargetProfile crates/backends/llvm/src/profile/target.rs:8
ResidentPlan crates/backends/llvm/src/func/resident.rs:377
Emission crates/backends/llvm/src/opts.rs:198
Files on diskWhat the compiler reads and writes: sources, generated text, the program, measurements.Source file (.mapal) crates/mapal-cli/src/main.rs:215
PTX file crates/mapal-cli/src/main.rs:378
Executable crates/mapal-cli/src/main.rs:378
libmapal_rt.a crates/mapal-rt/Cargo.toml:1
Wisdom file line crates/mapal-rt/gpu/mapal_choice.h:138
calibration line benches/results/evidence/local-rtx-5080/calib/rtx-5080.calib:1
The running program: host memoryThe CPU side of a compiled program: frames, arrays, task queues, and the tables it picks kernels from.ArenaBlock (ARENA) crates/mapal-rt/src/mem.rs:55
FrameSlot (FRAME) crates/mapal-rt/src/mem.rs:149
heap array buffer crates/backends/llvm/src/func/core/ptrs.rs:367
Pool crates/mapal-rt/src/sched.rs:145
mapal_cand crates/mapal-rt/gpu/mapal_choice.h:41
choice_memo crates/mapal-rt/gpu/mapal_choice.h:125
GPU global memoryDevice buffers a GPU program allocates, copies to and from, and shares between kernels.Arena (device) crates/mapal-rt/gpu/mapal_gpu_memory.inc:42
device arena slab crates/backends/llvm/src/func/resident.rs:461
loop buffer crates/backends/cuda/src/loops.rs:61
mapal_dev_trap word crates/mapal-rt/gpu/mapal_gpu_gen.inc:109
GPU shared memory and registersOn-chip storage inside one kernel: tile staging, accumulators and per-thread values.tile registers / shared memory crates/backends/llvm/src/func/gpu/kernel_geom.rs:580
device twin crates/backends/cuda/src/kernel.rs:461

Components, in pipeline order

Every component lists the categories it defines (its data), then the transformations it makes between categories, then its guarantees and the algorithms, data structures and design patterns it uses. Every code reference is a link to the line, shown as path:line so you can also open it with nvim path +line.

SyntaxLoweringCheckerFlow graphFactsRewritesInterpreterHardware facts and rulesMachine modelLLVM backendCUDA backendVerilog backendRuntimeCommand lineLanguage server and editors

Syntax

Reads Mapal source text and gives back tokens, a parse tree and error messages. It also formats source files.

Reads Text → produces Tokens, Syntax, Diagnostics

Guarantees: Formatting keeps the tree, Lexing and parsing never fail

Files (9)

crates/mapal-syntax/src/loc.rs:1
crates/mapal-syntax/src/token.rs:1
crates/mapal-syntax/src/lexer.rs:1
crates/mapal-syntax/src/ast.rs:1
crates/mapal-syntax/src/parser.rs:1
crates/mapal-syntax/src/parser/tests.rs:1
crates/mapal-syntax/src/diag.rs:1
crates/mapal-syntax/src/format.rs:1
crates/mapal-syntax/src/lib.rs:1

Category Text

Source text and positions in it: .mapal files, strings, spans, line tables.

Objects (6)
ObjectWhat it isDefined atLives inProvided by
Source file (.mapal)The program text.crates/mapal-cli/src/main.rs:215disk, then a String on the compiler heapCommand line
SourceLoc (IR)A byte range in the source file, copied onto every object and morphism so errors point back to text.crates/mapal-ir/src/loc.rs:13compiler heap: field of Object, Morphism, FuncDefFacts, Flow graph
source: &strThe whole program text, the single source of truth; tokens and names only point into it.crates/mapal-syntax/src/lexer.rs:23compiler process heap: a String read from the .mapal file (or the editor buffer), borrowed by every later stage
LineColA 1-based line and column, used only for display.crates/mapal-syntax/src/loc.rs:49stack value, made on demand
LineIndexA table of where each line starts, so an offset can be turned into a line and column.crates/mapal-syntax/src/loc.rs:59compiler process heap: a Vec of line-start offsets borrowing the source
SourceLoc (syntax)A byte range {start, end} in the source; every token and tree node carries one.crates/mapal-syntax/src/loc.rs:12two u32 values, copied inline inside Token, tree nodes and Diagnostic
Arrows (6)
ArrowFrom → toWhat it doesDefined at
atfile, LineIndex, byte offset → 'file:line:col' stringFormat a position for a message.crates/mapal-cli/src/main.rs:194
source_dirfile path → absolute directoryThe folder a relative read path resolves against, recorded in the IR.crates/mapal-cli/src/main.rs:202
SourceLoc::len / empty_atSourceLoc → u32 / SourceLocLength of a span; a zero-width span at a point (for synthesized nodes).crates/mapal-ir/src/loc.rs:18
LineIndex::line_coloffset (u32) → LineColA byte offset becomes its line and column.crates/mapal-syntax/src/loc.rs:93
SourceLoc::new / empty_atu32 offsets → SourceLocBuild a span from two offsets, or an empty span at one point.crates/mapal-syntax/src/loc.rs:21
slice by spanSourceLoc → &strA span gives back its text as source[start..end]; names and tokens keep no text of their own.crates/mapal-syntax/src/parser.rs:171

Category Tokens

The flat list of words and symbols the lexer cuts the text into.

Objects (5)
ObjectWhat it isDefined atLives in
LexOutputThe token list (always ending in an end-of-file token) together with the lexer's errors.crates/mapal-syntax/src/lexer.rs:14compiler heap: Vec<Token> + Vec<Diagnostic>
KEYWORDSThe fixed list of reserved words.crates/mapal-syntax/src/token.rs:113a constant table in the compiler binary
GuardKindWhich guard arrow it is: -true->, -false->, -_-> or -42->; the number sits inside the arrow lexeme.crates/mapal-syntax/src/token.rs:19payload of the Guard token kind
TokenKindWhat a token is: name, literal, keyword, punctuation, operator, guard arrow, error, end of file.crates/mapal-syntax/src/token.rs:33one small tag inside each Token
TokenA kind plus its span; the text is not copied.crates/mapal-syntax/src/token.rs:11compiler heap: element of Vec<Token>, a Copy value
Arrows (2)
ArrowFrom → toWhat it doesDefined at
keyword lookup&str → TokenKindA word's text is checked against the reserved list to become a keyword token or a plain name.crates/mapal-syntax/src/token.rs:113
unescape_stringToken (string lexeme) → StringA string lexeme becomes its real text with escapes resolved.crates/mapal-syntax/src/token.rs:155

Category Syntax

The parse tree: items, functions, chains of stages, expressions.

Objects (15)
ObjectWhat it isDefined atLives inProvided by
Item (Fn, Type, Bind, Error)One top-level declaration: a function, a type, a top-level value, or a parse error.crates/mapal-syntax/src/ast.rs:40compiler heap, inside ProgramLowering
StageKindWhat one stage of a chain does: map, fold, call, bind, guard, fan-out and so on.crates/mapal-syntax/src/ast.rs:303compiler heap
Block / BlockItemA braced body: statements, then an optional final chain that is the value.crates/mapal-syntax/src/ast.rs:215compiler heap
Chain / StageA pipeline written with arrows: a start value flowing through stages such as map, fold, call, bind or fan-out.crates/mapal-syntax/src/ast.rs:286compiler heap
Expr / ExprKindAn expression: literal, name, operator, index, member, struct literal.crates/mapal-syntax/src/ast.rs:393compiler heap
FnDeclA function: name, size and format parameters, parameters, return type and body.crates/mapal-syntax/src/ast.rs:62compiler heap
GuardArm / GuardDiscrOne arm of a conditional (guard) with the case it matches.crates/mapal-syntax/src/ast.rs:365compiler heap
LoopStmtA loop statement with its label.crates/mapal-syntax/src/ast.rs:253compiler heap
NameA bare span; its text is read from the source.crates/mapal-syntax/src/ast.rs:141a SourceLoc inline
ParseOutputThe program tree plus every lexer and parser error, sorted by position.crates/mapal-syntax/src/ast.rs:21compiler heap, handed to lowering, the checker, the formatter-free tools and the language server
ProgramThe whole parse tree: a list of items.crates/mapal-syntax/src/ast.rs:28compiler process heap, produced by the parser and borrowed by lowerLowering
SizeExprA size written as arithmetic over numbers and size names, such as tokens * hidden.crates/mapal-syntax/src/ast.rs:186compiler heap
Ty / TyKindA written type: a primitive, a named type, an array with a size, or a tuple.crates/mapal-syntax/src/ast.rs:147compiler heap
TypeDeclA named record type with fields.crates/mapal-syntax/src/ast.rs:122compiler heap
SourceLoc (syntax)A byte range in the source text; lower keys many tables by its (start,end).crates/mapal-syntax/src/loc.rs:12compiler heap, 8 bytes inline in every nodeLowering
Arrows (7)
ArrowFrom → toWhat it doesDefined at
ir_locsyntax SourceLoc → IR SourceLocCarries a source span across from the parse tree to the IR so graph nodes remember where they came from.crates/mapal-lower/src/tys.rs:19
name_textName → &strA name node to its text in the source.crates/mapal-lower/src/tys.rs:211
src_sliceSourceLoc → &strA span to the source text it covers.crates/mapal-lower/src/tys.rs:216
Block to its items and tailBlock → BlockItem / ChainA body to its statements and its final value chain.crates/mapal-syntax/src/ast.rs:215
Chain.stagesChain → StageA chain to the ordered stages the value flows through.crates/mapal-syntax/src/ast.rs:286
Program.itemsProgram → ItemA program to its top-level items.crates/mapal-syntax/src/ast.rs:28
every node's spanany tree node → SourceLocEach tree node maps to the source range it covers, so any error or tool can point back at the text.crates/mapal-syntax/src/parser.rs:193

Category Diagnostics

Error and warning messages with the place they refer to, whichever stage found them.

Objects (9)
ObjectWhat it isDefined atLives inProvided by
TCodeThe check stage's error catalogue: T0101 multiple return writers, T0201 effect in a fan-out.crates/mapal-check/src/diag.rs:15a tag value, becomes a &'static str codeChecker
Diagnostic (check findings)The same Diagnostic type as syntax, always severity Error with no fix.crates/mapal-check/src/diag.rs:33compiler heap: Vec<Diagnostic>, in the order exclusivity findings then effect findingsChecker
ScopeThe set of names bound so far while walking the tree, used to tell a local value from a callee.crates/mapal-check/src/effects.rs:77compiler heap: stack of name sets, temporary during the walkChecker
Exit code (Res<u8>)0 ok, 1 failure, 2 usage, 3 toolchain missing; from the program: 101 trap, 102 driver failure, 103 read failure.crates/mapal-cli/src/main.rs:55the process exit statusCommand line
LCodeThe catalogue of lowering error kinds, each with a stable L-code.crates/mapal-lower/src/diag.rs:15compiler heap, Copy tagLowering
SeverityError or warning.crates/mapal-syntax/src/diag.rs:17one tag
DiagCodeA stable code string: L#### lexer, P#### parser, T#### check.crates/mapal-syntax/src/diag.rs:13a &'static str constant
Diagnostic (syntax)An error with a span, code and message, shared with the parser.crates/mapal-syntax/src/diag.rs:32compiler heap Vec<Diagnostic>Lowering
SuggestedFixReplace this span with this text, with a label.crates/mapal-syntax/src/diag.rs:24compiler heap, inside a Diagnostic
Arrows (9)
ArrowFrom → toWhat it doesDefined at
diag(TCode, SourceLoc, message) → DiagnosticA code, a span and a message become a Diagnostic.crates/mapal-check/src/diag.rs:33
TCode::codeTCode → DiagCode stringA check error kind to its stable code string.crates/mapal-check/src/diag.rs:22
to_syntaxmapal_ir SourceLoc → SourceLocA source location of the flow graph converts to the syntax span type.crates/mapal-check/src/exclusivity.rs:18
reportDiagnostic list → stderr linesPrint 'file:line:col error[code] (stage) message'.crates/mapal-cli/src/main.rs:215
diagLCode x SourceLoc x message → DiagnosticBuilds a diagnostic.crates/mapal-lower/src/diag.rs:211
LCode::codeLCode → &strThe code string such as L1201.crates/mapal-lower/src/diag.rs:113
ir_errIrError x SourceLoc → DiagnosticTranslates a builder refusal or seal failure into a source-located error.crates/mapal-lower/src/emit.rs:149
Diagnostic::error / with_fix(code, SourceLoc, message) → DiagnosticBuild an error at a span, optionally attach a fix.crates/mapal-syntax/src/diag.rs:43
Parser::diag / diag_fix(code, SourceLoc, message) → DiagnosticThe parser records an error, with a cooldown so one mistake does not cascade into many.crates/mapal-syntax/src/parser.rs:249
Transformations (4)
NameFrom → toKindWhat it doesDefined atLives in
lexText
→ Tokens
Diagnostics
functorCuts the text into tokens. It is total: unknown input becomes an Error token plus a diagnostic and scanning goes on; guard arrows are single tokens recognised by adjacency and statement-start context.crates/mapal-syntax/src/lexer.rs:23compiler heap; runs once per source on the main thread
parseTokens
→ Syntax
Diagnostics
functorBuilds the parse tree from the tokens by recursive descent, recovering at statement and item borders. It merges lexer and parser errors and sorts them by position.crates/mapal-syntax/src/parser.rs:43compiler heap; recursion depth capped by DEPTH_LIMIT so deep nesting reports an error instead of overflowing the stack
format_sourceText
Tokens
→ Text
processRe-prints source in the one canonical layout (four spaces, multiline braces) by walking the token stream and re-spacing it, keeping comments. It refuses input that has syntax errors.crates/mapal-syntax/src/format.rs:11compiler heap: output String; used by `mapal fmt` and the editors' format action
source to treeText
→ Syntax
Diagnostics
processThe two steps above in order: lex then parse.
made of: lex, parse
crates/mapal-syntax/src/parser.rs:43compiler heap
Algorithms, data structures and design patterns (7)
NameKindWhat it isDefined atUsed by
Hand-written recursive-descent parser with depth limitalgorithmOne function per grammar rule, a cursor over the token array, and a recursion cap that turns runaway nesting into an error.crates/mapal-syntax/src/parser.rs:62parse
Error recovery with cooldowndesign patternAfter an error the parser skips to a safe point and mutes follow-up errors for a short while.crates/mapal-syntax/src/parser.rs:241parse
Context-sensitive guard-arrow scanalgorithmA guard arrow like -42-> is one lexeme only when adjacent and at statement start; otherwise it is minus, number, arrow.crates/mapal-syntax/src/lexer.rs:30lex
Spans instead of copied textdesign patternTokens and names hold only offsets, and text is cut from the one source string when needed.crates/mapal-syntax/src/token.rs:11lex, parse, format_source
Line-start index with binary searchdata structureLine starts are stored once, and an offset is found by search.crates/mapal-syntax/src/loc.rs:59lex
Token-stream pretty printeralgorithmThe formatter walks tokens, tracks a stack of brace frames and decides spacing and line breaks from neighbouring token kinds.crates/mapal-syntax/src/format.rs:52format_source
Renderer-free diagnosticsdesign patternDiagnostics are plain data with no Display; only the CLI and the language server turn them into text or editor messages.crates/mapal-syntax/src/diag.rs:32lex, parse

Guarantees of Syntax

Guarantee (natural transformation)What must agreeChecked in
Formatting keeps the treeParsing the formatted text gives the same tree as parsing the original (apart from positions), and formatting twice changes nothing.crates/mapal-syntax/tests/format.rs:171
Lexing and parsing never failFor every input string, even invalid, lexing and parsing return a result and never panic; bad input shows up only as diagnostics.crates/mapal-syntax/tests/proptest_lexer.rs:40
crates/mapal-syntax/tests/proptest_parser.rs:310
crates/mapal-syntax/tests/proptest_parser.rs:404

Lowering

Turns the parse tree into the Flow graph: it resolves names, works out types and sizes, and builds the graph.

Reads Syntax → produces Names, Types, Flow, Diagnostics

Guarantees: The lowered graph means what the program means

Files (11)

crates/mapal-lower/src/lib.rs:1
crates/mapal-lower/src/globals.rs:1
crates/mapal-lower/src/effects.rs:1
crates/mapal-lower/src/tys.rs:1
crates/mapal-lower/src/formats.rs:1
crates/mapal-lower/src/sizes.rs:1
crates/mapal-lower/src/typing.rs:1
crates/mapal-lower/src/emit.rs:1
crates/mapal-lower/src/scope.rs:1
crates/mapal-lower/src/convert.rs:1
crates/mapal-lower/src/diag.rs:1

Category Names

What names mean while lowering: top-level values, effects, generic sizes.

Objects (6)
ObjectWhat it isDefined atLives in
EffectsWhich functions are (transitively) effectful, i.e. print, clock or read something.crates/mapal-lower/src/effects.rs:19compiler heap: BTreeMap<String,bool>
BindingWhat a surface name stands for during emission: its graph object, type, mutability and declaration order.crates/mapal-lower/src/emit.rs:72compiler heap, payload of ScopeStack<Binding>
CallLogWhat emission saw at generic calls: bindings per site, instances called and requested, and widen checks to prove.crates/mapal-lower/src/emit.rs:61compiler heap in a RefCell shared by rounds
Globals / TopItemThe program's top-level values, who reads whom, which are computed before running.crates/mapal-lower/src/globals.rs:71compiler heap, built in lower()
ScopeStack<T>A stack of lexical scopes mapping a name to what it stands for; supports poisoning (a name unreadable after a loop) and loop-exit bindings.crates/mapal-lower/src/scope.rs:36compiler heap: Vec of BTreeMaps; one per function being typed or emitted
Instance / SiteKey / GenericsOne instance of a generic function at concrete sizes/formats, the call site that asked for it, and the table of generic declarations.crates/mapal-lower/src/sizes.rs:68compiler heap, rebuilt each monomorphization round
Arrows (4)
ArrowFrom → toWhat it doesDefined at
is_effectfulfn name → boolWhether a call to this function carries the IO token.crates/mapal-lower/src/effects.rs:26
Globals::used_byFnDecl → top-level itemsWhich top-level values a function reads.crates/mapal-lower/src/globals.rs:95
ScopeStack::poisonname → unreadable nameMarks a name unreadable (reading it later is an error).crates/mapal-lower/src/scope.rs:135
ScopeStack::resolvename → BindingFinds what a name stands for, innermost scope first.crates/mapal-lower/src/scope.rs:104
Transformations (13)
NameFrom → toKindWhat it doesDefined atLives in
lower: Syntax -> FlowSyntax
→ Flow
Diagnostics
functorThe whole component as one partial map: each parse-tree form goes to its graph realization, or to a diagnostic where the form is outside the core language. Entry point; handles programs with top-level values by first computing them.
made of: collect top-level values, compute top-level values before the program runs, lower with globals
crates/mapal-lower/src/lib.rs:52
collect top-level valuesSyntax
→ Names
Diagnostics
processFinds top-level bindings, who reads whom, and rejects effects or cycles among them.crates/mapal-lower/src/globals.rs:340compiler heap; pure
compute top-level values before the program runsNames
→ Names
Types
processLowers a small synthetic program and runs its top-level scalars on the interpreter, so they become literals/sizes.crates/mapal-lower/src/lib.rs:117compiler heap; uses the interpreter and a work budget
lower with globalsSyntax
Names
→ Flow
Diagnostics
processThe staged pipeline: structural checks, types, effects, signatures, then monomorphization rounds of typing + emission + seal.
made of: effect analysis, build the type table, build function signatures, typing and size inference, declare, emit and seal, prove widen exactness
crates/mapal-lower/src/lib.rs:378
effect analysisSyntax
→ Names
Diagnostics
processWalks the call graph to mark effectful functions and reports recursion.crates/mapal-lower/src/effects.rs:35compiler heap; pure
build the type tableSyntax
→ Types
Diagnostics
functorResolves every declared type, rejecting cycles, bad sizes and duplicates.crates/mapal-lower/src/tys.rs:87compiler heap; pure
build function signaturesSyntax
Types
Names
→ Types
functorGives every function its declared signature, flagged effectful or generic.crates/mapal-lower/src/typing/sigs.rs:53compiler heap; pure
typing and size inferenceSyntax
Types
Names
→ Types
Names
Diagnostics
processPer function (or generic instance): types literals by unification, infers sizes and formats of generic calls, computes captures, and records which instances are needed.
made of: type one function, infer generic sizes and formats
crates/mapal-lower/src/lib.rs:599compiler heap; pure per round
type one functionSyntax
Types
→ Types
processWalks a function, unifies literal widths, types map/fold blocks and computes their captures.crates/mapal-lower/src/typing.rs:229compiler heap; WTy variables and union-find per function
infer generic sizes and formatsTypes
→ Names
processSolves the size equations of a generic call to choose its instance.crates/mapal-lower/src/sizes/infer.rs:229compiler heap
declare, emit and sealSyntax
Types
Names
→ Flow
Diagnostics
processDeclares each function and body, emits statements and chains through the IR builder, then seals the graph.
made of: emit one function
crates/mapal-lower/src/emit.rs:216compiler heap; builder arena
emit one functionSyntax
Types
Names
→ Flow
processBinds parameters, threads the IO token for effectful functions, emits the body and return, fail-fast on the first error.crates/mapal-lower/src/emit/decl.rs:260compiler heap; FnBuilder
prove widen exactnessFlow
→ Diagnostics
processAfter sealing, uses the facts to check that each int-to-f32 widen stays within the exact range.crates/mapal-lower/src/convert.rs:35compiler heap; reads facts stored on the sealed graph
Algorithms, data structures and design patterns (10)
NameKindWhat it isDefined atUsed by
Staged pipeline with fail-fast emissiondesign patternChecks run in stages and are collected; once emission starts the first error stops that function.crates/mapal-lower/src/lib.rs:378lower with globals, declare, emit and seal
Fixed-point rounds (monomorphization)algorithmRepeat typing and emission up to 32 rounds until every called generic instance was declared.crates/mapal-lower/src/lib.rs:40lower with globals, typing and size inference
Union-find over literal typesalgorithmInteger/float literals of unknown width are variables merged into groups, then pinned to a type.crates/mapal-lower/src/typing/walk_core.rs:376type one function
Size equation solving (inversion, monotone search, divisor enumeration)algorithmSolves expressions like n*2 = 8 for n by inverting or searching.crates/mapal-lower/src/sizes/infer.rs:477infer generic sizes and formats
Cycle detection by iterative DFSalgorithmFinds recursive types and recursive calls with an explicit stack frame.crates/mapal-lower/src/tys.rs:222build the type table, effect analysis
Scope stack with poison marksdata structureLexical scopes as a stack, with names marked unreadable after a loop.crates/mapal-lower/src/scope.rs:36type one function, emit one function
Token threading for effectsdesign patternEffectful functions take and return an IO token so order of print/clock is explicit data.crates/mapal-lower/src/emit/exprs.rs:444emit one function, effect analysis
Capture analysis (struct captures flattened to fields)algorithmFinds which outer values a map/fold body reads and passes them as leading inputs.crates/mapal-lower/src/typing.rs:90type one function, emit one function
Prelude of parsed conversion signaturesdesign patternto/widen are declared as ordinary generic functions in a prelude parsed once; calls are realized by the builtin the format pair admits.crates/mapal-lower/src/formats.rs:201emit one function, build function signatures
Typed diagnostic cataloguedesign patternEvery error is one LCode variant with a stable code string.crates/mapal-lower/src/diag.rs:15lower: Syntax -> Flow

Guarantees of Lowering

Guarantee (natural transformation)What must agreeChecked in
The lowered graph means what the program meansFor every program, interpreting the lowered graph gives what interpreting the parse tree gives.crates/mapal-lower/tests/top_level.rs:43
crates/mapal-lower/tests/proptests.rs:43

Checker

Checks rules the Flow graph must follow after lowering (one return value, no effects racing each other).

Reads Flow → produces Diagnostics

Guarantees: Accepted means the interpreter's assumptions hold

Files (4)

crates/mapal-check/src/lib.rs:1
crates/mapal-check/src/exclusivity.rs:1
crates/mapal-check/src/effects.rs:1
crates/mapal-check/src/diag.rs:1

Transformations (3)
NameFrom → toKindWhat it doesDefined atLives in
checkFlow
Syntax
Text
→ Diagnostics
processTakes the sealed flow graph, the parse tree and the source, runs both passes, and returns a list of errors; an empty list means accept. No HashMap is used, so the same input always gives the same list.crates/mapal-check/src/lib.rs:41compiler heap; the result is a Vec<Diagnostic>
return exclusivity passFlow
→ Diagnostics
processFor every function in the flow graph, counts the writers feeding its return value; each beyond the first becomes T0101 at the writing operation's location.crates/mapal-check/src/exclusivity.rs:26reads the sealed CategoryIr on the compiler heap
effect legality passSyntax
Flow
Text
→ Diagnostics
processWalks the parse tree; inside a parallel fan-out branch, any print, clock read or file read becomes T0201. A nested sequential block stays inside the illegal zone.
made of: return exclusivity pass
crates/mapal-check/src/effects.rs:34compiler heap: a Walk with a Scope stack
Algorithms, data structures and design patterns (4)
NameKindWhat it isDefined atUsed by
Tree walk keyed by node kind with sticky contextdesign patternA fan-out opens the illegal context, and a sequential block inside it inherits it.crates/mapal-check/src/effects.rs:104effect legality pass
Lexical scope stackdata structurePush on entering a block, pop on leaving, to know whether a name is a local binding.crates/mapal-check/src/effects.rs:77effect legality pass
In-edge count on the graphalgorithmCounts non-pair edges into the return object to find a second writer.crates/mapal-check/src/exclusivity.rs:26return exclusivity pass
Deterministic orderingdesign patternNo hash maps; findings come in a fixed order so two runs agree exactly.crates/mapal-check/src/lib.rs:41check

Guarantees of Checker

Guarantee (natural transformation)What must agreeChecked in
Accepted means the interpreter's assumptions holdFor every program the checker accepts, what the interpreter assumes (one return writer, no effect racing in a fan-out) is true.crates/mapal-check/tests/acceptance.rs:65
crates/mapal-check/tests/acceptance.rs:110
crates/mapal-check/tests/exclusivity.rs:44
crates/mapal-check/tests/effects.rs:25

Flow graph

The one data structure every later stage shares: Mapal's types and the dataflow graph, with its builder, validator and pictures.

Reads Types, Flow → produces Flow, Diagram, Diagnostics

Guarantees: A sealed graph is always valid, Pictures are stable, Graph algorithms agree with loop structure

Files (20)

crates/mapal-ir/src/graph.rs:1
crates/mapal-ir/src/ty.rs:1
crates/mapal-ir/src/loc.rs:1
crates/mapal-ir/src/builder.rs:1
crates/mapal-ir/src/validate.rs:1
crates/mapal-ir/src/facts.rs:1
crates/mapal-ir/src/algo.rs:1
crates/mapal-ir/src/access.rs:1
crates/mapal-ir/src/residence.rs:1
crates/mapal-ir/src/unit.rs:1
crates/mapal-ir/src/math.rs:1
crates/mapal-ir/src/exp.rs:1
crates/mapal-ir/src/split.rs:1
crates/mapal-ir/src/narrow.rs:1
crates/mapal-ir/src/read.rs:1
crates/mapal-ir/src/mermaid.rs:1
crates/mapal-ir/src/mermaid_flow.rs:1
crates/mapal-ir/src/mermaid_cat.rs:1
crates/mapal-ir/src/mermaid_string.rs:1
crates/mapal-ir/src/mermaid_diagram.rs:1

Category Types

Mapal's types and number formats, as lowering resolves them and the graph stores them.

Objects (17)
ObjectWhat it isDefined atLives inProvided by
ExpFormOne exp realization: its algorithm constants and error bound per float width.crates/mapal-ir/src/exp.rs:30consts F32 / F64 in the binary
NarrowFormFacts of one narrow format: precision bits, exponent range, unit round-off, largest value, whether it saturates.crates/mapal-ir/src/narrow.rs:30computed on demand (NarrowForm::of), no storage
SplitForm / SplitKindA way to run an f32 product on a matrix unit by cutting operands into exact parts, with its a-priori error coefficient.crates/mapal-ir/src/split.rs:62computed on demand; chosen at compile time by the backend
NarrowFloatThe narrow float formats bf16, f16, f8e4m3, f8e5m2.crates/mapal-ir/src/ty.rs:192compiler heapFacts
Ty / ValueA Mapal type: Int, Float, Narrow, Bool, Unit, Str, IoToken, Tuple, Struct, Array{elem,size}.crates/mapal-ir/src/ty.rs:23compiler heap: field of each ObjectFacts
ValueA constant: i32, i64, u8, f32, f64, narrow bits, bool, string, unit.crates/mapal-ir/src/ty.rs:241compiler heap: Object.value for Constant objects; constant tables in emitted code later
ArgOne generic argument: a size or a format.crates/mapal-lower/src/formats.rs:184compiler heapLowering
FormatOne concrete number format (f32, bf16, i32, ...), the unit of format generics.crates/mapal-lower/src/formats.rs:20compiler heap, Copy valueLowering
KindA class of formats a generic parameter may range over (number, float, int, precision, ...).crates/mapal-lower/src/formats.rs:111compiler heap, Copy valueLowering
GlobalConstA top-level number computed before the program runs (int, float or bool).crates/mapal-lower/src/globals.rs:42compiler heap, inside Globals.constsLowering
Equation / EquationsThe size equations one call gives (declared dimension = actual length) that inference solves.crates/mapal-lower/src/sizes/infer.rs:24compiler heap, temporary per callLowering
SizeEnvThe values of size names and format names in scope (n=4, t=bf16).crates/mapal-lower/src/sizes.rs:34compiler heap: BTreeMap<String,u64> + BTreeMap<String,Format>Lowering
WTy (working type)A type that may still be an unknown literal width, resolved by unification.crates/mapal-lower/src/typing.rs:125compiler heap, only during typing of one functionLowering
BlockSigThe signature of one map/fold body: its input, output and the outer values it captures.crates/mapal-lower/src/typing.rs:65compiler heap, inside TypeInfo.blocksLowering
FnSigA function's declared signature (parameter types, return type, effectful?, generic?).crates/mapal-lower/src/typing.rs:215compiler heap: BTreeMap<String, FnSig>Lowering
TypeInfoWhat typing found for one function: the type of each literal and the signature of each map/fold block, keyed by span.crates/mapal-lower/src/typing.rs:56compiler heap, handed from typing to emissionLowering
TypeTableAll declared Mapal types, resolved to fixed-size IR types, with generic declarations kept for instantiation.crates/mapal-lower/src/tys.rs:28compiler heap: BTreeMap<String, Ty> plus the declarationsLowering
Arrows (15)
ArrowFrom → toWhat it doesDefined at
bf16_from_f32 / f8_from_f32f32 → narrow bitsConcrete roundings to bf16 and fp8.crates/mapal-ir/src/narrow.rs:205
narrow::round / widenf64 / f32 / u16 bits → u16 bits / f32Round a number into a narrow format and read it back.crates/mapal-ir/src/narrow.rs:138
narrow::widen / roundNarrowFloat bits → f32Exact widening and round-to-nearest-even narrowing, the oracle's conversions.crates/mapal-ir/src/narrow.rs:294
tf32_parts / bf16_partsf32 → [f32] partsCut an f32 into parts a matrix instruction multiplies exactly.crates/mapal-ir/src/split.rs:278
Ty::Array elemTy (array) → Ty (element)An array type points to its element type; product types point to their components.crates/mapal-ir/src/ty.rs:23
ty_labelTy → StringPlain-text name of a type for pictures.crates/mapal-ir/src/ty.rs:405
Value::tyValue → TyThe type of a constant.crates/mapal-ir/src/ty.rs:257
admitVerb x Format x Format → RealizeDecides how a to<target>/widen<target> conversion is realized, or why it is refused.crates/mapal-lower/src/formats.rs:303
embedsFormat x Format → boolWhether every value of one format is exactly a value of another (so widening is lossless).crates/mapal-lower/src/formats.rs:288
Format::of / Format::tyIR Ty → FormatMoves between a format name and its IR scalar type.crates/mapal-lower/src/formats.rs:79
Kind::admitsKind x Format → boolWhether a format belongs to a generic parameter's class.crates/mapal-lower/src/formats.rs:142
eval (size)SizeExpr x SizeEnv → u64Computes a size expression's number or reports why it cannot.crates/mapal-lower/src/sizes.rs:262
resolve_tykindsurface Ty → IR TyTurns a written type into a resolved type with known sizes.crates/mapal-lower/src/tys.rs:334
default_ofTy → TyA struct with a default field `_` is read as that field when its context needs it.crates/mapal-lower/src/tys.rs:57
TypeTable::instancegeneric TypeDecl + [Arg] → IR TyInstantiates a generic type at given sizes.crates/mapal-lower/src/tys.rs:652

Category Flow

The dataflow graph of a program: objects (values) and morphisms (operations) in sealed functions.

Flow as Mapal's own category: values and operations

The Flow graph is itself a category: its objects are typed values and its morphisms are the operations below, each from one kind of value to another.

Product, coproduct, loopWhat it isWhere it lives
ProductsSeveral values held together are one object, a product. Pair builds it, Proj takes a part out, and every binary operation reads a pair.crates/mapal-ir/src/graph.rs:63
crates/mapal-ir/src/graph.rs:68
crates/mapal-ir/src/ty.rs:23
Coproducts (guards)A choice between two branches is a coproduct: Phi picks one value by a condition, and the facts record which work belongs to which arm.crates/mapal-ir/src/graph.rs:91
crates/mapal-ir/src/algo.rs:271
Loops (traced feedback)A loop is a cycle in the graph: LoopEnter feeds the start value into the loop state, LoopBack feeds the next state back, and LoopExit leaves. There is no loop node.crates/mapal-ir/src/graph.rs:158
crates/mapal-ir/src/graph.rs:160
crates/mapal-ir/src/graph.rs:162
crates/mapal-ir/src/graph.rs:38
crates/mapal-ir/src/algo.rs:80
Operations, the morphisms of Flow (37)
OperationFrom → toWhat it doesDefined at
Pairany value T → product (a, b, ...)Puts a value into slot i of a product of n slots.crates/mapal-ir/src/graph.rs:63
Projproduct (a, b, ...) → any value TTakes component i out of a product.crates/mapal-ir/src/graph.rs:68
Addproduct (a, b, ...) → numberAdds the two numbers of its pair.crates/mapal-ir/src/graph.rs:72
Subproduct (a, b, ...) → numberSubtracts.crates/mapal-ir/src/graph.rs:73
Mulproduct (a, b, ...) → numberMultiplies.crates/mapal-ir/src/graph.rs:74
Divproduct (a, b, ...) → numberDivides (a zero integer divisor traps).crates/mapal-ir/src/graph.rs:75
Modproduct (a, b, ...) → numberRemainder.crates/mapal-ir/src/graph.rs:76
Negnumber → numberNegates a number.crates/mapal-ir/src/graph.rs:78
Eqproduct (a, b, ...) → boolEqual.crates/mapal-ir/src/graph.rs:80
Neqproduct (a, b, ...) → boolNot equal.crates/mapal-ir/src/graph.rs:81
Ltproduct (a, b, ...) → boolLess than.crates/mapal-ir/src/graph.rs:82
Gtproduct (a, b, ...) → boolGreater than.crates/mapal-ir/src/graph.rs:83
Leproduct (a, b, ...) → boolAt most.crates/mapal-ir/src/graph.rs:84
Geproduct (a, b, ...) → boolAt least.crates/mapal-ir/src/graph.rs:85
Andproduct (a, b, ...) → boolBoth true.crates/mapal-ir/src/graph.rs:86
Orproduct (a, b, ...) → boolEither true.crates/mapal-ir/src/graph.rs:87
Notbool → boolNegates a truth value.crates/mapal-ir/src/graph.rs:88
Phiproduct (a, b, ...) → any value TPicks one of two values by a condition: the coproduct (guard) of two branches.crates/mapal-ir/src/graph.rs:91
Callany value T → any value TCalls a named function.crates/mapal-ir/src/graph.rs:94
Maparray [T; n] → array [T; n]Applies a function body to every element (with optional captured values broadcast to all).crates/mapal-ir/src/graph.rs:99
Foldproduct (a, b, ...) → any value TFolds an array into one value from a start value with a function body.crates/mapal-ir/src/graph.rs:107
Indexproduct (a, b, ...) → any value TReads one element of an array; out of range traps.crates/mapal-ir/src/graph.rs:113
Zipproduct (a, b, ...) → array [T; n]Pairs two arrays of the same length element by element.crates/mapal-ir/src/graph.rs:117
Enumeratearray [T; n] → array [T; n]Pairs every element with its index.crates/mapal-ir/src/graph.rs:120
Iotanumber → array [T; n]The array 0, 1, ..., n-1.crates/mapal-ir/src/graph.rs:125
Fillany value T → array [T; n]An array of n copies of one value.crates/mapal-ir/src/graph.rs:129
Updateproduct (a, b, ...) → array [T; n]A copy of an array with one element replaced.crates/mapal-ir/src/graph.rs:134
Printproduct (a, b, ...) → IoTokenPrints a value and passes the token on.crates/mapal-ir/src/graph.rs:138
TimeMsIoToken → product (a, b, ...)Reads the clock; gives the next token and the milliseconds.crates/mapal-ir/src/graph.rs:145
Readproduct (a, b, ...) → product (a, b, ...)Reads a file into an array; gives the next token and the array.crates/mapal-ir/src/graph.rs:155
LoopEnterany value T → loop state (LoopMerge)Feeds the loop's start value into the loop state.crates/mapal-ir/src/graph.rs:158
LoopBackproduct (a, b, ...) → loop state (LoopMerge)The back edge: sends the next state to the loop state when the condition says continue.crates/mapal-ir/src/graph.rs:160
LoopExitproduct (a, b, ...) → any value TSends the loop state out when the condition says stop.crates/mapal-ir/src/graph.rs:162
Outputany value T → ReturnSends a value to the function's return.crates/mapal-ir/src/graph.rs:164
Widennumber → numberExact numeric widening (i32 to i64, f32 to f64, ...).crates/mapal-ir/src/graph.rs:168
Narrownumber → numberRounds once to a narrow float format (bf16, f16).crates/mapal-ir/src/graph.rs:173
Mathnumber → numberA math builtin on a float: exp, sqrt, sin or cos.crates/mapal-ir/src/graph.rs:179
Kinds of object (5)
KindWhat it isDefined at
ParameterA function input.crates/mapal-ir/src/graph.rs:30
TemporaryA computed intermediate.crates/mapal-ir/src/graph.rs:32
ConstantA literal.crates/mapal-ir/src/graph.rs:34
ReturnThe function's output.crates/mapal-ir/src/graph.rs:36
LoopMergeThe value a loop carries between trips (the feedback point).crates/mapal-ir/src/graph.rs:38
Objects (20)
ObjectWhat it isDefined atLives inProvided by
DestWhere the next operation writes: a fresh object, the return slot, or an existing one.crates/mapal-ir/src/builder.rs:37compiler heap, argument onlyLowering
FnBuilderThe open builder of one function; emission adds objects and operations through it.crates/mapal-ir/src/builder.rs:438compiler heap, short-lived per functionLowering
FuncKindNamed, MapBody or FoldBody.crates/mapal-ir/src/graph.rs:264field of FuncDef
ObjectKindRole of a value: Parameter, Temporary, Constant, Return or LoopMerge.crates/mapal-ir/src/graph.rs:28field of Object
OperationThe kind of one graph edge: Map, Fold, Pair, Proj, Phi, Widen, Narrow, ...crates/mapal-ir/src/graph.rs:60compiler heap, tag on each morphismFacts, Lowering
CategoryIr (sealed graph)The whole graph, frozen after construction; it also carries the fact store, the per-product precision sets and the data directory for file reads.crates/mapal-ir/src/graph.rs:288compiler heap; created by IrBuilder::sealCommand line, Facts, Lowering, Rewrites
FuncDefA function (named, map body or fold body): one input object, one output object and its list of morphisms.crates/mapal-ir/src/graph.rs:277compiler heap: SlotMap<FuncId, FuncDef> inside CategoryIrFacts
FuncIdHandle naming one function (named function, map body or fold body).crates/mapal-ir/src/graph.rs:23compiler heap: key into SlotMap<FuncId, FuncDef>
MorphismId / MorphismOne operation (an edge) from a source object to a target object, tagged with its Operation and source location.crates/mapal-ir/src/graph.rs:191compiler heap: SlotMap<MorphismId, Morphism> inside CategoryIrFacts
MorphismIdTyped handle naming one operation edge.crates/mapal-ir/src/graph.rs:21compiler heap: key into SlotMap<MorphismId, Morphism>
ObjectId / ObjectOne typed value in the graph (parameter, temporary, constant, return, loop merge) with its type, optional constant value, name and source location.crates/mapal-ir/src/graph.rs:43compiler heap: SlotMap<ObjectId, Object> inside CategoryIrFacts
ObjectId / FuncIdTyped handle (slotmap key) naming one value in the graph.crates/mapal-ir/src/graph.rs:19compiler heap, index into the arenaLowering
PrecisionThe set of number formats a float multiplication is allowed to use (full f32, tf32, bf16, f16).crates/mapal-ir/src/graph.rs:206compiler heap: SecondaryMap<MorphismId, Precision> in CategoryIrFacts
Ty (IR)The IR type of a value: number format, array, struct, token.crates/mapal-ir/src/ty.rs:23compiler heapLowering
PassIdThe seven passes: ConstFold, Cse, Dce, MapFusion, Inline, LiftLoops, Unroll.crates/mapal-rewrite/src/driver.rs:28compiler stackRewrites
RewriteResult / RewriteReportThe new graph with rounds taken, how often each pass applied, and whether the graph was skipped as non-canonical.crates/mapal-rewrite/src/driver.rs:50compiler heapRewrites
NaturalityLawA catalogue of Zip/Enumerate naturality equalities, recorded as data with no pass yet.crates/mapal-rewrite/src/naturality.rs:10a const table in the compiler binaryRewrites
FusionSpec / LiftSpec / LiftKindWhat to fuse (two map bodies) and what to lift (a counted loop into a captured Fold or Map).crates/mapal-rewrite/src/plan.rs:45compiler heap: values inside RewritePlanRewrites
RewritePlanThe read-only product of an analysis, with channels alias, constify, drop, fuse, inline, lift, embed, drop_loops, unroll, keyed by the input graph's ids.crates/mapal-rewrite/src/plan.rs:65compiler heap: SecondaryMaps, dropped after replayRewrites
StaticReportWhat compile-time evaluation replaced.crates/mapal-rewrite/src/statics.rs:19compiler heapRewrites
Arrows (28)
ArrowFrom → toWhat it doesDefined at
to_mermaid / _flow / _category / _string (+ condensed)CategoryIr → Mermaid textThe dump-ir --mermaid views.crates/mapal-cli/src/main.rs:651
Pair{slot,arity}Object (component) → Object (product)Put one value into slot k of a tuple, struct or array object; products are built edge by edge.crates/mapal-ir/src/graph.rs:60
Proj{index}Object (product) → Object (component)Take component k out of a product.crates/mapal-ir/src/graph.rs:60
Add/Sub/Mul/Div/Mod/Neg, Eq/Lt/.., And/Or/NotObject (operand tuple) → Object (number or bool)Arithmetic, comparison and logic; binary ones read a 2-tuple product.crates/mapal-ir/src/graph.rs:60
PhiObject (condition and two arms) → Object (chosen value)A guard: pick one of two arms by a condition (only the chosen arm's work runs).crates/mapal-ir/src/graph.rs:60
Map{body,captures}Object (array and captured values) → Object (array)Apply a body function to every element.crates/mapal-ir/src/graph.rs:60
Fold{body,captures}Object (array, start, captures) → Object (accumulated value)Combine all elements with a body function into one value.crates/mapal-ir/src/graph.rs:60
Call(FuncId)Object (argument) → Object (result)Call a named function.crates/mapal-ir/src/graph.rs:60
Index / Update / Zip / Enumerate / Iota / FillObject (array, index...) → Object (element or array)Collection operations: read an element, write one, pair up, number, generate.crates/mapal-ir/src/graph.rs:60
LoopEnter / LoopBack / LoopExitObject (state) → Object (LoopMerge or exit value)A loop is a real cycle: enter into the merge, a back edge returns the next state, exit leaves it.crates/mapal-ir/src/graph.rs:60
Print / TimeMs / ReadObject (IoToken and payload) → Object (IoToken and result)Effects: output, clock, file read; ordered by threading a world token.crates/mapal-ir/src/graph.rs:60
Widen / NarrowObject (number) → Object (number)Convert between a narrow float format and f32, and back with rounding.crates/mapal-ir/src/graph.rs:60
Math(MathFn) (Exp, Sqrt, Sin, Cos)Object (float) → Object (float)A math builtin, realized later by a target-specific form.crates/mapal-ir/src/graph.rs:60
CategoryIr::out_edges / in_edgesObjectId → [MorphismId]Adjacency: which arrows leave and enter a value.crates/mapal-ir/src/graph.rs:348
CategoryIr::ownerObjectId → FuncIdWhich function a value belongs to.crates/mapal-ir/src/graph.rs:359
out_edges / in_edgesObjectId → Vec<MorphismId>From a value to the operations that read it, or the one that makes it.crates/mapal-ir/src/graph.rs:288
ownerObjectId → FuncIdWhich function a value belongs to.crates/mapal-ir/src/graph.rs:288
Morphism source / targetMorphismId → ObjectIdThe two ends of an operation.crates/mapal-ir/src/graph.rs:191
Morphism{source,target,op}ObjectId → ObjectIdThe edge record itself: source object, target object, which operation, source span.crates/mapal-ir/src/graph.rs:191
Emitter::emit_convertto/widen call → Widen / Narrow morphismEmits a number-format conversion by what the format pair admits.crates/mapal-lower/src/emit/collections.rs:275
Emitter::emit_expr_destExpr → ObjectIdEmits one expression as an operation writing to a destination.crates/mapal-lower/src/emit/exprs.rs:14
Emitter::emit_loopLoopStmt → LoopMerge / LoopBack / LoopExitEmits a loop with carried state, merge, back edge and exits.crates/mapal-lower/src/emit/loops.rs:8
Emitter::emit_map_foldmap/fold stage → Map or Fold morphismEmits a map or fold whose body is a separately built function with captures as leading inputs.crates/mapal-lower/src/emit/collections.rs:9
Emitter::emit_print / emit_time / emit_readprint/time/read call → token-threaded morphismEmits effects as operations that take and return the IO token.crates/mapal-lower/src/emit/exprs.rs:458
Emitter::emit_stageStage → ObjectIdEmits one stage of a chain, feeding it the previous stage's value.crates/mapal-lower/src/emit/chains.rs:161
Emitter::emit_value_matchguard arms → right-folded Phi chainEmits a match on values as nested Phi choices with the default innermost.crates/mapal-lower/src/emit/guards.rs:141
RewritePlan::resolve_aliasObjectId → ObjectIdFollows alias chains to the object a value now stands for.crates/mapal-rewrite/src/plan.rs:121
old id to new id remapObjectId (old graph) → ObjectId (new graph)The map built while replaying each object through the builder.crates/mapal-rewrite/src/replay.rs:67

Category Diagram

Pictures of a graph (Mermaid text): the flow view, category diagrams and string diagrams.

Objects (3)
ObjectWhat it isDefined atLives in
DNode / DEdge / NodeKind / EdgeKindOne box, one arrow, and their style.crates/mapal-ir/src/mermaid_diagram.rs:43inside Diagram
DiagramNodes, subgraphs and edges, ready to be printed as Mermaid.crates/mapal-ir/src/mermaid_diagram.rs:75compiler heap, short-lived; ends as a String
FlowGraph / FlowAnchorThe plain-values view of the flow: nodes are values or prints, edges are steps, paths are chains.crates/mapal-ir/src/mermaid_flow.rs:33compiler heap, short-lived
Arrows (2)
ArrowFrom → toWhat it doesDefined at
Diagram::renderDiagram → StringPrint the Mermaid text.crates/mapal-ir/src/mermaid_diagram.rs:143
FlowGraph::edge_labelFlowGraph edge → StringLabel an arrow in source words.crates/mapal-ir/src/mermaid_flow.rs:99
Transformations (14)
NameFrom → toKindWhat it doesDefined atLives in
IrBuilder (declare, build_fn, FnBuilder ops, seal)Flow: (empty
Types
Text
→ Flow: (CategoryIr
processThe only way to make a graph: one method per operation that checks types and shape rules and refuses ill-formed edges, then seal freezes it. Called by the lowering stage.crates/mapal-ir/src/builder.rs:172builder holds growing SlotMaps on the compiler heap; seal moves them into CategoryIr and creates the empty Facts
FnBuilder primitives (constant, pack, binop, phi, map, fold, begin_loop/loop_back/loop_exit, output, read)Flow: (partial
Types
→ Flow: (partial
processEach call appends an object and edge; rejection matrix is IrError.crates/mapal-ir/src/builder.rs:438compiler heap
sealFlow: (partial
→ Flow: (CategoryIr
processFreeze: global checks then immutable graph.
made of: FnBuilder primitives (constant, pack, binop, phi, map, fold, begin_loop/loop_back/loop_exit, output, read)
crates/mapal-ir/src/builder.rs:266compiler heap
validateFlow
→ Diagnostics: (IrViolation list
functorAn independent re-check of every graph rule (ownership, edge types, tokens, loops, references); used as the test oracle.crates/mapal-ir/src/validate.rs:98returns Vec<IrViolation> on the heap
fact queries (tile_plan, loop_plan, last_use_plan, path_plan, precision_plan, elem_plan, access_plan, residence_plan, ...)Flow
Target: (capacities where asked
→ Facts
functorEach query reads the sealed graph and the facts it depends on and stores its answer once on the graph.crates/mapal-ir/src/algo/site_plans.rs:198cached in CategoryIr.facts OnceLock slots; per-function
sccs / topo_order / loop_structureFlow
→ Facts
processFind the cycles (loops) and a legal execution order, without recursion.crates/mapal-ir/src/algo/loops.rs:13compiler heap: Vec<Vec<ObjectId>>, Vec<MorphismId>
to_mermaid / to_mermaid_flow / to_mermaid_category / to_mermaid_stringFlow
→ Diagram
functorThree views of the graph (flow, category, string diagram), each condensed or full, printed as Mermaid.crates/mapal-ir/src/mermaid_flow.rs:232short-lived Diagram then String
category_diagramFlow
→ Diagram
functorObjects as boxes and morphisms as labelled arrows.crates/mapal-ir/src/mermaid_cat.rs:104short-lived
string_diagramFlow
→ Diagram
functorString-diagram view (wires and boxes).crates/mapal-ir/src/mermaid_string.rs:121short-lived
lint_mermaidDiagram
→ Diagnostics
processCheck that Mermaid text will render.crates/mapal-ir/src/mermaid.rs:200Vec<String>
math candidates / admits / chooseTypes: (MathFn
Target: (units
→ Code: (Choice, Def
processFor a builtin and a target's available units, list realizations, admit those within the stated error, pick the cheapest by cost, never by target name.crates/mapal-ir/src/math/target.rs:502compiler heap, decided at compile time; Choice later printed by a backend
Trace (record a reference definition as data)Types: (MathFn
→ Code: (Def: list of Steps
functorThe reference definition of exp/sqrt/sin/cos is written once over plain operations; running it with Trace records the steps so a backend can print them, running it with Native computes numbers.crates/mapal-ir/src/math/trace.rs:58Vec<Step> on compiler heap; printed as LLVM text or C
read::load / decode / encodeTypes: (array type
Text: (path
→ Flow: constants / Values
processLoad a binary file as an array of the declared element type, with exact-size checks and friendly messages.crates/mapal-ir/src/read.rs:154file bytes into a Vec<u8> then Vec<Value> on host heap
unit_plan / out_rowsFlow
Facts
→ Facts
functorGroup sites into row blocks and colour on-chip buffers by death.crates/mapal-ir/src/unit.rs:250cached in FuncFacts
Algorithms, data structures and design patterns (12)
NameKindWhat it isDefined atUsed by
Arena with typed ids (slotmap)data structureObjects, morphisms and functions live in slot arenas; a typed id cannot be confused with another kind, and side tables are SecondaryMaps keyed by the same id.crates/mapal-ir/src/graph.rs:288IrBuilder (declare, build_fn, FnBuilder ops, seal), fact queries (tile_plan, loop_plan, last_use_plan, path_plan, precision_plan, elem_plan, access_plan, residence_plan, ...), validate
Gatekeeper builder + sealing (ill-formed is unconstructible)design patternThe only mutable form is IrBuilder; sealing returns an immutable graph, and an independent validator double-checks.crates/mapal-ir/src/builder.rs:172IrBuilder (declare, build_fn, FnBuilder ops, seal), seal, validate
Fact cache stored on the sealed graph (compute once, read after)design patternOne OnceLock per fact and function; dependent facts read stored inputs; never recomputed per call site.crates/mapal-ir/src/facts.rs:25fact queries (tile_plan, loop_plan, last_use_plan, path_plan, precision_plan, elem_plan, access_plan, residence_plan, ...)
Iterative Tarjan strongly connected componentsalgorithmFinds loops as cycles with an explicit work stack, no recursion.crates/mapal-ir/src/algo/loops.rs:13sccs / topo_order / loop_structure
Kahn topological orderalgorithmA legal order of operations by a worklist, with loop back edges cut.crates/mapal-ir/src/algo/loops.rs:162sccs / topo_order / loop_structure
Deterministic containers (no HashMap)design patternInsertion-ordered Vecs and slot maps so dumps, orders and snapshots are byte-stable.crates/mapal-ir/src/lib.rs:1IrBuilder (declare, build_fn, FnBuilder ops, seal), to_mermaid / to_mermaid_flow / to_mermaid_category / to_mermaid_string
Depth guard on typesdesign patternType walks are iterative or capped at 64 levels so a hostile deep type cannot overflow the stack.crates/mapal-ir/src/ty.rs:276validate
Definition as data (tagless-final Arith trait: run or record)design patternOne generic definition of exp/sqrt/sin/cos runs natively (interpreter) or is traced into steps a backend prints.crates/mapal-ir/src/math.rs:178Trace (record a reference definition as data), math candidates / admits / choose
Cost-based choice over declared unitsdesign patternRealizations are data (Unit, TargetDef) filtered by error bound and ranked by issue cost.crates/mapal-ir/src/math/target.rs:138math candidates / admits / choose
Forward error analysis (gamma, bound_coef)algorithmA-priori rounding error of a sum of products, per site and per precision member.crates/mapal-ir/src/algo/precision.rs:83fact queries (tile_plan, loop_plan, last_use_plan, path_plan, precision_plan, elem_plan, access_plan, residence_plan, ...)
Lifetime colouring of buffersalgorithmValues that die before another is born share a colour (a buffer).crates/mapal-ir/src/unit.rs:43unit_plan / out_rows
Plain-function rendering, no Displaydesign patternValues stay free of printing code; text comes from plain functions like ty_label.crates/mapal-ir/src/ty.rs:405to_mermaid / to_mermaid_flow / to_mermaid_category / to_mermaid_string

Guarantees of Flow graph

Guarantee (natural transformation)What must agreeChecked in
A sealed graph is always validEvery program the builder accepts passes validation, and every rule validate has has a matching rejection in the builder.crates/mapal-ir/tests/proptest_builder.rs:87
crates/mapal-ir/tests/builder_rejections.rs:51
Pictures are stableEvery example graph draws to byte-identical Mermaid text (stored snapshots) and passes the lint.crates/mapal-ir/tests/golden_mermaid.rs:22
crates/mapal-ir/tests/golden_mermaid.rs:91
Graph algorithms agree with loop structureEvery loop is exactly one non-trivial cycle holding its merge, and loop-back edges are exactly the cycle breakers.crates/mapal-ir/tests/algos/scc.rs:59
crates/mapal-ir/tests/algos/scc.rs:85

Facts

Computes, once per graph, what is true of it (loops, lifetimes, tiles, bounds, ...). Every later decision reads these facts.

Reads Flow → produces Facts

Guarantees: Facts agree with the interpreter

Files (10)

crates/mapal-ir/src/algo.rs:1
crates/mapal-ir/src/facts.rs:1
crates/mapal-ir/src/access.rs:1
crates/mapal-ir/src/residence.rs:1
crates/mapal-ir/src/unit.rs:1
crates/mapal-ir/src/split.rs:1
crates/mapal-ir/src/exp.rs:1
crates/mapal-ir/src/narrow.rs:1
crates/mapal-ir/src/read.rs:1
crates/mapal-ir/src/validate.rs:1

Category Facts

Everything the compiler has proven about a graph, stored on the graph and read by every later stage.

Objects (30)
ObjectWhat it isDefined atLives inProvided by
AccessPlan / HazardThe bytes each operation reads and writes, shared-buffer classes, and the read-after-write, write-after-read, write-after-write ordering edges.crates/mapal-ir/src/access.rs:43compiler heap: FuncFacts.access_planFlow graph
DeltaWhich cells of a carried array one loop trip writes: a row range or a repeating set of pieces.crates/mapal-ir/src/algo.rs:106compiler heap: SecondaryMap<ObjectId, Delta> in FuncFacts.write_delta
MovePlan / CellSite / RowFoldSite / LinearSiteData-move sites, per-cell map sites, one-value-per-row folds and sums of tile sites.crates/mapal-ir/src/algo/tile_types.rs:336compiler heap: FuncFacts.move_plan, cell_plan, trap_cell_plan, row_fold, whole_fold, linear_plan
ElemPlan / ElemSrcEach array's element as a closed function of its index (index itself, broadcast, load, pair, apply).crates/mapal-ir/src/algo/plan_types.rs:301compiler heap: FuncFacts.elem_planFlow graph
EmissionPlan / EmissionClassWhich objects need bytes, which dissolve into views, and how many consumers each has.crates/mapal-ir/src/algo/plan_types.rs:153compiler heap: FuncFacts.emission_plan
FootprintPlan / Reach / EdgeWhat cells of a producer each consumer cell reads, so edges can be checked as staying within rows.crates/mapal-ir/src/algo/tile_types.rs:412compiler heap: FuncFacts.footprint_plan
GuardSite / GuardArmEach conditional select with the work exclusive to each arm and whether the arm must be gated (it may trap or is heavy).crates/mapal-ir/src/algo.rs:271compiler heap: Vec<GuardSite> in FuncFacts.guard_plan and guard_structure
LastUsePlanEach value's position, death point, whether it escapes into the output, and whether a loop back edge carries it.crates/mapal-ir/src/algo/last_use.rs:15compiler heap: FuncFacts.last_use_planFlow graph
LoopPlan / LoopSccA loop cycle and its canonical shape: initial value, merge, the step that decides to continue, the step that advances, the exit.crates/mapal-ir/src/algo.rs:80compiler heap (fact slots)Flow graph, Rewrites
PathPlan / Task / CheckpointIndependent parallel tasks, which are splittable bulk operations, and where the host must wait for them.crates/mapal-ir/src/algo.rs:205compiler heap: FuncFacts.path_planFlow graph
TensorFormA tile operand described as a dense tensor of at most three axes.crates/mapal-ir/src/algo/tile_types.rs:124compiler heap: computed on demand from a TileRead (TileRead::tensor_form)
TilePlan / TileSite / TileReadA sum-of-products (matrix-like) site: its rows, columns, depth, the two operand reads, seed, epilogue and narrow formats.crates/mapal-ir/src/algo/tile_types.rs:501compiler heap: FuncFacts.tile_plan, tile_plan_strided, tile_plan_post, tile_plan_narrow, tile_plan_radixFlow graph
TripSplit / TripPhaseFor a counted loop, the trip intervals cut by guards on the counter and the state each interval carries.crates/mapal-ir/src/algo/plan_types.rs:53compiler heap: Vec<TripSplit> in FuncFacts.trip_split
FoldCombinePlan / FoldCombine / DepLawHow a fold over blocks of its axis combines partial results, and how each per-row value it reads (factor, shift, rescale, phase) is applied.crates/mapal-ir/src/algo/algebra.rs:377compiler heap: FuncFacts.fold_combine
StepAlgebra / FmaPair / RegroupWhich multiply-add pairs may fuse into one rounding and which fold steps may be regrouped into lane partials plus a tree.crates/mapal-ir/src/algo/algebra.rs:61compiler heap: FuncFacts.step_algebra
BoundsProofWhich Index reads are proven inside their array, and the integer range of each index.crates/mapal-ir/src/algo/bounds.rs:49compiler heap: FuncFacts.bounds_proof
PrecisionPlan / NarrowStoreThe precisions each product admits, where rounding happens once, and each site's error bound.crates/mapal-ir/src/algo/precision.rs:16compiler heap: FuncFacts.precision_planFlow graph
RadixForm / Digit / RadixTileAn integer index split into digits (x divided by a stride, modulo a radix), which lets convolution and attention reads count as tiles.crates/mapal-ir/src/algo/radix.rs:33compiler heap: SecondaryMap<ObjectId, RadixForm> in FuncFacts.radix_plan
FinitePlanWhich float values are proven free of infinity and NaN by interval arithmetic.crates/mapal-ir/src/algo/range.rs:65compiler heap: FuncFacts.finite_plan
StaticPlan / StaticRoot / RealizeWhich values are computable before the program runs and whether each is embedded as bytes, attempted, or computed at run time.crates/mapal-ir/src/algo/statics.rs:90compiler heap: FuncFacts.static_planFlow graph
StreamPlan / StreamGroup / StreamGuard / GuardBoxA group proven to run in one pass over windows of an axis (attention style), with each member's role and the mask as a box.crates/mapal-ir/src/algo/stream.rs:71compiler heap: FuncFacts.stream_plan
StreamPlan / StreamGroupOne pass over windows of an axis (attention-like): the role of each member.crates/mapal-ir/src/algo/stream.rs:412cached in FuncFactsFlow graph
UnchangedPlan / CallKeepFor each loop-body array the cells that may differ from the previous trip, and for each call the arguments that are the same every time.crates/mapal-ir/src/algo/unchanged.rs:48compiler heap: FuncFacts.unchanged_plan and call_keep
ExpForm / NarrowForm / MathFormThe contract of the exponential and of each narrow float format (algorithm constants, error bound, exactness).crates/mapal-ir/src/exp.rs:30compiler heap: plain values; NarrowForm in narrow.rs
FactArmsSwitches that turn individual fact rules off, used only to compare against the older behaviour (all on by default).crates/mapal-ir/src/facts.rs:73compiler heap: field of Facts, set by CategoryIr::refactedFlow graph
FuncFacts / Facts (fact store)One write-once slot per function per fact (OnceLock); a query fills its slot on first use and every later call reads it.crates/mapal-ir/src/facts.rs:25compiler heap: SecondaryMap<FuncId, FuncFacts> inside CategoryIr.factsFlow graph
ResidencePlan / ResidencePer array its bytes and peak live bytes between producer and last reader, giving Chip, L2 or DRAM against a cache size.crates/mapal-ir/src/residence.rs:34compiler heap: FuncFacts.residence_planFlow graph
SplitForm / AccModelA way to do an f32 product on a matrix instruction by cutting operands into exact parts, with its error coefficient.crates/mapal-ir/src/split.rs:62compiler heap: plain values built by SplitForm::of
UnitPlan / UnitGroup / UnitMember / RowMapGroups of sites that share a block of rows so intermediates stay on chip, each member's role and row mapping.crates/mapal-ir/src/unit.rs:120compiler heap: FuncFacts.unit_plan
UnitPlan / UnitGroupRow-block groups of sites that can run together on chip.crates/mapal-ir/src/unit.rs:157cached in FuncFactsFlow graph
Arrows (7)
ArrowFrom → toWhat it doesDefined at
Hazard edges within a loop tripMorphismId → MorphismIdWhich operation must wait for which, with the kind of conflict.crates/mapal-ir/src/access.rs:96
Fact query by objectObjectId → Fact entryEvery fact answers per-object or per-morphism questions: death, delta, residence, finite, class.crates/mapal-ir/src/algo/last_use.rs:50
LastUsePlan::death / position / carried_byObjectId / MorphismId → position / ObjectIdWhere a value dies; the order of an edge; which loop state carries a value across trips.crates/mapal-ir/src/algo/last_use.rs:50
fact(f, slot, compute)FuncId → Fact valueLook a fact up in the function's slot and compute it only if the slot is empty.crates/mapal-ir/src/facts.rs:226
CategoryIr::fact(FuncId, slot) → plan valueReturn the stored fact, or compute it once from stored inputs and keep it.crates/mapal-ir/src/facts.rs:226
CategoryIr::refactedCategoryIr → CategoryIrCopy the graph with an empty fact store and different arms.crates/mapal-ir/src/facts.rs:203
ResidencePlan::atObjectId → ResidencePlace of a value given a cache capacity.crates/mapal-ir/src/residence.rs:53
Transformations (30)
NameFrom → toKindWhat it doesDefined atLives in
Seal the graphFlow
→ Flow
Facts
processFreezes the builder's graph and pre-allocates one empty fact slot per function.crates/mapal-ir/src/builder.rs:266compiler heap, once per graph
Validate the graphFlow
→ Diagnostics
processIndependently re-checks the graph's shape rules and lists violations; the test oracle for every pass.crates/mapal-ir/src/validate.rs:98compiler heap, returns Vec<IrViolation>
Loop factsFlow
→ Facts
functorFinds cycles, orders the graph, and reads each loop's canonical shape, trip splits and per-trip array writes.
made of: sccs, topo_order, loop_structure, loop_plan, trip_split, write_delta
crates/mapal-ir/src/algo/loops.rs:425FuncFacts slots
sccsFlow
→ Facts
processStrongly connected sets of objects, which are the loops.crates/mapal-ir/src/algo/loops.rs:13FuncFacts.sccs
topo_orderFlow
→ Facts
processA deterministic evaluation order of a function's operations.crates/mapal-ir/src/algo/loops.rs:162FuncFacts.topo_order
loop_structureFacts
→ Facts
processLists each loop and its merge objects.crates/mapal-ir/src/algo/loops.rs:385FuncFacts.loop_structure
loop_planFacts
→ Facts
processNames init, back route, exit and the decide/advance order of each canonical loop.crates/mapal-ir/src/algo/loops.rs:425FuncFacts.loop_plans
trip_splitFacts
→ Facts
processCuts a counted loop's trips where guards on the counter change behaviour.crates/mapal-ir/src/algo/site_plans.rs:336FuncFacts.trip_split
write_deltaFacts
→ Facts
processThe contiguous rows or pieces of a carried array that each trip writes.crates/mapal-ir/src/algo/write_delta.rs:36FuncFacts.write_delta
unchanged_plan and call_keepFacts
→ Facts
processCarries write deltas through row-local maps to say what stays the same between trips and calls.crates/mapal-ir/src/algo/unchanged/compute.rs:9FuncFacts.unchanged_plan, call_keep
static_planFacts
→ Facts
processFinds values computable before the program runs and prices embedding them against computing them.crates/mapal-ir/src/algo/statics.rs:137FuncFacts.static_plan
Lifetime and emission factsFlow
Facts
→ Facts
functorWhich values need bytes, when each dies, which bytes each operation touches, and where bytes live.
made of: emission_plan, last_use_plan, access_plan, residence_plan
crates/mapal-ir/src/algo/last_use.rs:142FuncFacts slots
emission_planFlow
→ Facts
processClassifies each object as materialized, dissolved into a view, inline or named.crates/mapal-ir/src/algo/site_plans.rs:26FuncFacts.emission_plan
last_use_planFacts
→ Facts
processPositions, death points, escapes and loop-carried liveness over two iterations.crates/mapal-ir/src/algo/last_use.rs:142FuncFacts.last_use_plan
access_planFacts
→ Facts
processReads, writes, storage classes and hazard edges per loop trip.crates/mapal-ir/src/access.rs:126FuncFacts.access_plan
residence_planFacts
→ Facts
processPeak live bytes from producer to last reader, compared to a cache size.crates/mapal-ir/src/residence.rs:65FuncFacts.residence_plan
path_plan and guard_planFlow
Facts
→ Facts
processSplits work into independent tasks, finds host checkpoints, and records which conditional arms must be gated.crates/mapal-ir/src/algo/paths.rs:16FuncFacts.path_plan, guard_plan, guard_structure
bounds_proof and finite_planFlow
Facts
→ Facts
processProves indices in range and values finite using integer and float interval arithmetic narrowed by the conditions that hold where a value is used.crates/mapal-ir/src/algo/bounds/compute.rs:9FuncFacts.bounds_proof, finite_plan
Site recognitionFlow
Facts
→ Facts
functorRecognizes maps and folds as tiles, row folds, cells and data moves and gives each element as a closed function of its index.
made of: elem_plan and map_law, tile_plan and variants, radix_plan, cell_plan, row_fold, whole_fold, move_plan, footprint_plan
crates/mapal-ir/src/algo/site_plans.rs:198FuncFacts slots
elem_plan and map_lawFlow
→ Facts
processEach array element as a closed function of its index, piecewise where cells outside a range are a capture's own.crates/mapal-ir/src/algo/elem.rs:20FuncFacts.elem_plan
tile_plan and variantsFlow
Facts
→ Facts
processFinds sum-of-products sites: plain, strided, with epilogue, narrow-storage, and mixed-radix.crates/mapal-ir/src/algo/site_plans.rs:198FuncFacts.tile_plan*, tile_plan_radix
radix_planFlow
→ Facts
processWrites each integer value as digits of the inputs so strided and implicit-matrix reads are visible.crates/mapal-ir/src/algo/radix.rs:263FuncFacts.radix_plan
cell_plan, row_fold, whole_fold, move_plan, footprint_planFlow
Facts
→ Facts
processPer-cell maps, row folds, data-move sites and what each cell reads.crates/mapal-ir/src/algo/cells.rs:16FuncFacts slots
Arithmetic freedom factsFlow
Facts
→ Facts
functorStates what the arithmetic may become: fused multiply-add, regrouped folds, block-combined folds.
made of: step_algebra, fold_combine, precision_plan
crates/mapal-ir/src/algo/algebra.rs:108FuncFacts slots
step_algebraFlow
→ Facts
processMultiply-add pairs that can fuse and fold steps that can regroup.crates/mapal-ir/src/algo/algebra.rs:108FuncFacts.step_algebra
fold_combineFacts
→ Facts
processHow block partials of a fold combine and how each per-row value is applied.crates/mapal-ir/src/algo/algebra.rs:428FuncFacts.fold_combine
precision_planFlow
Facts
→ Facts
processAdmitted product precisions, where rounding happens once, and a-priori error bounds per site.crates/mapal-ir/src/algo/precision.rs:112FuncFacts.precision_plan
Row-block and streaming factsFacts
→ Facts
functorGroups sites that can share a block of rows on chip, then proves a group can run window by window in one pass.
made of: unit_plan, stream_plan
crates/mapal-ir/src/unit.rs:284FuncFacts.unit_plan, stream_plan
unit_planFacts
→ Facts
processRow-block groups with row-closed edges and bytes per row.crates/mapal-ir/src/unit.rs:284FuncFacts.unit_plan
stream_planFacts
→ Facts
processOne-pass windowed evaluation of an axis, with mask boxes and per-fold combine laws.crates/mapal-ir/src/algo/stream.rs:430FuncFacts.stream_plan
Algorithms, data structures and design patterns (13)
NameKindWhat it isDefined atUsed by
Fact cache on the sealed graphdesign patternEach query is a pure function of the sealed graph, computed once into a write-once slot and read after that.crates/mapal-ir/src/facts.rs:226loop_plan, tile_plan and variants, last_use_plan, unit_plan, stream_plan
Arena with typed idsdata structureObjects, morphisms and functions sit in slot maps keyed by distinct id types; secondary maps hang per-id data off them with deterministic order.crates/mapal-ir/src/graph.rs:288Seal the graph, sccs, topo_order
Strongly connected componentsalgorithmLoop detection by finding cycles in the object graph.crates/mapal-ir/src/algo/loops.rs:13loop_structure, loop_plan
Topological orderalgorithmEvaluation order with insertion-order tie-breaks.crates/mapal-ir/src/algo/loops.rs:162last_use_plan, bounds_proof and finite_plan, path_plan and guard_plan
Liveness with two-iteration loop carryalgorithmPositions and death points of values, with a value live across a loop back edge marked carried.crates/mapal-ir/src/algo/last_use.rs:142residence_plan, unit_plan
Interval analysis narrowed by conditionsalgorithmInteger and float ranges tightened by the guards, loop bounds and phi arms where a value is used.crates/mapal-ir/src/algo/bounds/compute.rs:9bounds_proof and finite_plan
Digit decomposition of indicesalgorithmIndex arithmetic with constant division and remainder is split into per-digit affine terms to detect implicit matrix products.crates/mapal-ir/src/algo/radix.rs:263radix_plan, unit_plan, stream_plan
Hazard classification (RAW/WAR/WAW)algorithmDependencies between operations from the bytes they read and write, with shared buffers.crates/mapal-ir/src/access.rs:77access_plan
Working-set peak over a live intervalalgorithmA value's residence from the peak live bytes between producer and last reader against cache size.crates/mapal-ir/src/residence.rs:65residence_plan
A-priori error bound (gamma-n)algorithmA closed-form rounding error bound for sums of products used as the correctness gate.crates/mapal-ir/src/algo/precision.rs:83precision_plan
Online combine (running max and rescale)algorithmPer-block partials combined by the fold's own operator, with exp rescale for a running max.crates/mapal-ir/src/algo/algebra.rs:290fold_combine, stream_plan
Independent validatordesign patternA second pass re-derives the graph invariants without sharing builder code.crates/mapal-ir/src/validate.rs:98Validate the graph
Fact arms (OFF switches)design patternEach rule can be switched off for comparison, never per hardware.crates/mapal-ir/src/facts.rs:73bounds_proof and finite_plan, unchanged_plan and call_keep, stream_plan

Guarantees of Facts

Guarantee (natural transformation)What must agreeChecked in
Facts agree with the interpreterA claim a fact makes (a tile bound, a proven index, a static value) holds when the interpreter runs the program.crates/mapal-rewrite/tests/stream_plan.rs:135
crates/mapal-rewrite/tests/static_eval.rs:45

Rewrites

Rewrites the Flow graph into an equal, cheaper one (fold constants, remove dead and repeated work, inline, unroll).

Reads Flow, Facts → produces Flow

Guarantees: Rewrite preserves the interpreter's result, Replaying nothing changes nothing, Rewrite is deterministic and idempotent

Files (1)

crates/mapal-rewrite/tests/testgen/mod.rs:1

Transformations (12)
NameFrom → toKindWhat it doesDefined atLives in
rewrite: the fixpoint pipelineFlow
→ Flow
functorRuns inline, unroll, lift, constant fold, CSE, DCE and map fusion round after round until nothing changes (at most 32 rounds); the identity on non-canonical loops.
made of: Analysis passes, Replay
crates/mapal-rewrite/src/driver.rs:70compiler heap; returns a new graph
Analysis passesFlow
→ Flow: RewritePlan
processEach pass reads the graph and fills plan channels without changing the graph.crates/mapal-rewrite/src/driver.rs:87compiler heap
Constant folding and identitiesFlow
→ Flow: RewritePlan
processFolds constant scalars and forwards identities at the oracle's exact semantics, never folding a trap.crates/mapal-rewrite/src/equations.rs:24RewritePlan.constify, alias
Common-subexpression eliminationFlow
→ Flow: RewritePlan
processMerges duplicate pure computations; an element view outside guard arms is keyed by constant index value.crates/mapal-rewrite/src/graph_rewrites.rs:341RewritePlan.alias
Dead-code eliminationFlow
→ Flow: RewritePlan
processDrops dead cones of pure, non-trapping, terminating operations.crates/mapal-rewrite/src/graph_rewrites.rs:34RewritePlan.drop
Map fusionFlow
→ Flow: RewritePlan
processReplaces map g after map f by one map, and drops map of identity.crates/mapal-rewrite/src/functor_laws.rs:32RewritePlan.fuse, alias
InliningFlow
→ Flow: RewritePlan
processStrips Call operations by substituting the callee's body when it is small enough (256 morphisms).crates/mapal-rewrite/src/inline.rs:47RewritePlan.inline
Loop liftingFlow
→ Flow: RewritePlan
processRecognizes counted accumulator and fill loops and rewrites them as captured Fold or Map.crates/mapal-rewrite/src/lift.rs:23RewritePlan.lift
Loop unrollingFlow
→ Flow: RewritePlan
processReplays a short constant-trip loop as its trips one after another, up to 128 trips.crates/mapal-rewrite/src/unroll.rs:37RewritePlan.unroll
Static foldingFlow
Facts
→ Flow
processComputes the static_plan roots with the interpreter and replaces their cones with constants.crates/mapal-rewrite/src/statics.rs:34compiler heap; interpreter run at compile time
ReplayFlow
Flow: RewritePlan
→ Flow
functorWalks each function in topological order, classifies each object by its recipe, and rebuilds an equivalent graph through the public builder, so the output is well-formed by construction.crates/mapal-rewrite/src/replay.rs:67compiler heap; new CategoryIr
Canonical-loop guardFlow
→ Flow
processIf any loop is outside the canonical shapes, rewrite hands the graph back untouched.crates/mapal-rewrite/src/replay/support.rs:138compiler stack
Algorithms, data structures and design patterns (10)
NameKindWhat it isDefined atUsed by
Plan then replaydesign patternEvery pass only decides (graph to plan, pure); one shared replayer is the only code that builds graphs.crates/mapal-rewrite/src/plan.rs:65rewrite: the fixpoint pipeline, Inlining, Loop lifting, Common-subexpression elimination
Fixpoint iteration with round capalgorithmRounds repeat until all plans are empty or 32 rounds, with validation after each rebuild.crates/mapal-rewrite/src/driver.rs:87rewrite: the fixpoint pipeline
Value-numbering CSEalgorithmOperations with the same op and same source are merged; views key by constant index value outside guard arms.crates/mapal-rewrite/src/graph_rewrites.rs:395Common-subexpression elimination
Liveness-based DCEalgorithmBackward reachability from outputs and effects; anything that may trap or diverge is pinned live.crates/mapal-rewrite/src/graph_rewrites.rs:34Dead-code elimination
Functor law as rewrite ruledesign patternMap fusion justified by map g after map f equals map (g after f); each pass names its law and preconditions.crates/mapal-rewrite/src/functor_laws.rs:32Map fusion
Body substitution (inlining and fusion synthesis)algorithmA callee or fused body is rebuilt in the caller with its input mapped to the call source and fresh ids.crates/mapal-rewrite/src/replay/inline.rs:13Replay, Inlining, Map fusion
Evaluate at compile time with the oracledesign patternStatic values are computed by the interpreter itself, so they are exact on every number face.crates/mapal-rewrite/src/statics.rs:34Static folding
By-value intake and no-op shortcutdesign patternThe graph is moved in; an all-empty round returns it without a rebuild.crates/mapal-rewrite/src/driver.rs:70rewrite: the fixpoint pipeline
Random program generator (testgen)design patternA proptest script of steps is built into a sealed graph or source text, used to validate rules on programs they were not designed on; checked in parallel.crates/mapal-rewrite/tests/testgen/mod.rs:203Rewrite preserves the interpreter's result, Facts agree with the interpreter
Rule data tabledata structureThe Zip/Enumerate naturality laws kept as a const table.crates/mapal-rewrite/src/naturality.rs:30rewrite: the fixpoint pipeline

Guarantees of Rewrites

Guarantee (natural transformation)What must agreeChecked in
Rewrite preserves the interpreter's resultEvaluating the graph before and after rewriting gives the same result, traps included.crates/mapal-rewrite/tests/property.rs:67
Replaying nothing changes nothingReplaying with an empty plan reproduces a valid graph equal to the original for every example.crates/mapal-rewrite/tests/identity.rs:55
Rewrite is deterministic and idempotentRewriting twice equals rewriting once, and the same input always gives the same output.crates/mapal-rewrite/tests/property.rs:151

Interpreter

Runs a Flow graph directly on the CPU. It is the reference: every compiled result is compared against it.

Reads Flow, Facts → produces Values

Guarantees: Same graph, same result, The default face lies inside the bound, Traps and divergence are outcomes, not panics, Compiled code agrees with the interpreter within the bound

Files (5)

crates/mapal-interp/src/lib.rs:1
crates/mapal-interp/src/eval.rs:1
crates/mapal-interp/src/loops.rs:1
crates/mapal-interp/src/value.rs:1
crates/mapal-interp/src/bound.rs:1

Category Values

What a program computes: scalars, arrays and records, and the error bound of a result.

Objects (11)
ObjectWhat it isDefined atLives inProvided by
BoundA printed value's error bound split by source: member rounding, summation order, fma, comparison flip, math builtin.crates/mapal-interp/src/bound.rs:60Vec<Bound> returned by run_bound, one per print
TapeRecord of every float operation of the exact run: operands, partial derivatives, own deviation.crates/mapal-interp/src/bound.rs:146thread-local TAPE (RefCell<Option<Tape>>) during run_bound
EvalCtxWorking state of one function evaluation: value of each object, staged product slots, guard sites, gated morphisms.crates/mapal-interp/src/eval.rs:20compiler heap, one per function call
RunResult / Outcome / BoundOutput text, how it ended, each printed float's composed bound.crates/mapal-interp/src/lib.rs:40compiler heapCommand line
RunResultOutcome plus the printed output text.crates/mapal-interp/src/lib.rs:33returned by value; output is a String
AbortInternal early exit (Diverged, Trapped, ReadFailed) threaded as the Err side.crates/mapal-interp/src/value.rs:86Result error; read failure message in a thread-local READ_FAILURE
OutcomeHow a run ended: Done(value), Diverged, Trapped(kind), ReadFailed(message).crates/mapal-interp/src/value.rs:61returned by value
RValueA runtime value: scalar, tuple, struct, array (shared), world token with its log, tracked scalar (for bounds), unit.crates/mapal-interp/src/value.rs:14compiler process heap while the oracle runs; arrays in Rc<Vec<RValue>>
TrapKindDivZero or IndexOob.crates/mapal-interp/src/value.rs:51inside Outcome
Embedded static valueA value the interpreter computed at compile time and spliced into the graph as constants.crates/mapal-rewrite/src/plan.rs:65compiler heap, then constants inside the new graphRewrites
RValue / interpreter resultThe interpreter's value for a program or call, compared before and after a rewrite (floats within tolerance).crates/mapal-rewrite/tests/property.rs:47test heapRewrites
Arrows (5)
ArrowFrom → toWhat it doesDefined at
componentRValue (product) → RValue (slot k)Take a component of a runtime product.crates/mapal-interp/src/eval/helpers.rs:64
eval_fnFuncId and RValue (argument) → RValue (result)Evaluate one function on an argument.crates/mapal-interp/src/eval.rs:84
native_observableRunResult → (stdout, exit code)What the compiled program must print and exit with.crates/mapal-interp/src/lib.rs:252
renderValue → StringPrint a scalar the way the program shows it.crates/mapal-interp/src/value.rs:113
Abort::into_outcomeAbort → OutcomeLift an early exit to the public outcome.crates/mapal-interp/src/value.rs:97
Transformations (8)
NameFrom → toKindWhat it doesDefined atLives in
run / run_orderedFlow
→ Values: (RunResult
functorSeed the entry function (world token or unit), walk the graph, return the outcome and output; total, never panics.crates/mapal-interp/src/lib.rs:40compiler heap; fuel is a u64 counter passed by &mut
eval_fn_within (walk operations in topological order)Flow
Facts: (topo, guard_plan
→ Values
processFor each morphism in order compute the target value from its sources; Map and Fold call body functions; reads load files; each step spends one unit of fuel.crates/mapal-interp/src/eval.rs:107EvalCtx.env SecondaryMap<ObjectId, RValue>
run_loop (guard-first loop driver)Flow: (loop SCC
Facts: (loop_plan
→ Values
processPer trip: decide and exit first, advance only if continuing, so speculative reads never happen on the exit step.crates/mapal-interp/src/loops.rs:31EvalCtx.env, staging buffers reset per trip
Phi handler (gated arms)Flow
Facts: (guard_plan
→ Values
processArm work that may trap or is heavy runs only when the condition picks that arm.crates/mapal-interp/src/eval.rs:107EvalCtx.guards and EvalCtx.gated
eval_values / eval_values_once / static_coneFlow
Facts: (static roots
→ Values
processEvaluate only the cone of values feeding chosen root objects; used to embed compile-time constants.crates/mapal-interp/src/lib.rs:127SecondaryMap of the wanted objects; results Vec<Option<RValue>>
run_bound (record tape, reverse sweep)Flow
Facts: (precision_plan, step_algebra
→ Values: (Bound
functorRun exactly, record each float op, then one backward pass per printed value gives how far fast realizations may differ (reduced-precision members, summation order, fma, math builtins).crates/mapal-interp/src/bound.rs:170thread-local Tape; Bound per print
run_weakestFlow
→ Values: (RunResult
processRun with every admitted reduced-precision multiply taken at its coarsest grid, giving the opposite extreme of the oracle.crates/mapal-interp/src/lib.rs:85thread-local WEAKEST flag in eval.rs
Math and Narrow ops via ir Native ArithValues: (scalar
Types
→ Values: (scalar
processEvaluate exp/sqrt/sin/cos and narrow rounding with the same definitions a backend prints.crates/mapal-interp/src/eval.rs:107Native<B> in crates/mapal-ir/src/math.rs
Algorithms, data structures and design patterns (7)
NameKindWhat it isDefined atUsed by
Fuel (step budget) for total evaluationdesign patternA u64 budget decremented per step so every run halts with Done, Diverged or Trapped.crates/mapal-interp/src/eval.rs:62run / run_ordered, eval_fn_within (walk operations in topological order), eval_values / eval_values_once / static_cone
Result as early-exit channel (Abort)design patternTraps, divergence and read failure travel as Err and are lifted once at the entry.crates/mapal-interp/src/value.rs:86run / run_ordered, eval_fn_within (walk operations in topological order)
Guard-first loop evaluationalgorithmDecide and exit cone evaluated before the advance cone.crates/mapal-interp/src/loops.rs:31run_loop (guard-first loop driver)
Reverse-mode derivative tape (first-order error composition)algorithmRecord partial derivatives forward, sweep backward per output to compose deviations along the program.crates/mapal-interp/src/bound.rs:249run_bound (record tape, reverse sweep)
Shared immutable arrays (Rc) with staging slots for productsdata structureArrays are reference counted; products are assembled in staging buffers slot by slot, matching Pair edges.crates/mapal-interp/src/eval/helpers.rs:74eval_fn_within (walk operations in topological order)
Cone evaluation (evaluate only what a root reads)algorithmRestrict the walk to the set of objects feeding wanted roots.crates/mapal-interp/src/lib.rs:201eval_values / eval_values_once / static_cone
Thread-local recorders (tape, weakest flag, read failure)design patternOptional modes switched by scoped thread-local state so the common path has no extra parameters.crates/mapal-interp/src/bound.rs:170run_bound (record tape, reverse sweep), run_weakest

Guarantees of Interpreter

Guarantee (natural transformation)What must agreeChecked in
Same graph, same resultRunning twice gives the identical outcome and output (no hash maps, no clocks in the value path).crates/mapal-interp/tests/determinism.rs:59
crates/mapal-interp/tests/determinism.rs:49
The default face lies inside the boundThe weakest-precision run differs from the exact run by at most the composed error bound.crates/mapal-interp/tests/bound.rs:86
crates/mapal-interp/tests/bound.rs:124
Traps and divergence are outcomes, not panicsAn out-of-range index, a zero division or running out of steps gives Trapped or Diverged rather than a crash.crates/mapal-interp/tests/traps.rs:111
crates/mapal-interp/tests/traps.rs:40
crates/mapal-interp/tests/divergence.rs:60
Compiled code agrees with the interpreter within the boundThe compiled program's printed values equal the interpreter's within the interpreter's bound; the check lives in the backend tests.crates/backends/llvm/tests/differential/basics.rs:10
crates/backends/llvm/tests/differential/batching.rs:274

Hardware facts and rules

Describes a chip by its measurable properties and picks optimization switches from those properties, never from a chip's name.

Reads Target → produces Target, Schedule

Guarantees: The native profile is the query plus the calibration, The rules agree with every cited measurement, The rules ignore names

Files (10)

crates/backends/llvm/src/profile.rs:1
benches/gpu/calib.cu:1
benches/local/place_calib.cu:1
benches/local/place_calib_opt.cu:1
benches/local/place_calib.sh:1
benches/local/place_calib_facts.py:1
benches/results/evidence/local-rtx-5080/calib/rtx-5080.calib:1
crates/backends/llvm/src/rules.rs:1
crates/backends/llvm/src/rung_replay.tsv:1
crates/backends/llvm/src/lib.rs:1

Category Target

A chip as measurable properties (SM count, cache sizes, rates) plus the calibration lines that measured them.

Objects (13)
ObjectWhat it isDefined atLives inProvided by
calibration lineOne text line per device: a key made of physical facts, then name=value pairs the probes measured.benches/results/evidence/local-rtx-5080/calib/rtx-5080.calib:1a text file on disk (also embedded into the compiler binary as COMMITTED_CALIB, or read from MAPAL_GPU_CALIB or ~/.cache/mapal/gpu-calib)
PLACE_* tablesThe measured placement numbers written into the compiler, one table per known part (4090, 5090, 5080, 3090, A100, H100, H100 PCIe, a generic Ada one).crates/backends/llvm/src/profile/place_rtx_5080.rs:66compiler process: constants in read-only data
CalibSourceSays where the calibration text for this run came from: a file, the committed line, or none.crates/backends/llvm/src/profile/calib.rs:7compiler process: a OnceLock static
Machine (CPU or GPU class)The choice inside a profile: a CPU core, or a GPU streaming multiprocessor with its extra facts.crates/backends/llvm/src/profile/facts.rs:87inside TargetProfile, same place
CapsWhat instructions the chip can run, described by what they move and compute (cp.async copies, matrix shapes, bulk copies, PTX level), never by a version number.crates/backends/llvm/src/profile/caps.rs:12compiler process: field of GpuLLVM backend
DeviceCostMapal's own achieved rates on this part (FMA-tile flops per ns, launch cost, copy and zero-pass rates, ...), each from a named calibration run.crates/backends/llvm/src/profile/device_cost.rs:10compiler process: Option field of Gpu; values come from a constant or the calibration textLLVM backend
DeviceQueryWhat the driver reports about device 0 (compute capability, SMs, registers, shared memory, L2, clocks, memory bus).crates/backends/llvm/src/profile/calib.rs:61compiler process stack, built from cuDeviceGetAttribute answers
GpuThe facts of one GPU SM and chip: threads per warp, number of SMs, registers, shared memory, L2 bytes, clock, capabilities, and an optional measured cost table.crates/backends/llvm/src/profile/facts.rs:113compiler process: inside TargetProfile (Copy struct, no heap)LLVM backend
MatrixOp / MmaShape / MmaFmtOne matrix-multiply instruction as geometry (rows x columns x depth, operand formats, where operands live, rate per clock).crates/backends/llvm/src/profile/matrix.rs:79compiler process: static tables inside CapsLLVM backend
PlaceFactsThe extra measured numbers the machine model reads: per-operation efficiency curves, primitive rates and latencies, L2 keep, hit curve, sustained clock, each with where it came from.crates/backends/llvm/src/profile/facts.rs:220compiler process: a static table per part (PLACE_RTX_5080 and others) referenced from TargetProfile::placeLLVM backend
TargetProfileOne part's whole description: name, CPU or GPU class, cache sizes, vector widths, and (for a GPU) the Gpu facts plus measured costs.crates/backends/llvm/src/profile/target.rs:8compiler process: a const in the binary's read-only data (hand profiles such as RTX_5080) or one built at start-up and leaked into a static (native-gpu)LLVM backend
CostOverA list of optional overrides, one slot per DeviceCost field, read from a calibration line.crates/backends/llvm/src/profile/device_cost.rs:367compiler process stack
SrcA tag that goes with every number: measured, queried, declared, derived or nominal. Derived and nominal numbers are marked as less certain.crates/mapal-place/src/fact.rs:7compiler process: inside every Fact
Arrows (14)
ArrowFrom → toWhat it doesDefined at
calib_linecalibration text, key → CostOverReads one device's line into numbers.crates/backends/llvm/src/profile/calib.rs:264
calib_supplycalibration key → calibration textFinds the calibration text: env file, cache file, then the committed line, or none.crates/backends/llvm/src/profile/calib.rs:36
caps_of_cccompute capability → CapsTurns the compute capability into the instruction abilities once, at the boundary.crates/backends/llvm/src/profile/matrix.rs:343
native_gpudevice query + calib file → TargetProfileQuery the driver and read measured calibration; never a name lookup.crates/backends/llvm/src/profile/native.rs:92
resolveprofile name → &TargetProfileNamed profile or detected native; unknown name is an error.crates/backends/llvm/src/profile/registry.rs:111
with_hostdevice and host profiles → combined profileA GPU build also carries its host's CPU facts.crates/backends/llvm/src/profile/profiles_host.rs:11
Gpu::matrix_opGpu, format, operand home → MatrixOp (optional)Looks up the matrix instruction that fits a format and operand location.crates/backends/llvm/src/profile/matrix.rs:271
DeviceQuery::calib_keyDeviceQuery → calibration key (String)Turns the physical facts into the key that finds this part's calibration line.crates/backends/llvm/src/profile/calib.rs:138
DeviceQuery::deviceCUDA driver → DeviceQueryAsks the driver (libcuda opened at run time) for device 0's attributes.crates/backends/llvm/src/profile/calib.rs:111
DeviceQuery::profileDeviceQuery, calibration text → TargetProfileBuilds the profile of this machine's GPU from the query and the measured rates.crates/backends/llvm/src/profile/calib.rs:149
Gpu::dram_bytes_per_us_per_smGpu → rateThe share of memory bandwidth one SM gets.crates/backends/llvm/src/profile/plan.rs:526
Gpu::l2_keep_bytesGpu → bytesHow many bytes of a repeatedly read set the L2 actually keeps.crates/backends/llvm/src/profile/plan.rs:382
Gpu::warps_per_schedulerGpu, grid size → countHow full a grid keeps the chip's schedulers.crates/backends/llvm/src/profile/plan.rs:539
TargetProfile::gpuTargetProfile → Gpu (optional)Picks out the GPU facts, if this is a GPU profile.crates/backends/llvm/src/profile/target.rs:586
Transformations (6)
NameFrom → toKindWhat it doesDefined atLives in
Calibration probesTarget: the physical chip
→ Target: calibration line
processSmall CUDA programs time the chip (latency, bandwidth, matrix rate, launch gaps, L2 keep, efficiency curves, primitive rates) and print name=value lines. A Python script turns the print-out into calibration keys and Rust table fields.benches/gpu/calib.cu:1runs on the GPU box; output is a text file on disk; extra probe in benches/local/place_calib.cu, optional modules in benches/local/place_calib_opt.cu, driver script benches/local/place_calib.sh, converter benches/local/place_calib_facts.py
Native GPU profileTarget: DeviceQuery
Target: calibration line
→ Target: TargetProfile
functorQuery the driver, find the calibration line, and assemble the part's profile. No part names are looked at.
made of: Ask the driver, Find the calibration, Assemble the profile
crates/backends/llvm/src/profile/native.rs:92compiler process: one TargetProfile leaked into a OnceLock static at first use
Ask the driverTarget: CUDA driver
→ Target: DeviceQuery
processLoads libcuda.so.1 at run time and reads attributes.crates/backends/llvm/src/profile/detect.rs:8compiler process stack
Find the calibrationTarget: calibration key
→ Target: calibration text
processEnv file, cache file, committed line in that order.crates/backends/llvm/src/profile/calib.rs:36reads a file from disk; text kept in the process
Assemble the profileTarget: DeviceQuery
Target: CostOver
→ Target: TargetProfile
functorFills Gpu, Caps and DeviceCost; fills the PlaceFacts fields from the calibration's place.* keys.crates/backends/llvm/src/profile/calib.rs:149compiler process heap, then leaked
Choose optimization switches from propertiesTarget: Gpu
Target: site fill
→ Schedule: GpuRungs
functorMaps a chip and a site's fill to the switches, using thresholds that sit between the nearest measured winner and loser.crates/backends/llvm/src/rules.rs:342compiler process, pure function evaluated per site while emitting
Algorithms, data structures and design patterns (8)
NameKindWhat it isDefined atUsed by
Facts carry provenancedesign patternEvery number is tagged with how it was obtained, and uncertain ones are marked so a decision that depends on them can be called open.crates/mapal-place/src/fact.rs:64Assemble the profile, Translate the profile
Layered fallback for calibrationdesign patternTry the user's file, then the file in the repository, else run with unmeasured numbers.crates/backends/llvm/src/profile/calib.rs:36Find the calibration
Capabilities as geometrydesign patternInstructions are described by what they move and compute, so rules never compare versions.crates/backends/llvm/src/profile/caps.rs:12Assemble the profile
Probe sweep to kneealgorithmEach primitive is swept over how much work a unit keeps in flight; rate is the best point, concurrency the least in flight reaching 90 percent of it.benches/local/place_calib.cu:1Calibration probes
Static table per partdata structureA constant struct per known part, plus a lookup by physical key for new ones.crates/backends/llvm/src/profile/place_rtx_5080.rs:66Assemble the profile
Threshold between nearest winner and loseralgorithmEach rule's cut is placed between the closest measured case that won and the closest that lost, then replayed.crates/backends/llvm/src/rules.rs:342Choose optimization switches from properties
Plan and replaydesign patternDecisions are stored as data (a tsv of measurements) and a test replays them against the rule code.crates/backends/llvm/src/rung_replay.tsv:1The rules agree with every cited measurement
ON/OFF measurement armsdesign patternEvery optimization switch can be forced on or off from the command line for A/B timing; defaults come from the rules only.crates/backends/llvm/src/gpu_arms.rs:544Choose optimization switches from properties

Guarantees of Hardware facts and rules

Guarantee (natural transformation)What must agreeChecked in
The native profile is the query plus the calibrationFor every device query and calibration line, the native profile equals the one built from those two inputs alone (no name lookup).crates/backends/llvm/src/rules/native_tests.rs:50
The rules agree with every cited measurementFor every recorded measurement, what the rules decide matches the measured winner, or the line is marked open.crates/backends/llvm/src/rules/tests.rs:124
The rules ignore namesTwo parts with the same properties take the same switches.crates/backends/llvm/src/rules/tests.rs:407

Machine model

A model of one machine that prices a way of running a computation and searches for the cheapest, with a bridge to the GPU backend.

Reads Target, Facts → produces Machine, Schedule

Guarantees: Search equals exhaustive, The closed form equals the LRU simulation, Time is monotone and above the bound, The pick does not depend on enumeration order, The pick agrees with the measured winner, The floor is admissible on every replay arm, The host launches the kernel the device module holds, The error band is the replay's residuals

Files (14)

crates/mapal-place/src/lib.rs:1
crates/mapal-place/src/fact.rs:1
crates/mapal-place/src/machine.rs:1
crates/mapal-place/src/schedule.rs:1
crates/mapal-place/src/lower.rs:1
crates/mapal-place/src/space.rs:1
crates/mapal-place/src/eval.rs:1
crates/mapal-place/src/reuse.rs:1
crates/mapal-place/src/lru.rs:1
crates/mapal-place/src/search.rs:1
crates/backends/llvm/src/place.rs:1
crates/backends/llvm/src/place_replay.rs:1
crates/backends/llvm/src/place_replay.tsv:1
crates/backends/llvm/src/func/gpu.rs:1

Category Machine

The abstract machine the placement search prices: levels of memory, rates, latencies.

Objects (14)
ObjectWhat it isDefined atLives in
BoundWhich end of the intervals to read: slow, value or fast.crates/mapal-place/src/fact.rs:52compiler process stack
Fact<T>A value with its source tag and a low and high end.crates/mapal-place/src/fact.rs:64inside every numeric field
Cache / Keep / PolicyA cache place's line size, how many bytes it keeps for each access pattern, and per-access policies (evict first, persist).crates/mapal-place/src/machine.rs:253boxed inside Place::mgmt
CostA primitive's rate, latency and loaded latency in ns at one bound, with a flag for borrowed or marked inputs.crates/mapal-place/src/machine/prims.rs:237compiler process stack
DispatchHow work reaches executors: slot start timing, launch costs by mode, atomics, zero pass, clock, barriers.crates/mapal-place/src/machine/prims.rs:116field of Machine
Exec / ExecKindA level of compute: device, unit (SM), scheduler, warp group, lane, with how many instances sit under each parent.crates/mapal-place/src/machine.rs:36Vec<Exec> inside Machine
MachineThe whole machine: executors, places, capacity groups, unit resources, issue pipes, operations, movers, dispatch and measured primitives.crates/mapal-place/src/machine.rs:351compiler process heap (Vecs); one per part, cached per process
MoverA way to move bytes from one place to another and who issues it (load, async copy, bulk copy).crates/mapal-place/src/machine/prims.rs:65Vec<Mover> inside Machine
OpOne compute instruction as a row of geometry and rate (FMA lane, warp matrix product, warpgroup product) with formats, fragment registers and efficiency points.crates/mapal-place/src/machine.rs:141Vec<Op> inside Machine
Pipe / ClassHow many instructions of a class (math, matrix, shared, global, barrier) a unit issues per clock.crates/mapal-place/src/machine/prims.rs:25Vec<Pipe> inside Machine
PlaceSomewhere bytes can live: registers, shared memory, L2, DRAM, tensor memory, host. Has capacity, how it is managed, banking, backing place and reach.crates/mapal-place/src/machine.rs:288Vec<Place> inside Machine
Prim / PrimOfA measured primitive (a compute row, a load, a copy, a panel stream, a store, a reduction, a barrier, a launch) with rate, latency and concurrency each as a Fact.crates/mapal-place/src/machine/prims.rs:222Vec<Prim> inside Machine::prims
ReachAn executor's link to a place: bandwidth per instance, total bandwidth, loaded latency, transaction size.crates/mapal-place/src/machine.rs:275Vec<Reach> inside Place
ResourceA per-unit capacity a running block occupies (registers, threads, slots, scratchpad bytes); occupancy is derived from it.crates/mapal-place/src/machine.rs:328Vec<Resource> inside Machine
Arrows (8)
ArrowFrom → toWhat it doesDefined at
Fact::rate / Fact::costFact, Bound → numberRead a rate at its slow or fast end, a cost at the opposite end.crates/mapal-place/src/fact.rs:121
Machine::costPrimOf, Bound → CostA primitive's price: its measured row, else a neighbour's, else derived from other facts and marked.crates/mapal-place/src/machine/cost.rs:19
Machine::nearPrimOf → neighbouring measured PrimFinds the closest measured row to borrow when one is missing.crates/mapal-place/src/machine/cost.rs:185
Machine::occupancythreads, registers, bytes → slots per unitHow many blocks fit on a unit given what each takes.crates/mapal-place/src/machine.rs:475
Machine::reachPlace, ExecKind → ReachHow an executor level gets at a place.crates/mapal-place/src/machine.rs:442
Machine::rowsMachine → Vec<Row>Lists every numeric fact with its provenance for the evidence report.crates/mapal-place/src/machine.rs:511
Exec.parentExec → ExecThe level above (lane to warp to scheduler to SM to device).crates/mapal-place/src/machine.rs:36
Place.backingPlace → PlaceWhere a miss or spill goes (L2 to DRAM).crates/mapal-place/src/machine.rs:288

Category Schedule

A way of running a piece of work: tile shapes, launch geometry, residency, placement picks.

Objects (51)
ObjectWhat it isDefined atLives inProvided by
ChainA chain of dependent launches that become one persistent kernel.crates/backends/llvm/src/func/calls.rs:267compiler heapLLVM backend
Block / Slices / StageRows per block, a row cut over blocks, and the staged shared-memory window.crates/backends/llvm/src/func/flow.rs:204compiler heapLLVM backend
UMember / UKind / USrcA member (fold, cell, or tile), its kind, and where each input comes from.crates/backends/llvm/src/func/flow.rs:84compiler heapLLVM backend
UnitA row-block group: one launch, rows threads, ordered members, operands, optional slices or stream.crates/backends/llvm/src/func/flow.rs:105compiler heap, inside ResidentPlan.unitsLLVM backend
ArithmeticWhat the kernel computes with: separate mul-add, ordered FMA, TF32/half/split matrix instructions.crates/backends/llvm/src/func/gpu/launch_rules.rs:8compiler stackLLVM backend
CombineHow partial sums are joined: none, split atomic, workspace, stream-K.crates/backends/llvm/src/func/gpu/launch_rules.rs:89field of LaunchLLVM backend
LaunchThe concrete kernel choice the emitter uses: tile kind, block size, grid, combine, optimization switches.crates/backends/llvm/src/func/gpu/launch_rules.rs:60compiler process stack, CopyLLVM backend
MmaWalkTile grid rounds across SMs versus a stream-K walk on the matrix pipes.crates/backends/llvm/src/func/gpu/mma_plan.rs:389compiler stackLLVM backend
SiteCandOne candidate launch of a site's table with its arms and flipped axes.crates/backends/llvm/src/func/gpu/site_table.rs:18compiler heapLLVM backend
SiteTableA site's candidate table on its way to the launch point.crates/backends/llvm/src/func/gpu/site_table.rs:28compiler heap; constant table in the host module at run timeLLVM backend
RefuseWhy a launch was not added to an open group (args, block, smem, occupancy, waves).crates/backends/llvm/src/func/horizontal.rs:97compiler stack; reported in evidence linesLLVM backend
HzGroupLaunches merged side by side or as a persistent chain, with each member's level.crates/backends/llvm/src/func/horizontal.rs:63compiler heap, inside ResidentPlan.hzLLVM backend
ShapeA launch's grid and resource use, the input of the merge rule.crates/backends/llvm/src/func/horizontal.rs:84compiler stackLLVM backend
DevSiteA device site: a tile site or a row fold.crates/backends/llvm/src/func/resident.rs:136compiler heapLLVM backend
ArenaOne device allocation per function, with a byte offset for each member whose lifetime allows sharing.crates/backends/llvm/src/func/resident.rs:469compiler heap (plan); at run time one slab in GPU global memoryLLVM backend
BatchA loop whose skippable first trips are written once by one launch before entry.crates/backends/llvm/src/func/resident.rs:449compiler heapLLVM backend
CarryA loop state kept on the device across trips: merge, next value, views, exit.crates/backends/llvm/src/func/resident.rs:71compiler heap; at run time one device buffer per carryLLVM backend
CellA per-cell map run as its own one-thread-per-cell kernel.crates/backends/llvm/src/func/resident.rs:273compiler heapLLVM backend
DeltaUpAn upload that sends only the rows a trip wrote.crates/backends/llvm/src/func/resident.rs:121compiler heap; a first-pass flag slot on the host stackLLVM backend
EpiA tile with its epilogue cells grouped so the cell work rides on the tile launch.crates/backends/llvm/src/func/resident.rs:198compiler heapLLVM backend
GenA producer computed on the device (id, body function, element count).crates/backends/llvm/src/func/resident.rs:110compiler heapLLVM backend
ResidentPlanThe whole decision record of one function: uploads, keeps, device-built producers, carries, arena, units, merged launches.crates/backends/llvm/src/func/resident.rs:377compiler heap, a pure function of Flow, profile and optimization switches; computed before the walkLLVM backend
RetainCellA cell whose output differs from the previous trip only in a row range, so later trips launch only that range.crates/backends/llvm/src/func/resident.rs:315compiler heapLLVM backend
RetainedA tile site over a carried array that recomputes only the rows the last trip wrote.crates/backends/llvm/src/func/retain.rs:29compiler heapLLVM backend
StreamOne pass over windows of an axis (attention shape): rows per block, window, threads, cp.async, split-KV, matrix format.crates/backends/llvm/src/func/stream.rs:52compiler heapLLVM backend
GpuArmsThe user's measurement flags: which optimization switches to force ON or OFF, plus placement search arms.crates/backends/llvm/src/gpu_arms.rs:544compiler process: options passed down from the command lineHardware facts and rules, LLVM backend
GpuRungsThe set of on/off optimization switches chosen for one site (wide tile, async copy, split, stream-K, machine-place, ...).crates/backends/llvm/src/gpu_rungs.rs:31compiler process: Copy struct inside each LaunchHardware facts and rules, LLVM backend
PLACE_BAND_PM / PLACE_NULLThe model's error band by bounding term and the measurement null (2 percent), derived from the replay's residuals.crates/backends/llvm/src/place/search.rs:18constants in read-only data
Emitter (Lowering)One present kernel family (naive cell, FMA tile, mma, wgmma, wgmma warp-specialized) acting as a Lowering over one site and profile.crates/backends/llvm/src/place/emitter.rs:9compiler stackLLVM backend
PlacedThe search's pick for a site: the launch to take, its plan name, the ; mapal.place line, whether open, whether the rules' launch was kept.crates/backends/llvm/src/place/search.rs:138compiler process heap; cached in a thread-local PICKS map keyed by site, part, arms and orderLLVM backend
place_replay.tsvOne row per measured arm of a site on a part: extents, formats, order, arm name and measured time.crates/backends/llvm/src/place_replay.tsv:1text file in the repo; read by tests
FaceThe numeric promise being compiled for (exact, default, TF32 and so on), which changes which optimization switches are allowed.crates/backends/llvm/src/profile/choice.rs:12compiler process stackHardware facts and rules
rung_replay.tsvOne line per cited measurement: the part's properties, fill and whether the optimization switch won; replayed against the rules.crates/backends/llvm/src/rung_replay.tsv:1text file in the repo; read by a testHardware facts and rules
CornerOne choice of slow or fast end for each of compute, cache, memory, dispatch; sixteen corners in all.crates/mapal-place/src/eval/terms.rs:223compiler process stack
FlowOne resource of a loop trip: work, rate, latency and bytes in flight.crates/mapal-place/src/eval/terms.rs:52compiler process stack
Terms / PhaseThe evaluator's result: per-phase times by resource (compute, issue, dram, cache, latency, atomics, epilogue, barriers), occupancy, misses, marked facts, infeasibility reason.crates/mapal-place/src/eval/terms.rs:112compiler process heap; one line written into the emitted module as a ; mapal.place comment
MoveHow a slot's panels arrive: register loads, async copies, bulk boxes.crates/mapal-place/src/lower.rs:13field of Declared
DeclaredWhat a lowering says its schedule costs: lanes, registers, shared bytes, instructions per class per trip, bytes in flight, mover.crates/mapal-place/src/lower.rs:27compiler process heap, paired with each candidate
Grid / Order / ReadsA traversal as the cache sees it (tiles, panels, slot sizes, access order) and the bytes missed per slice family.crates/mapal-place/src/reuse.rs:23compiler process stack; results memoized in thread-local hash maps
FoldHow free the order of the k sum is: any, fixed grouping, sequential.crates/mapal-place/src/schedule.rs:10inside Site
Traversal / CombThe order tiles are visited: ordered with raster, split into k partitions (atomic or workspace), stream-K walk, hybrid, persistent.crates/mapal-place/src/schedule.rs:96inside Schedule
Level / Home / BindA tile of m x n x k bound to an executor level or place, with each operand's place, layout and buffering depth.crates/mapal-place/src/schedule.rs:78inside Schedule::levels
ScheduleOne placement: the operation, tile levels with where each operand lives, groups, traversal, launch mode, cache policies, occupancy.crates/mapal-place/src/schedule.rs:133compiler process heap (Vec of levels)
SiteWhat the dataflow says about one tile site: sizes m, n, k, batch, operand bytes, fold freedom, allowed formats, operands already resident.crates/mapal-place/src/schedule.rs:26compiler process stack or heap, built per site
OptsSearch parameters: how many candidates to keep, error band per bounding term, null, traversal kinds allowed.crates/mapal-place/src/search.rs:37compiler process stack
Cand / Ranked / StatsA priced candidate (schedule, counts, terms, times at slow, value, fast, every corner), the search's ranked result, and counters of what was walked and pruned.crates/mapal-place/src/search.rs:117compiler process heap
VerdictThe index of the chosen candidate and the reasons it is open (a flip at some corner, or a tie).crates/mapal-place/src/search.rs:485compiler process stack
Wisdom file lineOne stored decision: key, site, pick, repetitions, nanoseconds, kernel names.crates/mapal-rt/gpu/mapal_choice.h:138a tab-separated file wisdom-<device>.tsv under MAPAL_WISDOM, XDG_CACHE_HOME or ~/.cache/mapalRuntime
choice_memoThe pick already decided for a table, found by the table's address.crates/mapal-rt/gpu/mapal_choice.h:125a small direct-mapped array in host static memoryRuntime
mapal_candOne candidate's launch recipe: main kernel id, reduce kernel id, bytes to zero, workspace bytes, grid, block, shared memory.crates/mapal-rt/gpu/mapal_choice.h:41a constant table in the emitted host module (56 bytes each; layout declared by SITE_DECL in the backend)Runtime
mapal_site_regA site, its table, its length and its flags (re-run safe, output already zeroed, cooperative, operand in DRAM).crates/mapal-rt/gpu/mapal_choice.h:54the constant array @mapal_sites in the host moduleRuntime
Arrows (44)
ArrowFrom → toWhat it doesDefined at
flag applyCLI flag text → EmitOpts updateEach --gpu-off=name and similar flag toggles one arm.crates/backends/llvm/src/flags.rs:8
member sourceUMember input slot → USrcWhere an input comes from: another member, global memory, the cell index, or a closed-form law.crates/backends/llvm/src/func/flow.rs:52
kernel_idTileSite, profile, contract → u64 idContent hash naming a kernel so equal sites share one.crates/backends/llvm/src/func/gpu/split_plan.rs:325
launch_inTileSite, TargetProfile, Order, arms → LaunchThe launch a site gets under an emission's order.crates/backends/llvm/src/func/gpu/launch_lines.rs:338
launch_splitTileSite, TargetProfile → Launch (split form)The launch with the k fold cut or streamed.crates/backends/llvm/src/func/gpu/launch_rules.rs:198
arena offsetObjectId → byte offsetWhere a member sits in the arena slab.crates/backends/llvm/src/func/resident/arena.rs:181
chain streamMorphismId → stream numberWhich stream each straight-line device site goes on.crates/backends/llvm/src/func/resident/plan.rs:405
upload / keep / elemObjectId → copy decisionPer object: copy in after producer, never copy out, or copy out one element.crates/backends/llvm/src/func/resident.rs:377
devgen / skipMorphismId → Gen or skippedPer producer: build it on the device, or skip it because every reader is device-built.crates/backends/llvm/src/func/resident.rs:377
free_afterMorphismId → objects freedWhich device buffers die right after this morphism.crates/backends/llvm/src/func/resident.rs:377
zero_by / zero_afteratomic site → kernel or step that zeroes its outputThe kernel or earliest step that clears an atomic site's output bytes.crates/backends/llvm/src/func/resident.rs:377
launch_ofSchedule → LaunchTurns a placed schedule back into the kernel geometry the emitter lowers.crates/backends/llvm/src/place/launch.rs:361
lowering_ofLaunch → emitter idNames which emitter a launch belongs to.crates/backends/llvm/src/place/search.rs:536
machine_ofTargetProfile → MachineReads every physical fact and its source into the target-neutral machine; missing facts become marked intervals.crates/backends/llvm/src/place/machine.rs:7
schedule_ofLaunch → ScheduleWrites the rules' launch as a schedule, so the rules' choice can be the search's incumbent.crates/backends/llvm/src/place/launch.rs:161
schedule_of / launch_ofLaunch / Schedule → Schedule / LaunchThe rules' launch as a schedule and back.crates/backends/llvm/src/place/launch.rs:161
site_ofTileSite (Flow facts) → SiteReads a dataflow tile site as extents, operand bytes, fold freedom, allowed formats.crates/backends/llvm/src/place/site.rs:11
table_rungsTileSite, profile, arms → GpuRungsThe optimization switches the site's table carries beyond the launch.crates/backends/llvm/src/place/launch.rs:129
warm_ofTileSite → which operands are already residentReads the residence facts to know operands kept from the previous call.crates/backends/llvm/src/place/site.rs:58
Emitter::declareMachine, Site, Schedule → DeclaredEach kernel family states its footprint and per-trip instruction counts.crates/backends/llvm/src/place/lowering.rs:6
grid_spread_pmblocks, SMs → per milleHow evenly a grid spreads across SMs.crates/backends/llvm/src/rules.rs:74
row_split_paysGpu, row bytes → boolSplit a long row fold across blocks.crates/backends/llvm/src/rules.rs:169
rungsGpu, warps per scheduler, Face → GpuRungsThe main rule chain: the chip's numbers plus the site's fill give the optimization switch values.crates/backends/llvm/src/rules.rs:342
split_rate_paysGpu, tile → boolDoes a split-precision matrix product beat the plain FMA tile at its achieved rate.crates/backends/llvm/src/rules.rs:229
stream_ld_paysGpu, bytes read once → boolMark a read-once operand as streaming so it does not push other data out of L2.crates/backends/llvm/src/rules.rs:485
streamk_epi_paysGpu, operand bytes → boolDoes stream-K with an epilogue pay.crates/backends/llvm/src/rules.rs:134
vec_cells_payGpu, grids → boolDo vector cells beat scalar ones given the DRAM share.crates/backends/llvm/src/rules.rs:91
wide_fma_paysGpu, blocks, wave → boolDoes the wider FMA tile win at this grid size.crates/backends/llvm/src/rules.rs:59
ws_persist_paysGpu, tiles, stages → boolDoes a persistent warp-specialized kernel pay.crates/backends/llvm/src/rules.rs:312
Lowering::slotsMachine, Site, op → Vec<Schedule>A lowering lists its tile schedules that fit the chip's capacities.crates/mapal-place/src/lower.rs:125
Lowering::declareMachine, Site, Schedule → Declared or RefusalChecks constraints and gives the counts.crates/mapal-place/src/lower.rs:125
Lowering::search_domain / pointprefix of coordinates → allowed values / ScheduleExposes the schedule space as coordinates for the branch and bound.crates/mapal-place/src/lower.rs:125
lru_bytestrace, keep → ReadsExact LRU misses over a trace.crates/mapal-place/src/lru.rs:188
traceGrid → access trace of slicesThe exact order slices are touched, for the simulator.crates/mapal-place/src/lru.rs:22
readsGrid, keep bytes → ReadsBytes a cache misses on a grid's traversal.crates/mapal-place/src/reuse.rs:101
Schedule::planSchedule → StringA short readable name of the placement.crates/mapal-place/src/schedule.rs:201
Schedule::tiles / panelsSchedule, Site → countsHow many output tiles and k panels a placement makes.crates/mapal-place/src/schedule.rs:193
opsMachine, Site → operations the site's formats admitStep 1 of the space: which instructions can run this site.crates/mapal-place/src/space.rs:18
traversalsSchedule, Declared → Vec<Traversal>Step 4: the traversals and their parameters over the slots a footprint allows.crates/mapal-place/src/space.rs:51
choice_lookuptable bytes, module text → key and stored pickHash the table and the module text; look it up in the wisdom file.crates/mapal-rt/gpu/mapal_choice.h:227
choice_sitetable, timing hooks → pick indexThe decision rule shared by device and emulator.crates/mapal-rt/gpu/mapal_choice.h:279
mapal_gpu_sitesite, table, pointers → one chosen launchRun a site: pick a candidate (forced, remembered, timed, or the compiler's first) and launch it.crates/mapal-rt/gpu/mapal_gpu_sites.inc:161
mapal_gpu_sitessite_reg table → registered tablesThe host hands its tables to the runtime before init.crates/mapal-rt/gpu/mapal_gpu_init.inc:33
sites_resolve / choice_presetsite_reg → decided pick, ready kernelsAt load, decide every pick that needs no run and prepare every candidate's kernel.crates/mapal-rt/gpu/mapal_gpu_init.inc:37
Transformations (19)
NameFrom → toKindWhat it doesDefined atLives in
Generate candidate schedulesMachine
Machine: Site
Machine: Lowering
→ Schedule: Schedule + Declared
functorFrom the machine's facts and the site, list operations, then tiles, then traversals, never from a fixed table.crates/mapal-place/src/space.rs:129compiler process heap, temporary Vec
Price a scheduleMachine
Machine: Site
Schedule
Machine: Declared
→ Schedule: Terms (nanoseconds
functorOne evaluator for every schedule: steady state of a trip, a wave's pipeline, the grid by traversal, plus fixed costs. Reads only measured or declared facts.
made of: A trip's steady state, Pipeline calculation, Count misses by distinct bytes, Zero pass, reduce, launches
crates/mapal-place/src/eval.rs:35compiler process, pure function
A trip's steady stateFlow: list
→ Machine: ns per trip
processThe slowest of compute, issue, scratchpad, and every mover; a mover with too little in flight is slowed by Little's law.crates/mapal-place/src/eval/terms.rs:92compiler process stack
Pipeline calculationMachine: trips
Machine: compute flows
Machine: mover flows
Machine: fill
Machine: serial
→ Machine: ns
processfill + trips x (slowest of compute and movement + barriers) + drain.crates/mapal-place/src/eval/terms.rs:102compiler process stack
Count misses by distinct bytesMachine: Grid
Machine: keep
→ Machine: Reads
functorClosed forms for lockstep waves, walks and staggered starts, counting distinct slices rather than bytes requested.crates/mapal-place/src/reuse.rs:101compiler process; memoized in thread-local hash maps
Zero pass, reduce, launchesSchedule
Machine
→ Machine: ns
processCosts outside the loop: zeroing the output, workspace reduce, launches.crates/mapal-place/src/eval.rs:55compiler process stack
Admissible floorMachine
Machine: Site
Schedule
→ Machine: Terms (lower bound)
functorThe same evaluation with every operand byte missed exactly once, cheap and never above the true price; used to cut the search.crates/mapal-place/src/eval.rs:51compiler process
Evaluate at every cornerMachine: Cand
→ Machine: Cand.corners
processPrices a candidate with each fact group at its slow or fast end, sixteen times.crates/mapal-place/src/search.rs:401compiler process heap
Tile boundMachine
Machine: Site
Machine: op
Machine: bm
Machine: bn
→ Machine: ns lower bound
processCheapest any schedule with this slot tile can be: peak compute and the panel stream.crates/mapal-place/src/search.rs:138compiler process stack
Point boundSchedule
Machine: Declared
→ Machine: ns lower bound
processCompute at the efficiency this footprint's occupancy reaches.crates/mapal-place/src/search.rs:192compiler process stack
Post-lowering gateMachine: Cand
→ Machine: ok or refusal
processChecks the candidate actually lowers to code (and, with an arm, assembles without spills); a refusal makes the next candidate be taken. The gate itself is a closure supplied by the backend.crates/mapal-place/src/search.rs:496closure called during search
Minimax verdictMachine: times per candidate at value
Machine: times at every corner
→ Machine: Verdict
processPicks the candidate whose worst regret over the corners is least; marks the pick open on a flip at a corner or a tie within the null.crates/mapal-place/src/search.rs:420compiler process stack
Translate the profileTarget: TargetProfile
→ Machine: Machine
functorExecutors, places, capacity groups, resources, pipes, operation rows, movers, dispatch and measured primitives built from the profile; each number keeps its provenance and every missing one is marked.crates/backends/llvm/src/place/machine.rs:7compiler process heap; cached per part in a thread-local MACHINES map
Place one siteFlow: TileSite
Target: TargetProfile
Machine: rules' Launch
→ Schedule: Placed
processTranslates the site, lists the emitters as lowerings, sets the rules' launch as incumbent, runs the search with the post-lowering gate, and records the pick and a ; mapal.place line. When the best does not clear the band, the rules' launch is kept; when no candidate passes, the rules' launch is used and the line says so.
made of: Translate the profile, Translate the site, Branch and bound search, Lower to check a candidate, Record the pick
crates/backends/llvm/src/place/search.rs:291compiler process; result memoized in thread-local PICKS
Translate the siteFlow: TileSite
→ Machine: Site
functorReads the dataflow facts into placement's site.crates/backends/llvm/src/place/site.rs:11compiler process stack
Lower to check a candidateSchedule
→ Machine: emitted device text or refusal
processTurns the schedule into a launch and lowers the kernel text under a forced launch; with the ptxas arm it also assembles it and rejects spills.crates/backends/llvm/src/place/search.rs:219compiler process; the ptxas arm writes temp files and runs llc and ptxas
Record the pickMachine: Placed
→ Code: ; mapal.place comment
processWrites the chosen plan, times at three bounds, counters and terms into the module text.crates/backends/llvm/src/place/search.rs:291a comment line inside the emitted device module
Placement at launch timeMachine: rules' Launch
Machine: order
→ Machine: Launch
processCalled when the emitter derives a launch; returns the pick when the machine-place switch is on, else the rules' launch. A second entry picks the pick whose combine matches the kernel being emitted.crates/backends/llvm/src/place/search.rs:435compiler process; called from func/gpu.rs launch_in and launch_for
Algorithms, data structures and design patterns (17)
NameKindWhat it isDefined atUsed by
Branch and boundalgorithmSearch with an admissible lower bound that prunes prefixes and points.crates/mapal-place/src/search.rs:496Branch and bound search
Minimax regret over intervalsalgorithmChoose the candidate whose largest regret at any corner of the fact intervals is smallest.crates/mapal-place/src/search.rs:420Minimax verdict
Exact LRU trace simulationalgorithmCounts misses of a line-granular LRU using a Fenwick tree over distinct bytes since last use.crates/mapal-place/src/lru.rs:188The closed form equals the LRU simulation
Fenwick treedata structureA binary indexed tree for prefix sums used by the LRU simulator.crates/mapal-place/src/lru.rs:162The closed form equals the LRU simulation
Three-gap progressionalgorithmThe gaps between readers of a row in a stream-K walk take at most three sizes; counted directly.crates/mapal-place/src/reuse/walk.rs:11Count misses by distinct bytes
Closed-form reuse by interval unionsalgorithmMisses by distinct bytes over waves and walk windows, linear instead of simulated.crates/mapal-place/src/reuse/cross.rs:118Count misses by distinct bytes
Memo caches in thread localsdesign patternPure functions of a grid are memoized in thread-local maps and cleared at a size cap.crates/mapal-place/src/reuse.rs:101Count misses by distinct bytes
Little's law flowalgorithmA mover's time is the larger of work over rate and latency times work over bytes in flight.crates/mapal-place/src/eval/terms.rs:52A trip's steady state
Facts with intervalsdesign patternEvery machine number has a low, value and high; evaluation at the ends makes uncertain picks visible.crates/mapal-place/src/fact.rs:64Evaluate at every corner, Minimax verdict
Lowering as a traitdesign patternThe backend supplies its kernels as a Lowering that declares constraints and counts; the search is generic over them.crates/mapal-place/src/lower.rs:125Generate candidate schedules, Branch and bound search
Incumbent with error banddesign patternThe rules' choice stays unless the model's pick beats it by more than the measured error band, so a re-measured rate does not churn emission.crates/mapal-place/src/search.rs:37Branch and bound search
Incumbent and candidatedesign patternThe rules' launch is always a point of the model's space, and wins unless beaten beyond the band.crates/backends/llvm/src/place/search.rs:252Place one site
Memo by search keydesign patternA search is cached by site, part, face, arms and order in a thread-local map; related per-site memos are cleared when a search ends.crates/backends/llvm/src/place/search.rs:252Place one site
Scoped guards (RAII)design patternWarmScope, ColScope and OrderScope set per-compile context and restore it when dropped.crates/backends/llvm/src/place/site.rs:97Placement at launch time
Forced launch for loweringdesign patternA thread-local FORCED launch replaces whatever the emitter would derive, so a candidate can be lowered and checked in isolation.crates/backends/llvm/src/place/search.rs:70Lower to check a candidate
Plan and replaydesign patternMeasured arms are stored as data and every change is re-scored against them.crates/backends/llvm/src/place_replay.tsv:1The pick agrees with the measured winner, The error band is the replay's residuals
Coordinate domainsdata structureA lowering's schedule space as a list of coordinates whose allowed values depend on earlier ones, so dominated choices are narrowed before the search.crates/backends/llvm/src/place/emitter.rs:76Branch and bound search

Guarantees of Machine model

Guarantee (natural transformation)What must agreeChecked in
Search equals exhaustiveFor every machine and site, branch and bound finds the same best time as pricing every candidate.crates/mapal-place/tests/search.rs:154
The closed form equals the LRU simulationFor lockstep grids the closed form equals the exact cache simulation byte for byte; for walks and staggers it is within a slice or five percent.crates/mapal-place/tests/props.rs:69
Time is monotone and above the boundA faster machine or a smaller site never raises the price, and the price is never below the admissible bound.crates/mapal-place/tests/props.rs:322
The pick does not depend on enumeration orderReversing every domain gives the same pick, and noise flips only picks marked open.crates/mapal-place/tests/search.rs:189
The pick agrees with the measured winnerFor every row of the replay corpus the model's pick is scored against the measured winner and the rules' pick; the count of agreements may not fall.crates/backends/llvm/src/place_replay.rs:455
The floor is admissible on every replay armFor every replayed arm, the cheap floor is never above the full price.crates/backends/llvm/src/place_replay.rs:261
The host launches the kernel the device module holdsThe host launches exactly the kernel the device module contains, including when the pick is kept.crates/backends/llvm/src/place/tests.rs:156
The error band is the replay's residualsThe error band written in the compiler equals the one recomputed from the replay data.crates/backends/llvm/src/place_replay.rs:682

LLVM backend

Turns the Flow graph and its facts into LLVM text for the CPU and, for GPU programs, a device module that becomes PTX.

Reads Flow, Facts, Schedule, Target → produces Code

Guarantees: A native run agrees with the interpreter, Emission is deterministic, Data movement equals what the facts require, The device agrees with the interpreter within the bound, A switch on and off compute the same values, A merged launch equals separate launches, Streamed attention agrees with the interpreter

Files (35)

crates/backends/llvm/src/lib.rs:1
crates/backends/llvm/src/module.rs:1
crates/backends/llvm/src/ty.rs:1
crates/backends/llvm/src/loops.rs:1
crates/backends/llvm/src/math.rs:1
crates/backends/llvm/src/narrow.rs:1
crates/backends/llvm/src/reuse.rs:1
crates/backends/llvm/src/func/mod.rs:1
crates/backends/llvm/src/func/drive.rs:1
crates/backends/llvm/src/func/ops.rs:1
crates/backends/llvm/src/func/core.rs:1
crates/backends/llvm/src/func/frame.rs:1
crates/backends/llvm/src/func/bulk.rs:1
crates/backends/llvm/src/func/tile.rs:1
crates/backends/llvm/src/func/trio.rs:1
crates/backends/llvm/src/func/vec.rs:1
crates/backends/llvm/src/func/packed.rs:1
crates/backends/llvm/src/func/window.rs:1
crates/backends/llvm/src/func/conv.rs:1
crates/backends/llvm/src/func/sme.rs:1
crates/backends/llvm/src/func/hostpar.rs:1
crates/backends/llvm/src/func/resident.rs:1
crates/backends/llvm/src/func/retain.rs:1
crates/backends/llvm/src/func/rowfold.rs:1
crates/backends/llvm/src/func/gpu.rs:1
crates/backends/llvm/src/profile.rs:1
crates/backends/llvm/src/func/flow.rs:1
crates/backends/llvm/src/func/stream.rs:1
crates/backends/llvm/src/func/horizontal.rs:1
crates/backends/llvm/src/func/calls.rs:1
crates/backends/llvm/src/func/zero.rs:1
crates/backends/llvm/src/rules.rs:1
crates/backends/llvm/src/flags.rs:1
crates/backends/llvm/src/place.rs:1
crates/backends/llvm/src/place_replay.rs:1

Category Code

Generated programs: LLVM text, device modules, PTX, object files and executables.

Objects (42)
ObjectWhat it isDefined atLives inProvided by
ArenaPlan / ArenaKeyOffset of each buffer in the function's one zone and its capacity.crates/backends/cuda/src/arena.rs:61compiler heap, a pure function of the graphCUDA backend
FnEmit (CUDA)Per-function host-side emission state.crates/backends/cuda/src/func.rs:69compiler heapCUDA backend
KernelSetKernels emitted for a function, deduplicated by structural shape.crates/backends/cuda/src/kernel/kernels.rs:98compiler heapCUDA backend
Qualifiers / FnQualHost, device or both for each function.crates/backends/cuda/src/kernel.rs:94compiler heapCUDA backend
SiteA launch-form bulk operation and its kernel name k<fn>_<site>.crates/backends/cuda/src/kernel/sites.rs:198compiler heapCUDA backend
TrapCapsWhich functions and launches can trap, so only they get a readback check.crates/backends/cuda/src/kernel.rs:262compiler heapCUDA backend
EmitError (CUDA)Unsupported feature with a SourceLoc, or internal.crates/backends/cuda/src/lib.rs:74compiler stackCUDA backend
CUDA translation unitThe .cu text; the String is the artifact.crates/backends/cuda/src/lib.rs:111compiler heap String; later a file on the GPU boxCUDA backend
EmitOpts (CUDA)Only a perf-timing switch.crates/backends/cuda/src/lib.rs:87compiler stackCUDA backend
ProdStructA struct generated for a product type.crates/backends/cuda/src/module.rs:302compiler heap; a struct definition in the .cuCUDA backend
@mapal_gsyncThe grid barrier used between levels of a persistent kernel.crates/backends/llvm/src/func/calls/kernel.rs:13device function in the device module; barrier counter in GPU global memory
UnitGenBuilder for the kernel text of a unit.crates/backends/llvm/src/func/flow.rs:443compiler heap, short-lived
UnitKernelKernel text of one unit plus the helper bodies it calls.crates/backends/llvm/src/func/flow.rs:383compiler heap
LoopBufHow a loop state's buffers are shared between trips: its own buffer, or a coloured set of spares.crates/backends/llvm/src/func/frame.rs:313compiler heap, decided before the walk
RootWhose bytes a view points at: an object, a loop-state position, or outside the function.crates/backends/llvm/src/func/frame.rs:337compiler heap, map keys
LoopA canonical loop of the function: its LoopPlan and the set of morphisms in its body.crates/backends/llvm/src/func/frame.rs:328compiler heap, Vec inside FnEmit
ParOrderFor the parallel entry: which task each morphism belongs to and which tasks come before which.crates/backends/llvm/src/func/frame.rs:346compiler heap
%mapal_site_regRegistry row of a table, handed to the runtime before init.crates/backends/llvm/src/func/gpu.rs:160private constant @mapal_sites in the host module
%mapal_candOne row of a site's candidate table: kernel id, reduce id, zero bytes, workspace, grid, block, smem.crates/backends/llvm/src/func/gpu/site_table.rs:8constant table in the host module; C twin read by the runtime
device module textThe nvptx64 LLVM unit: one kernel per live site, cell, generator, row fold, unit.crates/backends/llvm/src/func/gpu/device_text.rs:9compiler heap String; <exe>.dev.ll on disk
CellGeoGrid and shape of a one-thread-per-cell kernel.crates/backends/llvm/src/func/gpu/cell_kernels.rs:270compiler stack
EpiSite / EpiKernelA tile kernel with epilogue cells folded into it.crates/backends/llvm/src/func/gpu/epi_rowfold.rs:73compiler heap
Kernel text builderString builder for one kernel, separate from the host function around the site.crates/backends/llvm/src/func/gpu/kernel_geom.rs:580compiler heap, short-lived
HzSpecParsed merged-launch description read back from the host text.crates/backends/llvm/src/func/horizontal/device.rs:8compiler heap
FnAttrsPer function: is it clean (reads only, never traps or prints) and does it loop; decides readonly/nounwind/willreturn.crates/backends/llvm/src/func/mod.rs:40compiler heap: two SecondaryMaps keyed by FuncId
FnEmit (LLVM)All the state of emitting one function: slot name of each object, the alloca block, the body text, the facts it reads.crates/backends/llvm/src/func/mod.rs:254compiler heap, one per function, dropped after emit_ordered returns its text
HostEmitWhere the host waits for tasks: checkpoints, pinned tasks, waits that must fire before a loop.crates/backends/llvm/src/func/mod.rs:240compiler heap, inside FnEmit
TileCtxThe per-site numbers a CPU matrix tile is emitted with: tile sizes, packing, offsets.crates/backends/llvm/src/func/mod.rs:705compiler stack/heap while a site is emitted
EmitError (LLVM)Why an emission was refused: an unsupported feature at a source place, or an internal break.crates/backends/llvm/src/lib.rs:93compiler stack; carries a SourceLoc (Diagnostics)
OrderHow a tile's sum over k may be ordered: sequential, fixed split, or free.crates/backends/llvm/src/opts.rs:22compiler stack
; mapal.* comment linesEvidence lines in the module text (plan, host, ptx) read by the checker scripts.crates/backends/llvm/src/emit.rs:172comments inside .ll text
EmissionHost LLVM IR text, optional device LLVM IR, resolved profile name, fold orders.crates/backends/llvm/src/opts.rs:198compiler heap StringsCommand line
EmitOpts (LLVM)The knobs of one emission: target name, float face (contract, order), tiling, packing, timing, GPU arms.crates/backends/llvm/src/opts.rs:48compiler stack (Copy struct)
FoldOrderA split fold compiled in fixed order, kept so the interpreter can replay the same grouping.crates/backends/llvm/src/opts.rs:40compiler heap, Vec inside Emission
StrGlobalOne string literal turned into a private LLVM global with its byte length.crates/backends/llvm/src/module.rs:12compiler heap: SecondaryMap<ObjectId, StrGlobal>; at run time a constant in the module's read-only data
PtxThe PTX ISA version and SM a module declares and llc is told by -mattr.crates/backends/llvm/src/profile/caps.rs:80compiler stack; a ; mapal.ptx comment
ReuseHow a tile operand is reused across the i axis (new row each step, same row, shifting window).crates/backends/llvm/src/reuse.rs:27compiler stack
mapal_gpu.c / mapal_choice.h as embedded textThe C runtime and its header are embedded into the mapal binary and written next to each GPU build.crates/mapal-cli/src/main.rs:378include_str! in the mapal executable; written to <exe>.mapal_gpu.cRuntime
PTX fileThe device program made by opt and llc.crates/mapal-cli/src/main.rs:378disk <exe>.ptx; its path goes to the program in MAPAL_PTXCommand line
ExecutableThe linked native program.crates/mapal-cli/src/main.rs:378diskCommand line
libmapal_rt.aThe Rust runtime as a static library.crates/mapal-rt/Cargo.toml:1file in target/<profile>/ next to the mapal binaryRuntime
zero_ptxPTX text of the runtime's own zero-fill kernel.crates/mapal-rt/gpu/mapal_gpu_fills.inc:39a static string in the C runtime; loaded to the device at initRuntime
Arrows (17)
ArrowFrom → toWhat it doesDefined at
arena offsetArenaKey → byte offset256-byte aligned offset within the zone.crates/backends/cuda/src/arena.rs:70
collect_sitesFuncId → Vec<Site>Launch-form bulk operations in topological order.crates/backends/cuda/src/kernel/sites.rs:222
lower_tyTy (Types) → C++ type textMapal type to CUDA C++ type.crates/backends/cuda/src/ty.rs:42
kernel_nameu64 id → kernel symbolDeterministic kernel name.crates/backends/llvm/src/func/gpu/epi_rowfold.rs:84
site_registryhost text → @mapal_sites constantOne registry row per distinct table the host launches.crates/backends/llvm/src/func/gpu.rs:124
composemember kernel texts → merged kernel textJoins member kernels into one grid, each on its own block range.crates/backends/llvm/src/func/horizontal/device.rs:248
attrsFuncId (Flow) → clean / loopy flagsWhich functions may be marked readonly nounwind (willreturn when loop-free).crates/backends/llvm/src/func/mod.rs:46
slotObjectId (Flow) → LLVM alloca nameEach materialized object has one stack slot; erased objects (tokens, unit) have none.crates/backends/llvm/src/func/mod.rs:254
fnamesFuncId (Flow) → LLVM function nameThe entry becomes @mapal_main, every other function @fn<ordinal>, so output is deterministic.crates/backends/llvm/src/emit.rs:217
collect_str_globalsCategoryIr (Flow) → StrGlobal per string objectOne global per string literal object.crates/backends/llvm/src/module.rs:299
i_reuseTileSite, TileRead (Facts) → ReuseClassifies how an operand moves across tile rows.crates/backends/llvm/src/reuse.rs:53
mark / pack of capture pathsTy (Types) → array pointer pathsWhich arrays inside a function input arrive by address.crates/backends/llvm/src/ty.rs:67
lower_tyTy (Types) → LLVM type textA Mapal type becomes the LLVM type string of its slot.crates/backends/llvm/src/ty.rs:23
emitCategoryIr → EmissionCall the LLVM emitter; turn an Unsupported error into a source position message.crates/mapal-cli/src/main.rs:273
writetext → fileWrite a side file.crates/mapal-cli/src/main.rs:317
scan PTX for entriesPTX text → fn_entry tableFind every kernel name and resolve it once at load.crates/mapal-rt/gpu/mapal_gpu_modscan.inc:166
scan PTX for tensor-map recipesPTX text → tmap_e tableRead the copy recipes the compiler left in comments of the module.crates/mapal-rt/gpu/mapal_gpu_modscan.inc:68

Host code

Entry point and host function emission: loops, parallel tasks, CPU tiles.

Transformations (11)
NameFrom → toKindWhat it doesDefined atLives in
emit_detailedFlow: CategoryIr (Flow)
Code: EmitOpts
Target: TargetProfile (Target)
→ Code: Emission
processThe public entry: rebuilds facts under the fact arms asked for, resolves the profile, picks the face, then emits a host module (and a device module on GPU profiles).
made of: emit_module
crates/backends/llvm/src/emit.rs:21compiler process, pure over its inputs (profile is an explicit input)
emit_moduleFlow: CategoryIr (Flow)
→ Code: Emission.text (Code)
functorFlow to LLVM IR text: checks loops are canonical, emits every function, adds only the declarations the text uses, and ends with the main wrapper.
made of: FnEmit::emit_ordered, emit_loop
crates/backends/llvm/src/emit.rs:217compiler heap; output String
FnEmit::emit_orderedFlow: FuncDef (Flow)
→ Code: LLVM function text (Code)
functorOne function: allocate slots, walk morphisms in topological order, then return and free.
made of: emit_morphism
crates/backends/llvm/src/func/drive.rs:130compiler heap
emit_morphismFlow: Operation (Flow)
→ Code: LLVM instructions (Code)
functorThe operation table: each Flow operation becomes its instructions, applied one morphism at a time.crates/backends/llvm/src/func/ops.rs:15compiler heap
emit_loopFacts: LoopPlan (Facts)
→ Code: header / advance / exit blocks (Code)
functorA canonical loop becomes guard-first branches: decide cone, branch, advance cone, back edge.crates/backends/llvm/src/loops.rs:22compiler heap
emit_parallelFacts: PathPlan (Facts)
→ Code: task functions + mapal_par_* calls (Code)
processSplits independent paths into tasks launched on the mapal-rt pool and waits where the plan says.crates/backends/llvm/src/func/drive/parallel.rs:6emitted code runs on host threads; handle on host heap
emit_tiled_map (tile ladder)Facts: TileSite (Facts)
→ Code: CPU tile loop nest (Code)
functorPicks one CPU optimization switch for a matmul-like site: lanes, register block, packed panel, 1-D window, conv taps, or ARM SME.
made of: emit_tiled_map_blocked, emit_tiled_map_blocked_1d, emit_tiled_map_conv, emit_tiled_map_sme
crates/backends/llvm/src/func/tile.rs:36compiler heap
emit_tiled_map_blockedCode: TileSite
→ Code: register-blocked nest
functorRows blocked in registers so one b load serves several rows.crates/backends/llvm/src/func/tile.rs:402compiler heap
emit_tiled_map_blocked_1dCode: TileSite
→ Code: window nest
functorThe dual for 1-D windows such as FIR: blocks over lanes.crates/backends/llvm/src/func/window.rs:18compiler heap
emit_tiled_map_convCode: TileSite
→ Code: unrolled tap nest
functorConv micro-kernel with the k split constant-folded.crates/backends/llvm/src/func/conv.rs:16compiler heap
emit_tiled_map_smeCode: TileSite
→ Code: SME streaming-mode tile
functorARM streaming matrix unit realization of a tile.crates/backends/llvm/src/func/sme.rs:155compiler heap
Algorithms, data structures and design patterns (8)
NameKindWhat it isDefined atUsed by
Slot per object, mem2reg left to LLVMdesign patternEvery value gets a stack cell written once; LLVM turns them into registers.crates/backends/llvm/src/func/mod.rs:254FnEmit::emit_ordered, emit_morphism
Guard-first loop CFGdesign patternThe loop header decides first, so the exit trip still runs the decide cone.crates/backends/llvm/src/loops.rs:22emit_loop
Fixpoint over the call graph (attribute capability)algorithmA function is clean only if every callee is clean; loops block willreturn.crates/backends/llvm/src/func/mod.rs:46FnEmit::emit_ordered
Arena of typed ids (SecondaryMap)data structurePer-object and per-morphism side tables keyed by slotmap ids.crates/backends/llvm/src/func/mod.rs:254emit_module, FnEmit::emit_ordered
Declare only what is useddesign patternRuntime declarations are added by searching the emitted text for the call.crates/backends/llvm/src/emit.rs:217emit_module
Strategy ladder with a predicate per optimization switchdesign patternEach CPU tile optimization switch has one test (packing_site, window1d_site, conv_site, sme_tile_site) and one emitter.crates/backends/llvm/src/func/mod.rs:526emit_tiled_map (tile ladder)
Loop buffer colouringalgorithmNext-state bytes take a spare buffer not read while they are written.crates/backends/llvm/src/func/frame/loop_buffers.rs:52emit_loop
Text builder as the artifactdesign patternThe String is the translation unit; no intermediate LLVM object model.crates/backends/llvm/src/opts.rs:198emit_module

GPU memory residency

Which values live on the device, when they are copied or freed, and how device buffers share memory.

Transformations (9)
NameFrom → toKindWhat it doesDefined atLives in
resident_planFacts: tile_plan, last_use_plan, path_plan, loop_plan, unchanged_plan, access_plan (Facts
→ Schedule: ResidentPlan (Schedule)
functorReads the graph facts and decides placement for every object; no data is moved that the facts do not require.
made of: placement, chains, arena
crates/backends/llvm/src/func/resident/plan.rs:7compiler heap
placementFacts: TileSite set (Facts)
→ Code: device / host choice per site
functorPer tile site: device or host, by the cost rules and the machine facts.crates/backends/llvm/src/func/gpu/placement.rs:69compiler heap
chainsFacts: access_plan edges (Facts)
→ Code: stream per site, uploads per chain
functorIndependent sites go on different streams; uploads ride the chain that reads them.crates/backends/llvm/src/func/resident/plan.rs:405compiler heap
arenaFacts: last_use_plan births and deaths (Facts)
→ Code: Arena offsets
functorLifetime colouring packs buffers into one slab.crates/backends/llvm/src/func/resident/arena.rs:52compiler heap
color / color_byCode: (birth, death, bytes) intervals
→ Code: offsets, total bytes
processFirst-fit interval colouring.crates/backends/llvm/src/func/resident.rs:486compiler stack
emit_site_residentCode: DevSite, ResidentPlan
→ Code: host calls: alloc, h2d, launch, d2h (Code)
processEmits the host-side calls that run one device site.crates/backends/llvm/src/func/resident/emit_site.rs:259emitted code runs on host; effects on GPU
row folds on deviceFacts: RowFoldSite (Facts)
→ Code: device row-fold launch
functorA row fold over a device output runs on the device, one thread per row, so the output never crosses the bus whole.crates/backends/llvm/src/func/rowfold.rs:1compiler heap
retained_sitesFacts: Delta (Facts)
→ Code: Retained
functorInside a loop recompute only the rows the previous trip wrote.crates/backends/llvm/src/func/retain.rs:48compiler heap
host-parCode: split bulk sites on a GPU build
→ Code: pool tasks
functorHost-placed bulk work in a GPU build runs on the CPU task pool.crates/backends/llvm/src/func/hostpar.rs:1host threads
Algorithms, data structures and design patterns (4)
NameKindWhat it isDefined atUsed by
Plan then replaydesign patternA pure plan record is computed first; emission only reads it.crates/backends/llvm/src/func/resident.rs:377resident_plan, emit_site_resident
First-fit interval colouringalgorithmBuffers with disjoint lifetimes share bytes.crates/backends/llvm/src/func/resident.rs:486color / color_by, arena
Delta transferdesign patternOnly the rows a trip wrote are uploaded or recomputed.crates/backends/llvm/src/func/resident.rs:121retained_sites
Lazy allocation through a slotdesign patternThe runtime fills the slot on first use, so the host emits no branch.crates/mapal-rt/gpu/mapal_gpu_memory.inc:46emit_site_resident

GPU kernels

Kernels, the device module, and the table of candidate kernels a program picks from when it loads.

Transformations (9)
NameFrom → toKindWhat it doesDefined atLives in
launch_inFacts: TileSite (Facts)
Target: TargetProfile (Target)
→ Schedule: Launch (Schedule)
functorChooses a kernel and its grid from the site and the hardware properties.crates/backends/llvm/src/func/gpu/launch_lines.rs:338compiler heap
site_candsCode: TileSite
Code: Launch
→ Code: Vec<SiteCand>
functorA table of candidate launches, the rules' choice first.crates/backends/llvm/src/func/gpu/site_table.rs:105compiler heap
device_moduleCode: Launch, cells, gens, epis, units, rowfolds
→ Code: device module text (Code)
functorCollects every live kernel and writes the nvptx module.
made of: lowered_text / Kernel
crates/backends/llvm/src/func/gpu/device_text.rs:9compiler heap
lowered_text / KernelCode: Launch + TileSite
→ Code: kernel LLVM text
functorWrites one tile kernel: panel loops, FMA or matrix instructions, epilogue.crates/backends/llvm/src/func/gpu/kernel_geom.rs:539compiler heap
cell_kernel_textSchedule: Cell (Schedule)
→ Code: cell kernel text
functorOne thread per output cell, the host's own body text.crates/backends/llvm/src/func/gpu/cell_kernels.rs:90compiler heap
site_callCode: SiteTable
→ Code: call @mapal_gpu_site
processEmits the host call with the table constant.crates/backends/llvm/src/func/gpu/emit_site.rs:10emitted host code
init_callCode: host rungs
→ Code: call @mapal_gpu_init(flags)
processFirst call of main: hands the runtime its flags after registering site tables.crates/backends/llvm/src/func/gpu.rs:97emitted host code
opt then llcCode: device module text
→ Code: PTX file
processopt -O3 then llc for the profile's arch, with the declared PTX attribute.crates/mapal-cli/src/main.rs:378external tools; files <exe>.dev.ll, .dev.opt.ll, .ptx
load-time dispatchCode: @mapal_sites
Code: PTX
→ Code: picked candidate per site
processAt module load the runtime resolves each table to one candidate from shared-memory limits and occupancy.crates/mapal-rt/gpu/mapal_gpu_init.inc:33host heap in the runtime
Algorithms, data structures and design patterns (5)
NameKindWhat it isDefined atUsed by
Candidate table, chosen at loaddesign patternCompile time lists launches; the runtime picks one from device limits.crates/backends/llvm/src/func/gpu/site_table.rs:28site_cands, site_call, load-time dispatch
Content-hashed kernel idsalgorithmFNV hash of body and profile names a kernel so equal kernels merge.crates/backends/llvm/src/func/gpu/site_table.rs:256device_module
Rule table over hardware propertiesdesign patternChoices read geometry (SMs, registers, L2, bandwidth), never a part name.crates/backends/llvm/src/rules.rs:342launch_in
Stream-K / split-KalgorithmCut the k fold across blocks, add partials atomically or via workspace.crates/backends/llvm/src/func/gpu/launch_rules.rs:89launch_in, lowered_text / Kernel
Software-pipelined panelsalgorithmNext panel loads while this one computes (cp.async, TMA).crates/backends/llvm/src/func/gpu/kernel_geom.rs:580lowered_text / Kernel

Merged launches

Row-block units, one-pass streaming, merged launches and zero-fill folding.

Transformations (9)
NameFrom → toKindWhat it doesDefined atLives in
unit_of (flow)Facts: UnitGroup, footprint_plan, Reach (Facts)
→ Schedule: Unit (Schedule)
functorA consumer joins its producer's group when everything it reads from the producer lies in the same work unit, or is a halo the group recomputes.crates/backends/llvm/src/func/flow/units.rs:289compiler heap
block_choice / geoCode: Unit
Code: TargetProfile
→ Code: Block, Geo
functorRows per block and the resource budget from registers, shared memory and the roofline of fused versus separate launches.crates/backends/llvm/src/func/flow/slices.rs:329compiler heap
unit_kernelCode: Unit
→ Code: UnitKernel (Code)
functorOne kernel for the group: members in order as phases, values kept in registers or shared memory unless a reader outside needs them.crates/backends/llvm/src/func/flow/unit_kernel.rs:8compiler heap
stream_geoFacts: StreamGroup (Facts)
→ Code: Stream, Geo
functorWalks one axis in windows with running max and sum so axis-wide values are never stored.crates/backends/llvm/src/func/stream.rs:429compiler heap
mma_fmtCode: Unit members, roles, Gpu
→ Code: matrix format or none
functorWhether every product in the stream fits one warp matrix instruction.crates/backends/llvm/src/func/stream.rs:97compiler stack
side_by_sideCode: Vec<Shape>
Code: Gpu
→ Code: merged blocks or Refuse
functorWhether launches with no hazard between them fit one grid at no loss in waves.crates/backends/llvm/src/func/horizontal.rs:150compiler stack
hz_launchCode: HzGroup
→ Code: one merged launch call
processCaptures each member's launch and issues the group after its last member.crates/backends/llvm/src/func/horizontal/emit.rs:396emitted host code
persistent_fit / chain_nsCode: levels of Shapes
Code: Gpu
→ Code: grid size or Refuse; time
functorA chain is one co-resident kernel when it fits and beats separate launches.crates/backends/llvm/src/func/calls.rs:80compiler stack
zero-fold / zero-hoistFacts: access_plan hazards (Facts)
Code: atomic sites
→ Code: zero_by, zero_after
functorA zero pass becomes extra stores in an earlier kernel, or is issued after the earliest step that allows it.crates/backends/llvm/src/func/zero.rs:645compiler heap
Algorithms, data structures and design patterns (6)
NameKindWhat it isDefined atUsed by
Footprint rule (producer cells read lie inside the unit)design patternGroup membership is decided only by what each work unit reads, not by an operator name.crates/backends/llvm/src/func/flow/units.rs:289unit_of (flow)
Online softmax / running rescalealgorithmA running maximum and sum are rescaled as windows arrive.crates/backends/llvm/src/func/stream.rs:52stream_geo
Tree and warp-shuffle reductionalgorithmRow totals by tree in shared memory or by shuffles.crates/backends/llvm/src/func/flow/gen_slices.rs:322unit_kernel
Hazard graph (RAW/WAR/WAW) as the merge testdesign patternLaunches merge only if the access plan leaves them unordered.crates/backends/llvm/src/func/horizontal.rs:150side_by_side, persistent_fit / chain_ns
Grid barrieralgorithmA level barrier inside a persistent kernel.crates/backends/llvm/src/func/calls/kernel.rs:13persistent_fit / chain_ns
Ticket (last block combines)algorithmThe last block to finish a row combines partial states.crates/backends/llvm/src/func/gpu/k_streamk.rs:326stream_geo

Switches and placement

How the rules' switches and the machine-model search reach the emitter.

Transformations (5)
NameFrom → toKindWhat it doesDefined atLives in
rules::optimization switchesTarget: Gpu (Target)
Code: Face
→ Code: GpuRungs
functorEach optimization switch decides from properties such as FFMA per DRAM byte, registers per thread, L2 per SM.crates/backends/llvm/src/rules.rs:342compiler stack
arms applied over rulesCode: GpuRungs
Code: GpuArms
→ Code: effective GpuRungs
processon forces, off removes; default arms are empty.crates/backends/llvm/src/func/gpu.rs:275compiler stack
placed (machine-place search)Code: TileSite
Machine
→ Code: Placed
functorA cost model over candidate lowerings picks a launch; a pick that does not clear the band keeps the rules' launch. Off by default.
made of: machine_of
crates/backends/llvm/src/place/search.rs:435compiler heap; thread-local memo
machine_ofTarget: TargetProfile (Target)
→ Machine
functorProfile facts become machine facts with source and spread.crates/backends/llvm/src/place/machine.rs:7compiler heap, cached per profile
profile::resolveCode: name
→ Code: TargetProfile
processDetects the host (sysfs, sysctl) or device (driver query plus calibration) and returns a static profile.crates/backends/llvm/src/profile/registry.rs:111process static
Algorithms, data structures and design patterns (5)
NameKindWhat it isDefined atUsed by
Plan + replaydesign patternRules are checked by replaying every cited measurement.crates/backends/llvm/src/rules/tests.rs:124The rules agree with every cited measurement
ON/OFF measurement armsdesign patternEvery optimization switch has an off arm for A/B; defaults come from rules, not flags.crates/backends/llvm/src/gpu_arms.rs:544arms applied over rules
Roofline costalgorithmTime is the larger of flops over rate and bytes over bandwidth.crates/backends/llvm/src/profile/tiles.rs:550placed (machine-place search), rules::optimization switches
Candidate search with admissible flooralgorithmThe search prunes candidates whose lower bound cannot beat the best.crates/backends/llvm/src/place/search.rs:252placed (machine-place search)
Memoization by key (thread-local)data structureSearches and machines are cached per key inside one emission.crates/backends/llvm/src/place/search.rs:96placed (machine-place search)

Guarantees of LLVM backend

Guarantee (natural transformation)What must agreeChecked in
A native run agrees with the interpreterCompile and run gives the interpreter's output and exit status, at -O0 and -O2, on raw and rewritten graphs.crates/backends/llvm/tests/differential/basics.rs:10
crates/backends/llvm/tests/differential/basics.rs:29
Emission is deterministicThe same graph and options always give the same text; stored snapshots pin it.crates/backends/llvm/tests/golden_ll/basics.rs:6
crates/backends/llvm/tests/golden_ll/basics.rs:19
Data movement equals what the facts requireThe copies and allocations emitted are exactly those the dataflow facts need.crates/backends/llvm/tests/resident.rs:206
crates/backends/llvm/tests/resident.rs:239
The device agrees with the interpreter within the boundGPU results equal the interpreter's inside the stated error bound.crates/backends/llvm/tests/large_gemm.rs:253
crates/backends/llvm/tests/site_choice/choice.rs:12
A switch on and off compute the same valuesEach switch only moves operands; turning it off changes speed, not values.crates/backends/llvm/tests/site_choice/choice.rs:12
crates/backends/llvm/tests/site_choice/choice.rs:137
A merged launch equals separate launchesA merged group gives the same values as its members launched alone.crates/backends/llvm/tests/horizontal.rs:215
crates/backends/llvm/tests/horizontal.rs:342
Streamed attention agrees with the interpreterThe one-pass attention kernel matches the interpreter within the bound.crates/backends/llvm/tests/flash_attention/stream_facts.rs:89
crates/backends/llvm/tests/flash_attention/generated.rs:434

CUDA backend

A second backend that writes CUDA C for the same graph, used as a differential check against the main backend.

Reads Flow, Facts → produces Code

Guarantees: A CUDA run agrees with the interpreter, CUDA emission is deterministic

Files (7)

crates/backends/cuda/src/lib.rs:1
crates/backends/cuda/src/func.rs:1
crates/backends/cuda/src/kernel.rs:1
crates/backends/cuda/src/loops.rs:1
crates/backends/cuda/src/arena.rs:1
crates/backends/cuda/src/module.rs:1
crates/backends/cuda/src/ty.rs:1

Transformations (5)
NameFrom → toKindWhat it doesDefined atLives in
emit_with_optsFlow: CategoryIr (Flow)
→ Code: CUDA translation unit (Code)
functorFlow to .cu text, deterministic, with only the non-canonical loop shape unsupported.
made of: emit_kernel_set, emit_loop, arena_plan
crates/backends/cuda/src/lib.rs:111compiler heap
emit_kernel_setCode: Site
→ Code: __global__ kernel + host launch
functorOne kernel per structural shape; each site launches it.crates/backends/cuda/src/kernel/kernels.rs:111compiler heap
emit_loopCode: LoopPlan
→ Code: host guard-first loop
functorDecide, guard, advance, back edge; in-place updates where the last-use plan allows.crates/backends/cuda/src/loops.rs:61compiler heap
arena_planCode: CategoryIr
Code: FuncId
→ Code: ArenaPlan
functorGive every non-loop buffer the next aligned offset.crates/backends/cuda/src/arena.rs:99compiler heap
nvcc compile and runCode: .cu text
→ Code: executable and output
processBuilt on a GPU box and linked with mapal-rt.crates/backends/cuda/tests/differential/harness.rs:74external nvcc; files on the box
Algorithms, data structures and design patterns (4)
NameKindWhat it isDefined atUsed by
Shape-deduplicated kernelsdesign patternOne definition per structural shape, launched from many sites.crates/backends/cuda/src/kernel/kernels.rs:111emit_kernel_set
Capability fixpoint (TrapCaps)algorithmA launch may trap if any reachable callee may.crates/backends/cuda/src/kernel.rs:262emit_kernel_set
Fn-scope arena zonedesign patternOne allocation and one release per function, escape-checked.crates/backends/cuda/src/arena.rs:99arena_plan
Host-driven loopdesign patternThe loop runs on the host; each trip launches kernels.crates/backends/cuda/src/loops.rs:61emit_loop

Guarantees of CUDA backend

Guarantee (natural transformation)What must agreeChecked in
A CUDA run agrees with the interpreterOutputs and traps equal the interpreter's.crates/backends/cuda/tests/differential/basics.rs:11
crates/backends/cuda/tests/differential/basics.rs:168
CUDA emission is deterministicStored .cu snapshots pin the text.crates/backends/cuda/tests/golden_cu/basics.rs:6
crates/backends/cuda/tests/golden_cu/basics.rs:27

Verilog backend

Not built yet: the crate is a one-line placeholder.

Not built yet. The crate is a one-line placeholder: crates/backends/verilog/src/lib.rs:1

Runtime

The code a compiled program links against: host memory, parallel tasks, printing and traps, and the GPU driver glue (with a CPU emulator of the device).

Reads Code, Schedule → produces Run

Guarantees: Emulator agrees with the device, Print agrees with the interpreter

Files (5)

crates/mapal-rt/src/lib.rs:1
crates/mapal-rt/gpu/mapal_gpu.c:1
crates/mapal-rt/gpu/mapal_choice.h:1
crates/mapal-rt/gpu/mapal_gpu_emu.c:1
crates/mapal-rt/tests/read.rs:1

Category Run

A running program: host memory, tasks, device memory, output and exit code.

Objects (32)
ObjectWhat it isDefined atLives inProvided by
arena zoneOne cudaMalloc per function covering non-loop buffers, released at function exit unless an escape points into it.crates/backends/cuda/src/arena.rs:99GPU global memoryCUDA backend
device twin__device__ copy of a token-free function used inside kernels.crates/backends/cuda/src/kernel.rs:461GPU code; per-thread locals in registers or local memoryCUDA backend
loop bufferA per-buffer cudaMalloc inside loop cones; carried arrays swap pointers at the back edge.crates/backends/cuda/src/loops.rs:61GPU global memoryCUDA backend
packed panelA right-hand matrix repacked tile by tile for the CPU matmul loop.crates/backends/llvm/src/func/core/packs.rs:8host heap/stack scratch, 64-byte alignedLLVM backend
heap array bufferBytes of an array result, allocated and freed at last use.crates/backends/llvm/src/func/core/ptrs.rs:367host heap via mapal-rt @mapal_rt_allocLLVM backend
per-object slotThe stack cell of one value, written once by its producing operation.crates/backends/llvm/src/func/frame.rs:197host stack (alloca in the entry block); registers after LLVM mem2regLLVM backend
tile registers / shared memoryAccumulators sit in registers; panels staged in shared memory (cp.async or TMA).crates/backends/llvm/src/func/gpu/kernel_geom.rs:580GPU registers and shared memoryLLVM backend
%FrameThe struct holding every object's value of one function call.crates/backends/llvm/src/func/mod.rs:196host stack frame, or the mapal-rt frame arena when too large (@mapal_rt_frame_alloc)LLVM backend
device arena slabThe function's one cuMemAlloc, aligned to 256 bytes.crates/backends/llvm/src/func/resident.rs:461GPU global memoryLLVM backend
task pool runThe handle of one parallel run of split tasks.crates/backends/llvm/src/module.rs:284host heap inside mapal-rt (FlowParRun)LLVM backend
DeviceSlot (uint64_t* slot)A u64 device address in a frame slot, filled lazily by mapal_gpu_alloc / mapal_gpu_arena.crates/mapal-rt/gpu/mapal_gpu_memory.inc:35a host stack or frame slot owned by the emitted code; the bytes are in GPU global memoryLLVM backend
stream chainA CUDA stream a chain of dependent sites runs on.crates/mapal-rt/gpu/mapal_gpu_memory.inc:183CUDA driver stateLLVM backend
PinnedRangeA host array locked in memory so uploads can be asynchronous.crates/mapal-rt/gpu/mapal_gpu_transfer.inc:5host memory registered with the driver; a static array of (pointer, bytes)
mapal_gpu_siteThe call that launches a site: picks among the candidates at load time and then runs the pick.crates/mapal-rt/gpu/mapal_gpu_sites.inc:161host code; kernels in GPU code memoryLLVM backend
module trap wordA device cell records a trap here; the next host checkpoint reads it.crates/mapal-rt/gpu/mapal_gpu_gen.inc:100GPU global memoryLLVM backend
Module and fn_entryThe loaded PTX module and a table from kernel name to function handle, built by scanning the PTX text for entries.crates/mapal-rt/gpu/mapal_gpu_modscan.inc:166GPU module in the driver; table is a malloc'd array on the host
Stream slots and eventsEight non-blocking chains plus the default stream, each joined to program order by an event.crates/mapal-rt/gpu/mapal_gpu_fills.inc:5CUDA driver objects; the counters are static C arrays
mapal_dev_trap wordA 64-bit global in the device module where a kernel records a trap (all ones means none).crates/mapal-rt/gpu/mapal_gpu_gen.inc:109GPU global memory inside the module
Trace totalsCounters of time and bytes per phase, printed at exit under MAPAL_GPU_TRACE.crates/mapal-rt/gpu/mapal_gpu.c:1a static struct in the host process
Arena (device)One big device allocation that many buffers share, released as a whole.crates/mapal-rt/gpu/mapal_gpu_memory.inc:42GPU global memory; the table of arenas is a malloc'd array on the host
tmap_e (tensor-map recipe)How to build a copy descriptor for a kernel that uses bulk tile copies, read from the module text.crates/mapal-rt/gpu/mapal_gpu_launch.inc:23host heap; encoded descriptors are passed as kernel arguments
TaskStateWaiting, Running or Done.crates/mapal-rt/src/sched.rs:39one atomic byte per task
FrameSlot (FRAME)Scratch memory of one function call, released when the call returns.crates/mapal-rt/src/mem.rs:149host heap; per-thread Vec of (address, layout) in a thread_local
TrapA language error (divide by zero, index out of range): a code 0 or 1 that ends the process with exit 101.crates/mapal-rt/src/lib.rs:98a u32 argument; in a parallel run the first one is kept in Run.trap (an atomic u64)
ArenaBlock (ARENA)One heap block handed out by mapal_rt_alloc; all blocks are released together at the end.crates/mapal-rt/src/mem.rs:55host heap; the list of (address, layout) is a Vec behind one global mutex
ReadFailureA failed file read: a message and a position in the program order; exit code 103.crates/mapal-rt/src/read.rs:100host heap, a Mutex<Vec<(i64, String)>>
FlowParRunThe opaque handle the emitted code holds for a Run.crates/mapal-rt/src/sched.rs:113host heap; the pointer sits in an emitted stack slot
PoolThe worker threads, one queue and one parking spot per lane.crates/mapal-rt/src/sched.rs:145process-wide (global_pool); queues are Mutex<VecDeque<Work>>
RunOne parallel region: its tasks, the frame pointer they share, the first trap, and a wake-up signal.crates/mapal-rt/src/sched.rs:90host heap behind an Arc
TaskDefWhat one parallel task is: its kernel function, element count, rank, slice size, width.crates/mapal-rt/src/sched.rs:14host heap, filled by the emitted program's mapal_par_task calls
TaskBuild / TaskRtA task while the graph is being built (definition, dependents, count of unmet dependencies), and after it is sealed (atomic counters).crates/mapal-rt/src/sched.rs:79host heap: Mutex<Vec<TaskBuild>> turned into a Box<[TaskRt]> by seal
Work (slice)A range [lo, hi) of one task, queued for a worker.crates/mapal-rt/src/sched.rs:117host heap, inside a per-lane VecDeque
Arrows (28)
ArrowFrom → toWhat it doesDefined at
trap check after launchlaunch that can trap → readback and mapal_trapOnly launches that can trap read back.crates/backends/cuda/src/kernel.rs:262
Index with guardIndex morphism → bounds branch + trap or bare loadA proven in-bounds index drops its trap check.crates/backends/llvm/src/func/ops/index.rs:6
Operation to instructionsMorphismId (Flow) → LLVM instructions over slotsEach morphism loads its input slots, computes, and stores its output slot.crates/backends/llvm/src/func/ops.rs:36
resident_afterMorphismId → frees and copy-outsAfter each morphism, free what died and copy out what the host reads.crates/backends/llvm/src/func/resident/emit_site.rs:8
resident_insteadMorphismId → device alloc + launch instead of host opA producer placed on the device is replaced by its device call.crates/backends/llvm/src/func/resident/arena.rs:376
mapal_gpu_init / load_moduleflags, MAPAL_PTX file → Module, contextStart the driver on a helper thread and load the kernels; waits for it at the first use.crates/mapal-rt/gpu/mapal_gpu_init.inc:158
mapal_gpu_alloc / mapal_gpu_arenaDeviceSlot, bytes → device addressAllocate a buffer, or carve the shared arena.crates/mapal-rt/gpu/mapal_gpu_memory.inc:46
mapal_gpu_d2h / d2h_ondevice bytes → host bytesCopy back; also a checkpoint that reads the device trap word.crates/mapal-rt/gpu/mapal_gpu_memory.inc:152
mapal_gpu_eventtwo stream slots → orderingMake one stream wait for work on another.crates/mapal-rt/gpu/mapal_gpu_memory.inc:183
mapal_gpu_freeDeviceSlot → nothingRelease the buffer (members of an arena are only emptied).crates/mapal-rt/gpu/mapal_gpu_gen.inc:33
mapal_gpu_genkernel id, count → device arrayCompute a producer array on the device.crates/mapal-rt/gpu/mapal_gpu_gen.inc:9
mapal_gpu_h2d / h2d_async / h2d_onhost bytes → device bytesCopy to the device, optionally without waiting, optionally on a chosen stream.crates/mapal-rt/gpu/mapal_gpu_memory.inc:75
mapal_gpu_launch / launchv / launch_coop / launch_l2kernel id, pointers, grid → queued kernel runFind the kernel by its 64-bit id and enqueue it (plain, with many pointers, cooperative, or with a cache hint).crates/mapal-rt/gpu/mapal_gpu_launch.inc:362
mapal_gpu_launchvid, stream, pointers, grid → kernel launchLaunch over any number of device pointers.crates/mapal-rt/gpu/mapal_gpu_launch.inc:362
mapal_gpu_syncstreams → idle deviceWait for all device work.crates/mapal-rt/gpu/mapal_gpu_gen.inc:119
mapal_gpu_trap_arm / trap_poll / trap_worddevice trap word → host trapAfter a launch, arm a check that reads the device trap word at the next print, clock read, copy-back or exit and raises it as an ordinary trap.crates/mapal-rt/gpu/mapal_gpu_gen.inc:100
mapal_gpu_zero / zero_fordevice bytes → zeroed bytesZero a buffer with the runtime's own tiny kernel, unless the site's chosen variant needs none.crates/mapal-rt/gpu/mapal_gpu_memory.inc:134
mapal_print_str / emitvalue → stdout textPrint a value with the same formatter the interpreter uses, and flush.crates/mapal-rt/src/lib.rs:53
mapal_par_begintask count → FlowParRunOpen a parallel region.crates/mapal-rt/src/par.rs:46
mapal_par_deptwo task indexes → dependency edgeSay that one task must finish before another starts.crates/mapal-rt/src/par.rs:98
mapal_par_launch / pin / wait / finishFlowParRun → FlowParRunStart the region, keep a task on the calling thread, wait for chosen tasks, wait for all and close.crates/mapal-rt/src/par.rs:118
mapal_par_taskFlowParRun, TaskDef → FlowParRunAdd a task to the region.crates/mapal-rt/src/par.rs:60
mapal_par_trap / mapal_par_checkTrap → Run.trapRecord a trap raised inside a task; raise it at the right point of the program order.crates/mapal-rt/src/par.rs:210
mapal_read / mapal_read_taskpath, bytes → array bytesRead a data file into an array, relative to the recorded source directory (or MAPAL_DATA_DIR).crates/mapal-rt/src/read.rs:66
mapal_rt_allocsize and alignment → ArenaBlockGet a block that lives until the program ends.crates/mapal-rt/src/mem.rs:65
mapal_rt_frame_mark / alloc / releaseFrameSlot stack → FrameSlot stackRemember the stack height, push a block, pop back to the remembered height.crates/mapal-rt/src/mem.rs:141
mapal_rt_free_allall ArenaBlocks → nothingRelease every block.crates/mapal-rt/src/mem.rs:124
mapal_time_ms / mapal_perf_begin / mapal_perf_endnothing → millisecondsThe clock the program can read and the optional timing window.crates/mapal-rt/src/mem.rs:34
Transformations (14)
NameFrom → toKindWhat it doesDefined atLives in
Run a parallel regionRun: TaskDef
Run: FlowParRun
→ Run: Run
Run: Trap
processThe emitted program builds a task graph with begin, task and dep calls; launch seals it and queues slices; workers run them; wait and finish join. Any trap inside a task is reported in program order.
made of: Build the graph, Seal, Slice and queue, Worker loop, Wait and finish
crates/mapal-rt/src/par.rs:118host threads of the global Pool; frame shared through Run.frame
Build the graphRun: TaskDef
→ Run: TaskBuild
processCollect tasks and edges while the program issues them.crates/mapal-rt/src/par.rs:60
SealRun: TaskBuild
→ Run: TaskRt
processTurn the mutable build list into immutable tasks with atomic counters.crates/mapal-rt/src/run.rs:39
Slice and queueRun: TaskRt
→ Run: Work
processCut each ready task into slices (size from the grain, the pool width and MAPAL_SLICE) and put them on lane queues.crates/mapal-rt/src/run.rs:119slice_ranges decides the cuts
Worker loopRun: Work
→ Run: TaskState
processEach worker takes from its own queue, steals from others, runs the slice, and when a task's last slice finishes releases its dependents.crates/mapal-rt/src/pool.rs:136
Wait and finishRun: TaskState
→ Run: FlowParRun
processThe caller helps run work until its tasks are done, then checks for a trap.crates/mapal-rt/src/run.rs:297
Allocate host memoryRun: size
→ Run: ArenaBlock
Run: FrameSlot
processWhole-program blocks come from a global list freed at the end; per-call blocks come from a per-thread stack released on return.crates/mapal-rt/src/mem.rs:65
Print and trapRun: value
→ Run: stdout
Run: exit code
processA print writes the shortest round-trip text and flushes. A trap prints 'mapal trap: div_zero|index_oob' and exits 101.crates/mapal-rt/src/lib.rs:98
Load the device moduleCode: PTX file (MAPAL_PTX
Schedule: mapal_site_reg
→ Run: Module
Schedule: choice_memo
processOn a helper thread: start the driver, make the context, load the PTX, resolve all kernels and the site tables. The first site call joins it.crates/mapal-rt/gpu/mapal_gpu_init.inc:56helper pthread then host heap and the GPU context
Move bytesRun: host bytes
Run: DeviceSlot
→ Run: device bytes
processAllocate, upload, download and free by the emitted program's explicit calls; the runtime adds no copy of its own.crates/mapal-rt/gpu/mapal_gpu_memory.inc:75
Launch a kernelSchedule: mapal_cand
Run: DeviceSlot
→ Run: device bytes
processLook up the kernel by id, set its shared memory limit, enqueue on the stream the emitter named.crates/mapal-rt/gpu/mapal_gpu_launch.inc:362driver call cuLaunchKernel; arguments built on the host stack
Pick a candidate for a siteSchedule: mapal_cand
Schedule: Wisdom file line
→ Schedule: choice_memo
processUse the forced index, the stored winner, a timed trial of every candidate, or the compiler's first one, in that order; remember the answer.crates/mapal-rt/gpu/mapal_choice.h:279trial timed with events on the device; result appended to the wisdom file
Carry a device trap to the hostRun: mapal_dev_trap word
→ Run: Trap
processA kernel writes the word; the next host print, clock, copy-back or exit reads it and raises the same trap the host would.crates/mapal-rt/gpu/mapal_gpu_gen.inc:81the hook is a function pointer in the Rust runtime's CHECKPOINT atomic
Emulate the device on the CPURun: device (GPU
→ Run: device (host memory
functorSame entry points, device memory is host memory and a kernel is run once per thread, so tests can check the host half without a GPU.crates/mapal-rt/gpu/mapal_gpu_emu.c:1host heap filled with 0xA5; blocks run as threads that meet at barrier functions
Algorithms, data structures and design patterns (14)
NameKindWhat it isDefined atUsed by
Task graph with dependency countersdata structureEach task counts unmet dependencies; at zero it becomes ready.crates/mapal-rt/src/sched.rs:79Slice and queue, Worker loop
Work-stealing pool with spin then parkdesign patternPer-lane queues; idle workers steal, spin briefly, then sleep on a condition variable.crates/mapal-rt/src/sched.rs:145Worker loop
Epoch counter plus condition variabledesign patternA counter bumped on every change lets waiters re-check without missing a wake-up.crates/mapal-rt/src/run.rs:67Wait and finish
Build then sealdesign patternA mutable list while being built, an immutable lock-free array afterwards.crates/mapal-rt/src/run.rs:39Build the graph, Seal
Arena with one teardowndesign patternAllocate often, free everything once; per-call frames use a mark and release stack.crates/mapal-rt/src/mem.rs:65Allocate host memory
Pure-function parsing of quotasdesign patternThread count from MAPAL_PAR and cgroup limits is computed by small pure functions so it can be tested.crates/mapal-rt/src/sched.rs:385Run a parallel region
Autotune with memo and persistent cache (plan then replay)algorithmTime every candidate once, store the winner keyed by a hash of the table and module, never time again.crates/mapal-rt/gpu/mapal_choice.h:279Pick a candidate for a site
FNV-1a hashalgorithmThe key of a site decision.crates/mapal-rt/gpu/mapal_choice.h:130Pick a candidate for a site
Direct-mapped memo by table addressdata structureA decided site costs one pointer compare.crates/mapal-rt/gpu/mapal_choice.h:125Pick a candidate for a site
Init on a helper thread, join at first usedesign patternDriver start-up overlaps with host work before the first site.crates/mapal-rt/gpu/mapal_gpu_init.inc:128Load the device module
Kernel lookup by id with preloaded tabledata structureA hash table from kernel id to function handle built from the PTX text.crates/mapal-rt/gpu/mapal_gpu_modscan.inc:155Launch a kernel
Stream join by eventsdesign patternA chain stream waits on an event recorded on the default stream if anything was enqueued there since its last join.crates/mapal-rt/gpu/mapal_gpu_memory.inc:167Launch a kernel
Deferred trap checkpointdesign patternThe device error is read only at points where the host would observe a value.crates/mapal-rt/gpu/mapal_gpu_gen.inc:81Carry a device trap to the host
Baton scheduling in the emulatoralgorithmCooperative blocks run one at a time and hand over at grid barriers; a barrier that never completes exits 105.crates/mapal-rt/gpu/mapal_gpu_emu_launch.inc:219Emulate the device on the CPU

Guarantees of Runtime

Guarantee (natural transformation)What must agreeChecked in
Emulator agrees with the deviceThe emulated entry points and the real ones give the same values and the same trap outcome; both share the same pick code.crates/backends/llvm/tests/large_gemm.rs:253
crates/backends/llvm/tests/streamk_epi.rs:270
Print agrees with the interpreterCompiled and interpreted programs print the same text, because both use the same formatter and trap codes.crates/backends/llvm/tests/differential/basics.rs:53
crates/backends/llvm/tests/differential/basics.rs:187

Command line

The `mapal` command: it runs the stages in order for build, run, test, dump-ir, fmt, repl and lsp.

Reads Text → produces Driver

Guarantees: A compiled run agrees with the interpreter, Rewrite and no-rewrite agree

Files (3)

crates/mapal-cli/src/main.rs:1
crates/mapal-cli/src/fmt.rs:1
crates/mapal-cli/src/repl.rs:1

Category Driver

How the command line drives the stages: arguments, side files, sessions.

Objects (5)
ObjectWhat it isDefined atLives in
EmitOptsThe emitter's flags: target profile, face, order, optimization switch on/off settings.crates/backends/llvm/src/opts.rs:48compiler heap, inside Args
Options (fmt)check or stdout mode and the list of files.crates/mapal-cli/src/fmt.rs:23compiler heap
Side files<exe>.ll, <exe>.dev.ll, <exe>.dev.opt.ll, <exe>.ptx, <exe>.o, <exe>.mapal_gpu.c, remarks yaml.crates/mapal-cli/src/main.rs:290disk, next to the executable (or in $TMP/mapal-<pid>/ for run and test)
ArgsCommand, file, output path, mode flags, emitter options, face flags.crates/mapal-cli/src/main.rs:58compiler heap; built by parse_args from the command line
Session / Entry / ReplThe REPL's remembered definitions and statements, replayed as one program each time.crates/mapal-cli/src/repl.rs:79compiler heap; history in a file from history_file
Arrows (2)
ArrowFrom → toWhat it doesDefined at
mainArgs → exit codeDispatch to fmt, repl, lsp, build, run, dump-ir or test.crates/mapal-cli/src/main.rs:83
parse_argscommand line → ArgsRead the command, file and flags.crates/mapal-cli/src/main.rs:128
Transformations (20)
NameFrom → toKindWhat it doesDefined atLives in
frontend (source to checked IR)Text: Source file (.mapal
→ Flow: CategoryIr
functorparse, then lower, then check; any diagnostic stops with exit 1.
made of: parse, lower, check
crates/mapal-cli/src/main.rs:215compiler heap, one process
parseText: Source file (.mapal
→ Syntax: Program
functorSource text to parse tree.crates/mapal-syntax/src/parser.rs:43
lowerSyntax: Program
→ Flow: CategoryIr
functorParse tree to the IR; also records the source directory.crates/mapal-lower/src/lib.rs:52
checkFlow: CategoryIr
→ Diagnostics: Diagnostic
processRules on effects and exclusivity.crates/mapal-check/src/lib.rs:41
rewritten (static folding then rewrite)Flow: CategoryIr
→ Flow: CategoryIr
functorCompute what is known before the run, then apply the rewrite rules.crates/mapal-cli/src/main.rs:252
emitFlow: CategoryIr
Driver: EmitOpts
→ Code: Emission
functorPlan and write LLVM text for host and device.crates/mapal-cli/src/main.rs:273
build (emit, tools, link)Code: Emission
→ Code: PTX file
Code: Executable
processWrite <exe>.ll; on a GPU profile run opt -O3 and llc -O3 for the card's arch to get PTX, compile the host with clang, write the C GPU runtime next to it and link it with libcuda; on CPU link the .ll with libmapal_rt.a.
made of: Write host .ll, Optimize device IR, Device IR to PTX, Compile host object (GPU), Link
crates/mapal-cli/src/main.rs:378child processes opt, llc, clang; files on disk
Write host .llCode: Emission
→ Code: <exe>.ll
processSave the host text.crates/mapal-cli/src/main.rs:317
Optimize device IRCode: <exe>.dev.ll
→ Code: <exe>.dev.opt.ll
processopt -O3.crates/mapal-cli/src/main.rs:352
Device IR to PTXCode: <exe>.dev.opt.ll
→ Code: PTX file
processllc -O3 with -mcpu from the profile's GPU arch and -mattr from the module's declared PTX version.crates/mapal-cli/src/main.rs:378
Compile host object (GPU)Code: <exe>.ll
→ Code: <exe>.o
processclang -O2 -c.crates/mapal-cli/src/main.rs:347
runFlow: CategoryIr
→ Run: stdout
Run: exit code
processCompile into a temp directory, run the program (with MAPAL_PTX set on GPU), pass through its exit code, delete the directory. With --interp: run the interpreter instead.
made of: frontend (source to checked IR), rewritten (static folding then rewrite), build (emit, tools, link)
crates/mapal-cli/src/main.rs:556$TMP/mapal-<pid>/<stem>; child process inherits stdio
in_tempFlow: CategoryIr
→ Run: exit code
processMake the temp directory, build, give the executable command to a closure, remove the directory.crates/mapal-cli/src/main.rs:519
dump-irFlow: CategoryIr
→ Code: text on stdout
processPrint the IR at a chosen stage (lowered, rewritten, llvm, device) or as a Mermaid diagram.crates/mapal-cli/src/main.rs:651
testFlow: CategoryIr
→ Diagnostics: PASS/FAIL line
processRun the interpreter with the compiled program's fold orders and the compiled program with a timeout, and compare exit code and output byte for byte (or against the composed bound when a product admits a weaker member).crates/mapal-cli/src/main.rs:724child process stdout through a pipe, read by wait_boxed
Interpreter run (oracle)Flow: CategoryIr
→ Values: RunResult
processrun, run_ordered, run_weakest or run_bound, then native_observable.crates/mapal-interp/src/lib.rs:49
fmtText: Source file (.mapal
→ Text: Source file (.mapal
processFormat files in place, check, or print to stdout; rejects invalid input.crates/mapal-cli/src/fmt.rs:1
replDriver: Session
→ Values: RunResult
processKeep each definition and statement; on each input rebuild the whole program from the session and run it on the interpreter, showing only the new output.crates/mapal-cli/src/repl/session.rs:206compiler heap; history file on disk
lspEditor: requests
→ Editor: responses
processStart the language server on stdin and stdout.crates/mapal-lsp/src/server.rs:116
Algorithms, data structures and design patterns (8)
NameKindWhat it isDefined atUsed by
Pipeline of stages with a single error typedesign patternEach stage returns Result<_, u8> with the exit code; the message is already printed.crates/mapal-cli/src/main.rs:55frontend (source to checked IR), build (emit, tools, link), run, test
Artifacts named after the executabledesign patternEvery side file is <exe><ext>.crates/mapal-cli/src/main.rs:290build (emit, tools, link)
Embedded runtime sourcedesign patternThe C runtime is compiled into the CLI with include_str! and written out at build time, so the build needs only the CLI and the toolchain.crates/mapal-cli/src/main.rs:378build (emit, tools, link)
Temporary build directorydesign patternA private folder per process, removed even on failure.crates/mapal-cli/src/main.rs:519run, test
Differential testing against an oracledesign patternThe interpreter is the specification; test_cmd checks the native program against it.crates/mapal-cli/src/main.rs:724test
Timeout by polling a childalgorithmRun the program with piped stdout and kill it after N seconds.crates/mapal-cli/src/main.rs:839test
Replay session in REPLdesign patternState is the list of inputs, not a running machine.crates/mapal-cli/src/repl/render.rs:96repl
Toolchain lookup by environmentdesign patternCC, LLVM, MAPAL_RT, MAPAL_CUDA, MAPAL_LD select the tools; missing tools exit 3.crates/mapal-cli/src/main.rs:352build (emit, tools, link)

Guarantees of Command line

Guarantee (natural transformation)What must agreeChecked in
A compiled run agrees with the interpreterEmitting, linking and running gives the same output and exit code as the interpreter on the fixed face, and the same within the bound otherwise. `mapal test` is the gate.crates/mapal-cli/src/main.rs:724
crates/mapal-cli/tests/examples.rs:79
Rewrite and no-rewrite agreeThe --no-rewrite arm and the default arm give the same result; both stay reachable for A/B checks.crates/backends/llvm/tests/differential/basics.rs:10

Language server and editors

Gives editors the compiler's own answers (errors, hover, go to definition, rename, colors) and ships the Neovim and VS Code plugins.

Reads Text, Syntax → produces Editor

Guarantees: Editor errors equal build errors, Rename keeps meaning, Same highlighting everywhere

Files (6)

crates/mapal-lsp/src/lib.rs:1
crates/mapal-lsp/src/analysis.rs:1
crates/mapal-lsp/src/server.rs:1
crates/mapal-lsp/src/text.rs:1
crates/mapal-lsp/src/docs.rs:1
crates/mapal-cli/src/main.rs:1

Category Editor

What an editor sees: requests, answers, colors, plugin files.

Objects (15)
ObjectWhat it isDefined atLives in
ClassThe highlight class of a name (function declaration, builtin, binding, parameter, size ...), the shared vocabulary of all editors.crates/mapal-lsp/src/analysis.rs:156one tag per highlighted span
DefKindWhat a name is: function, type, field, global, local, parameter, body parameter, size parameter, format parameter.crates/mapal-lsp/src/analysis.rs:45one tag in each Def
Ty (editor type)A light type as the source states it, only for hovers and completion; sizes stay as written.crates/mapal-lsp/src/analysis.rs:83server heap, inside Def
AnalysisEverything known about one file: text, parse tree, definitions, uses, highlight spans. A pure function of the text.crates/mapal-lsp/src/analysis.rs:199server heap, rebuilt on each edit and kept per open document
Def / DefIdA named thing in the file (function, type, field, parameter, local) and its index in the definitions list.crates/mapal-lsp/src/analysis.rs:120server heap: Vec<Def> inside Analysis; DefId is a usize index
Occ / RoleOne use of a definition at a span, and whether it is a declaration, read, write, call or type use.crates/mapal-lsp/src/analysis.rs:147server heap: Vec<Occ> inside Analysis
builtin and primitive docsHover text for each builtin function and primitive type.crates/mapal-lsp/src/docs.rs:5constant strings in the binary
TOKEN_TYPES / TOKEN_MODIFIERSThe fixed list of semantic token names the server announces to the editor.crates/mapal-lsp/src/server.rs:41constant tables in the binary and in the capabilities message
Doc (open document)A document the editor opened: its URI, text, version and cached analysis.crates/mapal-lsp/src/server.rs:276server heap: map from URI to Doc inside Server
LineMapLine starts so byte offsets can be converted to editor positions counted in UTF-16 units.crates/mapal-lsp/src/text.rs:7server heap, one per document
server commandThe command used to start the server: the mapal executable plus lsp.editors/nvim/lua/mapal/lsp.lua:1a Lua table in Neovim; a {command, args:[lsp]} object in VS Code
Vim syntax groupsThe Neovim highlighting rules working without a server.editors/nvim/syntax/mapal.vim:1a Vim script loaded by Neovim
highlight class tableOne row per class with its Vim group, TextMate scope and language-server token, the single source of truth tested in all three places.editors/test/classes.tsv:1a data file read by tests; its rows are copied into each editor's own files
token fixtureA sample program and its expected token classes.editors/test/fixture.mapal:1test file on disk
TextMate grammarThe VS Code highlighting rules working without a server.editors/vscode/syntaxes/mapal.tmLanguage.json:1a JSON file inside the extension
Arrows (9)
ArrowFrom → toWhat it doesDefined at
Analysis::class_ofOcc → ClassA use to its highlight class.crates/mapal-lsp/src/analysis.rs:273
Analysis::occ_at / def_atoffset → Occ / DefIdA byte offset to the use under it, then to its definition.crates/mapal-lsp/src/analysis.rs:263
Analysis::occurrencesDefId → Occ listA definition to every place it is used (go to references, rename, highlight).crates/mapal-lsp/src/analysis.rs:268
Analysis::visible_atoffset → DefId listAn offset to the definitions whose name can be written there (completion).crates/mapal-lsp/src/analysis.rs:315
to_lsp_diagnosticDiagnostic → lsp DiagnosticA compiler diagnostic to an editor diagnostic.crates/mapal-lsp/src/server.rs:258
token_ofClass → (type, modifier)A highlight class to the editor's semantic token type and modifier.crates/mapal-lsp/src/server.rs:54
LineMap::position / offset / rangeSourceLoc / offset → lsp Position / RangeConvert between byte offsets or spans and editor positions or ranges.crates/mapal-lsp/src/text.rs:38
semantic token to Vim groupLSP semantic token → Vim groupThe server's token type maps back to a class's Vim group.editors/nvim/lua/mapal/lsp.lua:1
semantic token to TextMate scopeLSP semantic token → TextMate scopeThe same mapping into scopes through the extension manifest.editors/vscode/package.json:1
Transformations (8)
NameFrom → toKindWhat it doesDefined atLives in
Analysis::newText
Syntax
Tokens
→ Editor
functorParses and lexes the text, then walks the tree with a stack of scopes to record every definition and use, each with a role and highlight class.crates/mapal-lsp/src/analysis.rs:212server heap
compile_diagnosticsText
→ Diagnostics
processRuns the compiler's front end (parse, then lower and check if the parse is clean) and returns the same errors `mapal build` would, turning a front-end crash into a warning.crates/mapal-lsp/src/server.rs:229a worker thread with a 64 MiB stack, fed by a channel that keeps only the newest text per document
serve (the request loop)Editor
→ Editor
processReads requests and notifications from the editor over stdin/stdout, keeps open documents, answers definition, references, hover, symbols, rename, completion, format and semantic tokens, and pushes diagnostics.crates/mapal-lsp/src/server.rs:124main server thread; messages are JSON over stdio
mapal lsp commandEditor
→ Editor
processThe CLI subcommand that starts the server on stdin/stdout.
made of: serve (the request loop)
crates/mapal-cli/src/main.rs:83an OS process started by the editor
encode_tokensEditor
→ Editor
functorTurns the classified spans into the editor's delta-encoded semantic token array.crates/mapal-lsp/src/server.rs:646server heap: Vec<SemanticToken> in the reply
Neovim starts the serverEditor
→ Editor
processOn opening a .mapal file, runs `mapal lsp` (command overridable by a global setting) through vim.lsp.config / vim.lsp.start.editors/nvim/lua/mapal/lsp.lua:1a child OS process talking over stdio
VS Code starts the serverEditor
→ Editor
processThe extension finds the executable (setting, bundled binary, or PATH) and launches `<executable> lsp` over stdio; formatting falls back to `<executable> fmt -`.editors/vscode/extension.js:126extension host process spawning a child process
format on requestText
→ Text
processThe editors send buffer text to the formatter (through the server or `mapal fmt -`) and replace the buffer.editors/nvim/lua/mapal/format.lua:1buffer text in the editor, formatter in the mapal process
Algorithms, data structures and design patterns (9)
NameKindWhat it isDefined atUsed by
Pure analysis, rebuilt per editdesign patternAnalysis depends only on the text; no incremental state to keep in sync.crates/mapal-lsp/src/analysis.rs:199Analysis::new
Scope-frame stack walkeralgorithmThe walker pushes a frame per function, block and loop, binds names into it, and looks names up from the inner frame outward.crates/mapal-lsp/src/analysis.rs:379Analysis::new
Definition table plus occurrence listdata structureDefinitions are in one vector and every use points to one by index, so references and rename need no search of the tree.crates/mapal-lsp/src/analysis.rs:147Analysis::new, Rename keeps meaning
Background worker with coalescing queuedesign patternDiagnostics run on their own thread, and a burst of edits to one document collapses to the latest.crates/mapal-lsp/src/server.rs:176compile_diagnostics
UTF-16 position mappingalgorithmEditors count columns in UTF-16 units while the compiler counts bytes, so a line table converts between them.crates/mapal-lsp/src/text.rs:7serve (the request loop)
Request dispatch by method namedesign patternOne match routes each protocol method to a handler.crates/mapal-lsp/src/server.rs:384serve (the request loop)
Single class table checked by three testsdesign patternOne table drives tests in Neovim, VS Code and the server crate so they cannot drift.editors/test/classes.tsv:1Same highlighting everywhere
Layered highlighting (static grammar, then server tokens)design patternThe grammar gives instant colours; the server's semantic tokens refine names once it is running.editors/vscode/syntaxes/mapal.tmLanguage.json:1Same highlighting everywhere
Executable discovery orderalgorithmSetting first, bundled binary second, PATH last.editors/vscode/extension.js:1VS Code starts the server

Guarantees of Language server and editors

Guarantee (natural transformation)What must agreeChecked in
Editor errors equal build errorsFor every file, the errors the editor shows are the errors the compiler's own front end gives.crates/mapal-lsp/tests/protocol.rs:509
Rename keeps meaningRenaming a definition edits exactly its occurrences, so every name still resolves to the same definition.crates/mapal-lsp/tests/protocol.rs:382
Same highlighting everywhereFor each highlight class, Vim, TextMate and the server's tokens give the same look, with or without the server running.crates/mapal-lsp/tests/highlight.rs:324
crates/mapal-lsp/tests/highlight.rs:394
editors/test.sh:1

Guarantees

A guarantee is a natural transformation: two routes between the same two ends that must give the same result. Each square below is one such statement, with the test or gate that checks it.

The lowered graph means what the program means

For every program, interpreting the lowered graph gives what interpreting the parse tree gives.

Checked in: crates/mapal-lower/tests/top_level.rs:43, crates/mapal-lower/tests/proptests.rs:43 · Lowering
Checked on example programs run on the interpreter; the generated-program test checks only that lowering gives valid graphs, not yet that they agree with the tree's meaning.

Formatting keeps the tree

Parsing the formatted text gives the same tree as parsing the original (apart from positions), and formatting twice changes nothing.

Checked in: crates/mapal-syntax/tests/format.rs:171 · Syntax

Lexing and parsing never fail

For every input string, even invalid, lexing and parsing return a result and never panic; bad input shows up only as diagnostics.

Checked in: crates/mapal-syntax/tests/proptest_lexer.rs:40, crates/mapal-syntax/tests/proptest_parser.rs:310, crates/mapal-syntax/tests/proptest_parser.rs:404 · Syntax

Accepted means the interpreter's assumptions hold

For every program the checker accepts, what the interpreter assumes (one return writer, no effect racing in a fan-out) is true.

Checked in: crates/mapal-check/tests/acceptance.rs:65, crates/mapal-check/tests/acceptance.rs:110, crates/mapal-check/tests/exclusivity.rs:44, crates/mapal-check/tests/effects.rs:25 · Checker

Editor errors equal build errors

For every file, the errors the editor shows are the errors the compiler's own front end gives.

Checked in: crates/mapal-lsp/tests/protocol.rs:509 · Language server and editors

Rename keeps meaning

Renaming a definition edits exactly its occurrences, so every name still resolves to the same definition.

Checked in: crates/mapal-lsp/tests/protocol.rs:382 · Language server and editors
The two paths are: rename then resolve, and resolve then rename the table's keys.

Same highlighting everywhere

For each highlight class, Vim, TextMate and the server's tokens give the same look, with or without the server running.

Checked in: crates/mapal-lsp/tests/highlight.rs:324, crates/mapal-lsp/tests/highlight.rs:394, editors/test.sh:1 · Language server and editors
editors/test.sh is the gate that holds the Vim and TextMate files to the same class table.

Facts agree with the interpreter

A claim a fact makes (a tile bound, a proven index, a static value) holds when the interpreter runs the program.

Checked in: crates/mapal-rewrite/tests/stream_plan.rs:135, crates/mapal-rewrite/tests/static_eval.rs:45 · Facts
Similar checks are spread over several rewrite tests; these two are the closest.

Rewrite preserves the interpreter's result

Evaluating the graph before and after rewriting gives the same result, traps included.

Checked in: crates/mapal-rewrite/tests/property.rs:67 · Rewrites

Replaying nothing changes nothing

Replaying with an empty plan reproduces a valid graph equal to the original for every example.

Checked in: crates/mapal-rewrite/tests/identity.rs:55 · Rewrites

Rewrite is deterministic and idempotent

Rewriting twice equals rewriting once, and the same input always gives the same output.

Checked in: crates/mapal-rewrite/tests/property.rs:151 · Rewrites

A sealed graph is always valid

Every program the builder accepts passes validation, and every rule validate has has a matching rejection in the builder.

Checked in: crates/mapal-ir/tests/proptest_builder.rs:87, crates/mapal-ir/tests/builder_rejections.rs:51 · Flow graph

Pictures are stable

Every example graph draws to byte-identical Mermaid text (stored snapshots) and passes the lint.

Checked in: crates/mapal-ir/tests/golden_mermaid.rs:22, crates/mapal-ir/tests/golden_mermaid.rs:91 · Flow graph

Graph algorithms agree with loop structure

Every loop is exactly one non-trivial cycle holding its merge, and loop-back edges are exactly the cycle breakers.

Checked in: crates/mapal-ir/tests/algos/scc.rs:59, crates/mapal-ir/tests/algos/scc.rs:85 · Flow graph

Same graph, same result

Running twice gives the identical outcome and output (no hash maps, no clocks in the value path).

Checked in: crates/mapal-interp/tests/determinism.rs:59, crates/mapal-interp/tests/determinism.rs:49 · Interpreter

The default face lies inside the bound

The weakest-precision run differs from the exact run by at most the composed error bound.

Checked in: crates/mapal-interp/tests/bound.rs:86, crates/mapal-interp/tests/bound.rs:124 · Interpreter

Traps and divergence are outcomes, not panics

An out-of-range index, a zero division or running out of steps gives Trapped or Diverged rather than a crash.

Checked in: crates/mapal-interp/tests/traps.rs:111, crates/mapal-interp/tests/traps.rs:40, crates/mapal-interp/tests/divergence.rs:60 · Interpreter

Compiled code agrees with the interpreter within the bound

The compiled program's printed values equal the interpreter's within the interpreter's bound; the check lives in the backend tests.

Checked in: crates/backends/llvm/tests/differential/basics.rs:10, crates/backends/llvm/tests/differential/batching.rs:274 · Interpreter
Checked in the LLVM backend's tests, not in the interpreter's.

Emulator agrees with the device

The emulated entry points and the real ones give the same values and the same trap outcome; both share the same pick code.

Checked in: crates/backends/llvm/tests/large_gemm.rs:253, crates/backends/llvm/tests/streamk_epi.rs:270 · Runtime
Stated, not checked by a test here: these tests check the emulator against the interpreter; the real device is compared on a GPU box.

Print agrees with the interpreter

Compiled and interpreted programs print the same text, because both use the same formatter and trap codes.

Checked in: crates/backends/llvm/tests/differential/basics.rs:53, crates/backends/llvm/tests/differential/basics.rs:187 · Runtime

A compiled run agrees with the interpreter

Emitting, linking and running gives the same output and exit code as the interpreter on the fixed face, and the same within the bound otherwise. `mapal test` is the gate.

Checked in: crates/mapal-cli/src/main.rs:724, crates/mapal-cli/tests/examples.rs:79 · Command line

Rewrite and no-rewrite agree

The --no-rewrite arm and the default arm give the same result; both stay reachable for A/B checks.

Checked in: crates/backends/llvm/tests/differential/basics.rs:10 · Command line

The native profile is the query plus the calibration

For every device query and calibration line, the native profile equals the one built from those two inputs alone (no name lookup).

Checked in: crates/backends/llvm/src/rules/native_tests.rs:50 · Hardware facts and rules

The rules agree with every cited measurement

For every recorded measurement, what the rules decide matches the measured winner, or the line is marked open.

Checked in: crates/backends/llvm/src/rules/tests.rs:124 · Hardware facts and rules

The rules ignore names

Two parts with the same properties take the same switches.

Checked in: crates/backends/llvm/src/rules/tests.rs:407 · Hardware facts and rules

Search equals exhaustive

For every machine and site, branch and bound finds the same best time as pricing every candidate.

Checked in: crates/mapal-place/tests/search.rs:154 · Machine model

The closed form equals the LRU simulation

For lockstep grids the closed form equals the exact cache simulation byte for byte; for walks and staggers it is within a slice or five percent.

Checked in: crates/mapal-place/tests/props.rs:69 · Machine model

Time is monotone and above the bound

A faster machine or a smaller site never raises the price, and the price is never below the admissible bound.

Checked in: crates/mapal-place/tests/props.rs:322 · Machine model

The pick does not depend on enumeration order

Reversing every domain gives the same pick, and noise flips only picks marked open.

Checked in: crates/mapal-place/tests/search.rs:189 · Machine model

The pick agrees with the measured winner

For every row of the replay corpus the model's pick is scored against the measured winner and the rules' pick; the count of agreements may not fall.

Checked in: crates/backends/llvm/src/place_replay.rs:455 · Machine model

The floor is admissible on every replay arm

For every replayed arm, the cheap floor is never above the full price.

Checked in: crates/backends/llvm/src/place_replay.rs:261 · Machine model

The host launches the kernel the device module holds

The host launches exactly the kernel the device module contains, including when the pick is kept.

Checked in: crates/backends/llvm/src/place/tests.rs:156 · Machine model

The error band is the replay's residuals

The error band written in the compiler equals the one recomputed from the replay data.

Checked in: crates/backends/llvm/src/place_replay.rs:682 · Machine model

A native run agrees with the interpreter

Compile and run gives the interpreter's output and exit status, at -O0 and -O2, on raw and rewritten graphs.

Checked in: crates/backends/llvm/tests/differential/basics.rs:10, crates/backends/llvm/tests/differential/basics.rs:29 · LLVM backend

Emission is deterministic

The same graph and options always give the same text; stored snapshots pin it.

Checked in: crates/backends/llvm/tests/golden_ll/basics.rs:6, crates/backends/llvm/tests/golden_ll/basics.rs:19 · LLVM backend

Data movement equals what the facts require

The copies and allocations emitted are exactly those the dataflow facts need.

Checked in: crates/backends/llvm/tests/resident.rs:206, crates/backends/llvm/tests/resident.rs:239 · LLVM backend

The device agrees with the interpreter within the bound

GPU results equal the interpreter's inside the stated error bound.

Checked in: crates/backends/llvm/tests/large_gemm.rs:253, crates/backends/llvm/tests/site_choice/choice.rs:12 · LLVM backend
Device kernels run through the CPU emulator in these tests; real GPUs are compared on rented boxes.

A switch on and off compute the same values

Each switch only moves operands; turning it off changes speed, not values.

Checked in: crates/backends/llvm/tests/site_choice/choice.rs:12, crates/backends/llvm/tests/site_choice/choice.rs:137 · LLVM backend

A merged launch equals separate launches

A merged group gives the same values as its members launched alone.

Checked in: crates/backends/llvm/tests/horizontal.rs:215, crates/backends/llvm/tests/horizontal.rs:342 · LLVM backend

Streamed attention agrees with the interpreter

The one-pass attention kernel matches the interpreter within the bound.

Checked in: crates/backends/llvm/tests/flash_attention/stream_facts.rs:89, crates/backends/llvm/tests/flash_attention/generated.rs:434 · LLVM backend

A CUDA run agrees with the interpreter

Outputs and traps equal the interpreter's.

Checked in: crates/backends/cuda/tests/differential/basics.rs:11, crates/backends/cuda/tests/differential/basics.rs:168 · CUDA backend

CUDA emission is deterministic

Stored .cu snapshots pin the text.

Checked in: crates/backends/cuda/tests/golden_cu/basics.rs:6, crates/backends/cuda/tests/golden_cu/basics.rs:27 · CUDA backend

Index of algorithms, data structures and design patterns

151 entries. Click a column header to sort; type to filter.

NameKindComponentWhat it isDefined atUsed by
Hand-written recursive-descent parser with depth limitalgorithmSyntaxOne function per grammar rule, a cursor over the token array, and a recursion cap that turns runaway nesting into an error.crates/mapal-syntax/src/parser.rs:62parse
Error recovery with cooldowndesign patternSyntaxAfter an error the parser skips to a safe point and mutes follow-up errors for a short while.crates/mapal-syntax/src/parser.rs:241parse
Context-sensitive guard-arrow scanalgorithmSyntaxA guard arrow like -42-> is one lexeme only when adjacent and at statement start; otherwise it is minus, number, arrow.crates/mapal-syntax/src/lexer.rs:30lex
Spans instead of copied textdesign patternSyntaxTokens and names hold only offsets, and text is cut from the one source string when needed.crates/mapal-syntax/src/token.rs:11lex, parse, format_source
Line-start index with binary searchdata structureSyntaxLine starts are stored once, and an offset is found by search.crates/mapal-syntax/src/loc.rs:59lex
Token-stream pretty printeralgorithmSyntaxThe formatter walks tokens, tracks a stack of brace frames and decides spacing and line breaks from neighbouring token kinds.crates/mapal-syntax/src/format.rs:52format_source
Renderer-free diagnosticsdesign patternSyntaxDiagnostics are plain data with no Display; only the CLI and the language server turn them into text or editor messages.crates/mapal-syntax/src/diag.rs:32lex, parse
Staged pipeline with fail-fast emissiondesign patternLoweringChecks run in stages and are collected; once emission starts the first error stops that function.crates/mapal-lower/src/lib.rs:378lower with globals, declare, emit and seal
Fixed-point rounds (monomorphization)algorithmLoweringRepeat typing and emission up to 32 rounds until every called generic instance was declared.crates/mapal-lower/src/lib.rs:40lower with globals, typing and size inference
Union-find over literal typesalgorithmLoweringInteger/float literals of unknown width are variables merged into groups, then pinned to a type.crates/mapal-lower/src/typing/walk_core.rs:376type one function
Size equation solving (inversion, monotone search, divisor enumeration)algorithmLoweringSolves expressions like n*2 = 8 for n by inverting or searching.crates/mapal-lower/src/sizes/infer.rs:477infer generic sizes and formats
Cycle detection by iterative DFSalgorithmLoweringFinds recursive types and recursive calls with an explicit stack frame.crates/mapal-lower/src/tys.rs:222build the type table, effect analysis
Scope stack with poison marksdata structureLoweringLexical scopes as a stack, with names marked unreadable after a loop.crates/mapal-lower/src/scope.rs:36type one function, emit one function
Token threading for effectsdesign patternLoweringEffectful functions take and return an IO token so order of print/clock is explicit data.crates/mapal-lower/src/emit/exprs.rs:444emit one function, effect analysis
Capture analysis (struct captures flattened to fields)algorithmLoweringFinds which outer values a map/fold body reads and passes them as leading inputs.crates/mapal-lower/src/typing.rs:90type one function, emit one function
Prelude of parsed conversion signaturesdesign patternLoweringto/widen are declared as ordinary generic functions in a prelude parsed once; calls are realized by the builtin the format pair admits.crates/mapal-lower/src/formats.rs:201emit one function, build function signatures
Typed diagnostic cataloguedesign patternLoweringEvery error is one LCode variant with a stable code string.crates/mapal-lower/src/diag.rs:15lower: Syntax -> Flow
Tree walk keyed by node kind with sticky contextdesign patternCheckerA fan-out opens the illegal context, and a sequential block inside it inherits it.crates/mapal-check/src/effects.rs:104effect legality pass
Lexical scope stackdata structureCheckerPush on entering a block, pop on leaving, to know whether a name is a local binding.crates/mapal-check/src/effects.rs:77effect legality pass
In-edge count on the graphalgorithmCheckerCounts non-pair edges into the return object to find a second writer.crates/mapal-check/src/exclusivity.rs:26return exclusivity pass
Deterministic orderingdesign patternCheckerNo hash maps; findings come in a fixed order so two runs agree exactly.crates/mapal-check/src/lib.rs:41check
Arena with typed ids (slotmap)data structureFlow graphObjects, morphisms and functions live in slot arenas; a typed id cannot be confused with another kind, and side tables are SecondaryMaps keyed by the same id.crates/mapal-ir/src/graph.rs:288IrBuilder (declare, build_fn, FnBuilder ops, seal), fact queries (tile_plan, loop_plan, last_use_plan, path_plan, precision_plan, elem_plan, access_plan, residence_plan, ...), validate
Gatekeeper builder + sealing (ill-formed is unconstructible)design patternFlow graphThe only mutable form is IrBuilder; sealing returns an immutable graph, and an independent validator double-checks.crates/mapal-ir/src/builder.rs:172IrBuilder (declare, build_fn, FnBuilder ops, seal), seal, validate
Fact cache stored on the sealed graph (compute once, read after)design patternFlow graphOne OnceLock per fact and function; dependent facts read stored inputs; never recomputed per call site.crates/mapal-ir/src/facts.rs:25fact queries (tile_plan, loop_plan, last_use_plan, path_plan, precision_plan, elem_plan, access_plan, residence_plan, ...)
Iterative Tarjan strongly connected componentsalgorithmFlow graphFinds loops as cycles with an explicit work stack, no recursion.crates/mapal-ir/src/algo/loops.rs:13sccs / topo_order / loop_structure
Kahn topological orderalgorithmFlow graphA legal order of operations by a worklist, with loop back edges cut.crates/mapal-ir/src/algo/loops.rs:162sccs / topo_order / loop_structure
Deterministic containers (no HashMap)design patternFlow graphInsertion-ordered Vecs and slot maps so dumps, orders and snapshots are byte-stable.crates/mapal-ir/src/lib.rs:1IrBuilder (declare, build_fn, FnBuilder ops, seal), to_mermaid / to_mermaid_flow / to_mermaid_category / to_mermaid_string
Depth guard on typesdesign patternFlow graphType walks are iterative or capped at 64 levels so a hostile deep type cannot overflow the stack.crates/mapal-ir/src/ty.rs:276validate
Definition as data (tagless-final Arith trait: run or record)design patternFlow graphOne generic definition of exp/sqrt/sin/cos runs natively (interpreter) or is traced into steps a backend prints.crates/mapal-ir/src/math.rs:178Trace (record a reference definition as data), math candidates / admits / choose
Cost-based choice over declared unitsdesign patternFlow graphRealizations are data (Unit, TargetDef) filtered by error bound and ranked by issue cost.crates/mapal-ir/src/math/target.rs:138math candidates / admits / choose
Forward error analysis (gamma, bound_coef)algorithmFlow graphA-priori rounding error of a sum of products, per site and per precision member.crates/mapal-ir/src/algo/precision.rs:83fact queries (tile_plan, loop_plan, last_use_plan, path_plan, precision_plan, elem_plan, access_plan, residence_plan, ...)
Lifetime colouring of buffersalgorithmFlow graphValues that die before another is born share a colour (a buffer).crates/mapal-ir/src/unit.rs:43unit_plan / out_rows
Plain-function rendering, no Displaydesign patternFlow graphValues stay free of printing code; text comes from plain functions like ty_label.crates/mapal-ir/src/ty.rs:405to_mermaid / to_mermaid_flow / to_mermaid_category / to_mermaid_string
Fact cache on the sealed graphdesign patternFactsEach query is a pure function of the sealed graph, computed once into a write-once slot and read after that.crates/mapal-ir/src/facts.rs:226loop_plan, tile_plan and variants, last_use_plan, unit_plan, stream_plan
Arena with typed idsdata structureFactsObjects, morphisms and functions sit in slot maps keyed by distinct id types; secondary maps hang per-id data off them with deterministic order.crates/mapal-ir/src/graph.rs:288Seal the graph, sccs, topo_order
Strongly connected componentsalgorithmFactsLoop detection by finding cycles in the object graph.crates/mapal-ir/src/algo/loops.rs:13loop_structure, loop_plan
Topological orderalgorithmFactsEvaluation order with insertion-order tie-breaks.crates/mapal-ir/src/algo/loops.rs:162last_use_plan, bounds_proof and finite_plan, path_plan and guard_plan
Liveness with two-iteration loop carryalgorithmFactsPositions and death points of values, with a value live across a loop back edge marked carried.crates/mapal-ir/src/algo/last_use.rs:142residence_plan, unit_plan
Interval analysis narrowed by conditionsalgorithmFactsInteger and float ranges tightened by the guards, loop bounds and phi arms where a value is used.crates/mapal-ir/src/algo/bounds/compute.rs:9bounds_proof and finite_plan
Digit decomposition of indicesalgorithmFactsIndex arithmetic with constant division and remainder is split into per-digit affine terms to detect implicit matrix products.crates/mapal-ir/src/algo/radix.rs:263radix_plan, unit_plan, stream_plan
Hazard classification (RAW/WAR/WAW)algorithmFactsDependencies between operations from the bytes they read and write, with shared buffers.crates/mapal-ir/src/access.rs:77access_plan
Working-set peak over a live intervalalgorithmFactsA value's residence from the peak live bytes between producer and last reader against cache size.crates/mapal-ir/src/residence.rs:65residence_plan
A-priori error bound (gamma-n)algorithmFactsA closed-form rounding error bound for sums of products used as the correctness gate.crates/mapal-ir/src/algo/precision.rs:83precision_plan
Online combine (running max and rescale)algorithmFactsPer-block partials combined by the fold's own operator, with exp rescale for a running max.crates/mapal-ir/src/algo/algebra.rs:290fold_combine, stream_plan
Independent validatordesign patternFactsA second pass re-derives the graph invariants without sharing builder code.crates/mapal-ir/src/validate.rs:98Validate the graph
Fact arms (OFF switches)design patternFactsEach rule can be switched off for comparison, never per hardware.crates/mapal-ir/src/facts.rs:73bounds_proof and finite_plan, unchanged_plan and call_keep, stream_plan
Plan then replaydesign patternRewritesEvery pass only decides (graph to plan, pure); one shared replayer is the only code that builds graphs.crates/mapal-rewrite/src/plan.rs:65rewrite: the fixpoint pipeline, Inlining, Loop lifting, Common-subexpression elimination
Fixpoint iteration with round capalgorithmRewritesRounds repeat until all plans are empty or 32 rounds, with validation after each rebuild.crates/mapal-rewrite/src/driver.rs:87rewrite: the fixpoint pipeline
Value-numbering CSEalgorithmRewritesOperations with the same op and same source are merged; views key by constant index value outside guard arms.crates/mapal-rewrite/src/graph_rewrites.rs:395Common-subexpression elimination
Liveness-based DCEalgorithmRewritesBackward reachability from outputs and effects; anything that may trap or diverge is pinned live.crates/mapal-rewrite/src/graph_rewrites.rs:34Dead-code elimination
Functor law as rewrite ruledesign patternRewritesMap fusion justified by map g after map f equals map (g after f); each pass names its law and preconditions.crates/mapal-rewrite/src/functor_laws.rs:32Map fusion
Body substitution (inlining and fusion synthesis)algorithmRewritesA callee or fused body is rebuilt in the caller with its input mapped to the call source and fresh ids.crates/mapal-rewrite/src/replay/inline.rs:13Replay, Inlining, Map fusion
Evaluate at compile time with the oracledesign patternRewritesStatic values are computed by the interpreter itself, so they are exact on every number face.crates/mapal-rewrite/src/statics.rs:34Static folding
By-value intake and no-op shortcutdesign patternRewritesThe graph is moved in; an all-empty round returns it without a rebuild.crates/mapal-rewrite/src/driver.rs:70rewrite: the fixpoint pipeline
Random program generator (testgen)design patternRewritesA proptest script of steps is built into a sealed graph or source text, used to validate rules on programs they were not designed on; checked in parallel.crates/mapal-rewrite/tests/testgen/mod.rs:203Rewrite preserves the interpreter's result, Facts agree with the interpreter
Rule data tabledata structureRewritesThe Zip/Enumerate naturality laws kept as a const table.crates/mapal-rewrite/src/naturality.rs:30rewrite: the fixpoint pipeline
Fuel (step budget) for total evaluationdesign patternInterpreterA u64 budget decremented per step so every run halts with Done, Diverged or Trapped.crates/mapal-interp/src/eval.rs:62run / run_ordered, eval_fn_within (walk operations in topological order), eval_values / eval_values_once / static_cone
Result as early-exit channel (Abort)design patternInterpreterTraps, divergence and read failure travel as Err and are lifted once at the entry.crates/mapal-interp/src/value.rs:86run / run_ordered, eval_fn_within (walk operations in topological order)
Guard-first loop evaluationalgorithmInterpreterDecide and exit cone evaluated before the advance cone.crates/mapal-interp/src/loops.rs:31run_loop (guard-first loop driver)
Reverse-mode derivative tape (first-order error composition)algorithmInterpreterRecord partial derivatives forward, sweep backward per output to compose deviations along the program.crates/mapal-interp/src/bound.rs:249run_bound (record tape, reverse sweep)
Shared immutable arrays (Rc) with staging slots for productsdata structureInterpreterArrays are reference counted; products are assembled in staging buffers slot by slot, matching Pair edges.crates/mapal-interp/src/eval/helpers.rs:74eval_fn_within (walk operations in topological order)
Cone evaluation (evaluate only what a root reads)algorithmInterpreterRestrict the walk to the set of objects feeding wanted roots.crates/mapal-interp/src/lib.rs:201eval_values / eval_values_once / static_cone
Thread-local recorders (tape, weakest flag, read failure)design patternInterpreterOptional modes switched by scoped thread-local state so the common path has no extra parameters.crates/mapal-interp/src/bound.rs:170run_bound (record tape, reverse sweep), run_weakest
Facts carry provenancedesign patternHardware facts and rulesEvery number is tagged with how it was obtained, and uncertain ones are marked so a decision that depends on them can be called open.crates/mapal-place/src/fact.rs:64Assemble the profile, Translate the profile
Layered fallback for calibrationdesign patternHardware facts and rulesTry the user's file, then the file in the repository, else run with unmeasured numbers.crates/backends/llvm/src/profile/calib.rs:36Find the calibration
Capabilities as geometrydesign patternHardware facts and rulesInstructions are described by what they move and compute, so rules never compare versions.crates/backends/llvm/src/profile/caps.rs:12Assemble the profile
Probe sweep to kneealgorithmHardware facts and rulesEach primitive is swept over how much work a unit keeps in flight; rate is the best point, concurrency the least in flight reaching 90 percent of it.benches/local/place_calib.cu:1Calibration probes
Static table per partdata structureHardware facts and rulesA constant struct per known part, plus a lookup by physical key for new ones.crates/backends/llvm/src/profile/place_rtx_5080.rs:66Assemble the profile
Threshold between nearest winner and loseralgorithmHardware facts and rulesEach rule's cut is placed between the closest measured case that won and the closest that lost, then replayed.crates/backends/llvm/src/rules.rs:342Choose optimization switches from properties
Plan and replaydesign patternHardware facts and rulesDecisions are stored as data (a tsv of measurements) and a test replays them against the rule code.crates/backends/llvm/src/rung_replay.tsv:1The rules agree with every cited measurement
ON/OFF measurement armsdesign patternHardware facts and rulesEvery optimization switch can be forced on or off from the command line for A/B timing; defaults come from the rules only.crates/backends/llvm/src/gpu_arms.rs:544Choose optimization switches from properties
Branch and boundalgorithmMachine modelSearch with an admissible lower bound that prunes prefixes and points.crates/mapal-place/src/search.rs:496Branch and bound search
Minimax regret over intervalsalgorithmMachine modelChoose the candidate whose largest regret at any corner of the fact intervals is smallest.crates/mapal-place/src/search.rs:420Minimax verdict
Exact LRU trace simulationalgorithmMachine modelCounts misses of a line-granular LRU using a Fenwick tree over distinct bytes since last use.crates/mapal-place/src/lru.rs:188The closed form equals the LRU simulation
Fenwick treedata structureMachine modelA binary indexed tree for prefix sums used by the LRU simulator.crates/mapal-place/src/lru.rs:162The closed form equals the LRU simulation
Three-gap progressionalgorithmMachine modelThe gaps between readers of a row in a stream-K walk take at most three sizes; counted directly.crates/mapal-place/src/reuse/walk.rs:11Count misses by distinct bytes
Closed-form reuse by interval unionsalgorithmMachine modelMisses by distinct bytes over waves and walk windows, linear instead of simulated.crates/mapal-place/src/reuse/cross.rs:118Count misses by distinct bytes
Memo caches in thread localsdesign patternMachine modelPure functions of a grid are memoized in thread-local maps and cleared at a size cap.crates/mapal-place/src/reuse.rs:101Count misses by distinct bytes
Little's law flowalgorithmMachine modelA mover's time is the larger of work over rate and latency times work over bytes in flight.crates/mapal-place/src/eval/terms.rs:52A trip's steady state
Facts with intervalsdesign patternMachine modelEvery machine number has a low, value and high; evaluation at the ends makes uncertain picks visible.crates/mapal-place/src/fact.rs:64Evaluate at every corner, Minimax verdict
Lowering as a traitdesign patternMachine modelThe backend supplies its kernels as a Lowering that declares constraints and counts; the search is generic over them.crates/mapal-place/src/lower.rs:125Generate candidate schedules, Branch and bound search
Incumbent with error banddesign patternMachine modelThe rules' choice stays unless the model's pick beats it by more than the measured error band, so a re-measured rate does not churn emission.crates/mapal-place/src/search.rs:37Branch and bound search
Incumbent and candidatedesign patternMachine modelThe rules' launch is always a point of the model's space, and wins unless beaten beyond the band.crates/backends/llvm/src/place/search.rs:252Place one site
Memo by search keydesign patternMachine modelA search is cached by site, part, face, arms and order in a thread-local map; related per-site memos are cleared when a search ends.crates/backends/llvm/src/place/search.rs:252Place one site
Scoped guards (RAII)design patternMachine modelWarmScope, ColScope and OrderScope set per-compile context and restore it when dropped.crates/backends/llvm/src/place/site.rs:97Placement at launch time
Forced launch for loweringdesign patternMachine modelA thread-local FORCED launch replaces whatever the emitter would derive, so a candidate can be lowered and checked in isolation.crates/backends/llvm/src/place/search.rs:70Lower to check a candidate
Plan and replaydesign patternMachine modelMeasured arms are stored as data and every change is re-scored against them.crates/backends/llvm/src/place_replay.tsv:1The pick agrees with the measured winner, The error band is the replay's residuals
Coordinate domainsdata structureMachine modelA lowering's schedule space as a list of coordinates whose allowed values depend on earlier ones, so dominated choices are narrowed before the search.crates/backends/llvm/src/place/emitter.rs:76Branch and bound search
Slot per object, mem2reg left to LLVMdesign patternLLVM backend / Host codeEvery value gets a stack cell written once; LLVM turns them into registers.crates/backends/llvm/src/func/mod.rs:254FnEmit::emit_ordered, emit_morphism
Guard-first loop CFGdesign patternLLVM backend / Host codeThe loop header decides first, so the exit trip still runs the decide cone.crates/backends/llvm/src/loops.rs:22emit_loop
Fixpoint over the call graph (attribute capability)algorithmLLVM backend / Host codeA function is clean only if every callee is clean; loops block willreturn.crates/backends/llvm/src/func/mod.rs:46FnEmit::emit_ordered
Arena of typed ids (SecondaryMap)data structureLLVM backend / Host codePer-object and per-morphism side tables keyed by slotmap ids.crates/backends/llvm/src/func/mod.rs:254emit_module, FnEmit::emit_ordered
Declare only what is useddesign patternLLVM backend / Host codeRuntime declarations are added by searching the emitted text for the call.crates/backends/llvm/src/emit.rs:217emit_module
Strategy ladder with a predicate per optimization switchdesign patternLLVM backend / Host codeEach CPU tile optimization switch has one test (packing_site, window1d_site, conv_site, sme_tile_site) and one emitter.crates/backends/llvm/src/func/mod.rs:526emit_tiled_map (tile ladder)
Loop buffer colouringalgorithmLLVM backend / Host codeNext-state bytes take a spare buffer not read while they are written.crates/backends/llvm/src/func/frame/loop_buffers.rs:52emit_loop
Text builder as the artifactdesign patternLLVM backend / Host codeThe String is the translation unit; no intermediate LLVM object model.crates/backends/llvm/src/opts.rs:198emit_module
Plan then replaydesign patternLLVM backend / GPU memory residencyA pure plan record is computed first; emission only reads it.crates/backends/llvm/src/func/resident.rs:377resident_plan, emit_site_resident
First-fit interval colouringalgorithmLLVM backend / GPU memory residencyBuffers with disjoint lifetimes share bytes.crates/backends/llvm/src/func/resident.rs:486color / color_by, arena
Delta transferdesign patternLLVM backend / GPU memory residencyOnly the rows a trip wrote are uploaded or recomputed.crates/backends/llvm/src/func/resident.rs:121retained_sites
Lazy allocation through a slotdesign patternLLVM backend / GPU memory residencyThe runtime fills the slot on first use, so the host emits no branch.crates/mapal-rt/gpu/mapal_gpu_memory.inc:46emit_site_resident
Candidate table, chosen at loaddesign patternLLVM backend / GPU kernelsCompile time lists launches; the runtime picks one from device limits.crates/backends/llvm/src/func/gpu/site_table.rs:28site_cands, site_call, load-time dispatch
Content-hashed kernel idsalgorithmLLVM backend / GPU kernelsFNV hash of body and profile names a kernel so equal kernels merge.crates/backends/llvm/src/func/gpu/site_table.rs:256device_module
Rule table over hardware propertiesdesign patternLLVM backend / GPU kernelsChoices read geometry (SMs, registers, L2, bandwidth), never a part name.crates/backends/llvm/src/rules.rs:342launch_in
Stream-K / split-KalgorithmLLVM backend / GPU kernelsCut the k fold across blocks, add partials atomically or via workspace.crates/backends/llvm/src/func/gpu/launch_rules.rs:89launch_in, lowered_text / Kernel
Software-pipelined panelsalgorithmLLVM backend / GPU kernelsNext panel loads while this one computes (cp.async, TMA).crates/backends/llvm/src/func/gpu/kernel_geom.rs:580lowered_text / Kernel
Footprint rule (producer cells read lie inside the unit)design patternLLVM backend / Merged launchesGroup membership is decided only by what each work unit reads, not by an operator name.crates/backends/llvm/src/func/flow/units.rs:289unit_of (flow)
Online softmax / running rescalealgorithmLLVM backend / Merged launchesA running maximum and sum are rescaled as windows arrive.crates/backends/llvm/src/func/stream.rs:52stream_geo
Tree and warp-shuffle reductionalgorithmLLVM backend / Merged launchesRow totals by tree in shared memory or by shuffles.crates/backends/llvm/src/func/flow/gen_slices.rs:322unit_kernel
Hazard graph (RAW/WAR/WAW) as the merge testdesign patternLLVM backend / Merged launchesLaunches merge only if the access plan leaves them unordered.crates/backends/llvm/src/func/horizontal.rs:150side_by_side, persistent_fit / chain_ns
Grid barrieralgorithmLLVM backend / Merged launchesA level barrier inside a persistent kernel.crates/backends/llvm/src/func/calls/kernel.rs:13persistent_fit / chain_ns
Ticket (last block combines)algorithmLLVM backend / Merged launchesThe last block to finish a row combines partial states.crates/backends/llvm/src/func/gpu/k_streamk.rs:326stream_geo
Plan + replaydesign patternLLVM backend / Switches and placementRules are checked by replaying every cited measurement.crates/backends/llvm/src/rules/tests.rs:124The rules agree with every cited measurement
ON/OFF measurement armsdesign patternLLVM backend / Switches and placementEvery optimization switch has an off arm for A/B; defaults come from rules, not flags.crates/backends/llvm/src/gpu_arms.rs:544arms applied over rules
Roofline costalgorithmLLVM backend / Switches and placementTime is the larger of flops over rate and bytes over bandwidth.crates/backends/llvm/src/profile/tiles.rs:550placed (machine-place search), rules::optimization switches
Candidate search with admissible flooralgorithmLLVM backend / Switches and placementThe search prunes candidates whose lower bound cannot beat the best.crates/backends/llvm/src/place/search.rs:252placed (machine-place search)
Memoization by key (thread-local)data structureLLVM backend / Switches and placementSearches and machines are cached per key inside one emission.crates/backends/llvm/src/place/search.rs:96placed (machine-place search)
Shape-deduplicated kernelsdesign patternCUDA backendOne definition per structural shape, launched from many sites.crates/backends/cuda/src/kernel/kernels.rs:111emit_kernel_set
Capability fixpoint (TrapCaps)algorithmCUDA backendA launch may trap if any reachable callee may.crates/backends/cuda/src/kernel.rs:262emit_kernel_set
Fn-scope arena zonedesign patternCUDA backendOne allocation and one release per function, escape-checked.crates/backends/cuda/src/arena.rs:99arena_plan
Host-driven loopdesign patternCUDA backendThe loop runs on the host; each trip launches kernels.crates/backends/cuda/src/loops.rs:61emit_loop
Task graph with dependency countersdata structureRuntimeEach task counts unmet dependencies; at zero it becomes ready.crates/mapal-rt/src/sched.rs:79Slice and queue, Worker loop
Work-stealing pool with spin then parkdesign patternRuntimePer-lane queues; idle workers steal, spin briefly, then sleep on a condition variable.crates/mapal-rt/src/sched.rs:145Worker loop
Epoch counter plus condition variabledesign patternRuntimeA counter bumped on every change lets waiters re-check without missing a wake-up.crates/mapal-rt/src/run.rs:67Wait and finish
Build then sealdesign patternRuntimeA mutable list while being built, an immutable lock-free array afterwards.crates/mapal-rt/src/run.rs:39Build the graph, Seal
Arena with one teardowndesign patternRuntimeAllocate often, free everything once; per-call frames use a mark and release stack.crates/mapal-rt/src/mem.rs:65Allocate host memory
Pure-function parsing of quotasdesign patternRuntimeThread count from MAPAL_PAR and cgroup limits is computed by small pure functions so it can be tested.crates/mapal-rt/src/sched.rs:385Run a parallel region
Autotune with memo and persistent cache (plan then replay)algorithmRuntimeTime every candidate once, store the winner keyed by a hash of the table and module, never time again.crates/mapal-rt/gpu/mapal_choice.h:279Pick a candidate for a site
FNV-1a hashalgorithmRuntimeThe key of a site decision.crates/mapal-rt/gpu/mapal_choice.h:130Pick a candidate for a site
Direct-mapped memo by table addressdata structureRuntimeA decided site costs one pointer compare.crates/mapal-rt/gpu/mapal_choice.h:125Pick a candidate for a site
Init on a helper thread, join at first usedesign patternRuntimeDriver start-up overlaps with host work before the first site.crates/mapal-rt/gpu/mapal_gpu_init.inc:128Load the device module
Kernel lookup by id with preloaded tabledata structureRuntimeA hash table from kernel id to function handle built from the PTX text.crates/mapal-rt/gpu/mapal_gpu_modscan.inc:155Launch a kernel
Stream join by eventsdesign patternRuntimeA chain stream waits on an event recorded on the default stream if anything was enqueued there since its last join.crates/mapal-rt/gpu/mapal_gpu_memory.inc:167Launch a kernel
Deferred trap checkpointdesign patternRuntimeThe device error is read only at points where the host would observe a value.crates/mapal-rt/gpu/mapal_gpu_gen.inc:81Carry a device trap to the host
Baton scheduling in the emulatoralgorithmRuntimeCooperative blocks run one at a time and hand over at grid barriers; a barrier that never completes exits 105.crates/mapal-rt/gpu/mapal_gpu_emu_launch.inc:219Emulate the device on the CPU
Pipeline of stages with a single error typedesign patternCommand lineEach stage returns Result<_, u8> with the exit code; the message is already printed.crates/mapal-cli/src/main.rs:55frontend (source to checked IR), build (emit, tools, link), run, test
Artifacts named after the executabledesign patternCommand lineEvery side file is <exe><ext>.crates/mapal-cli/src/main.rs:290build (emit, tools, link)
Embedded runtime sourcedesign patternCommand lineThe C runtime is compiled into the CLI with include_str! and written out at build time, so the build needs only the CLI and the toolchain.crates/mapal-cli/src/main.rs:378build (emit, tools, link)
Temporary build directorydesign patternCommand lineA private folder per process, removed even on failure.crates/mapal-cli/src/main.rs:519run, test
Differential testing against an oracledesign patternCommand lineThe interpreter is the specification; test_cmd checks the native program against it.crates/mapal-cli/src/main.rs:724test
Timeout by polling a childalgorithmCommand lineRun the program with piped stdout and kill it after N seconds.crates/mapal-cli/src/main.rs:839test
Replay session in REPLdesign patternCommand lineState is the list of inputs, not a running machine.crates/mapal-cli/src/repl/render.rs:96repl
Toolchain lookup by environmentdesign patternCommand lineCC, LLVM, MAPAL_RT, MAPAL_CUDA, MAPAL_LD select the tools; missing tools exit 3.crates/mapal-cli/src/main.rs:352build (emit, tools, link)
Pure analysis, rebuilt per editdesign patternLanguage server and editorsAnalysis depends only on the text; no incremental state to keep in sync.crates/mapal-lsp/src/analysis.rs:199Analysis::new
Scope-frame stack walkeralgorithmLanguage server and editorsThe walker pushes a frame per function, block and loop, binds names into it, and looks names up from the inner frame outward.crates/mapal-lsp/src/analysis.rs:379Analysis::new
Definition table plus occurrence listdata structureLanguage server and editorsDefinitions are in one vector and every use points to one by index, so references and rename need no search of the tree.crates/mapal-lsp/src/analysis.rs:147Analysis::new, Rename keeps meaning
Background worker with coalescing queuedesign patternLanguage server and editorsDiagnostics run on their own thread, and a burst of edits to one document collapses to the latest.crates/mapal-lsp/src/server.rs:176compile_diagnostics
UTF-16 position mappingalgorithmLanguage server and editorsEditors count columns in UTF-16 units while the compiler counts bytes, so a line table converts between them.crates/mapal-lsp/src/text.rs:7serve (the request loop)
Request dispatch by method namedesign patternLanguage server and editorsOne match routes each protocol method to a handler.crates/mapal-lsp/src/server.rs:384serve (the request loop)
Single class table checked by three testsdesign patternLanguage server and editorsOne table drives tests in Neovim, VS Code and the server crate so they cannot drift.editors/test/classes.tsv:1Same highlighting everywhere
Layered highlighting (static grammar, then server tokens)design patternLanguage server and editorsThe grammar gives instant colours; the server's semantic tokens refine names once it is running.editors/vscode/syntaxes/mapal.tmLanguage.json:1Same highlighting everywhere
Executable discovery orderalgorithmLanguage server and editorsSetting first, bundled binary second, PATH last.editors/vscode/extension.js:1VS Code starts the server