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.
| Category | Defined under | What it holds | Size |
|---|---|---|---|
| Text | Syntax | Source text and positions in it: .mapal files, strings, spans, line tables. | 6 objects, 6 arrows |
| Tokens | Syntax | The flat list of words and symbols the lexer cuts the text into. | 5 objects, 2 arrows |
| Syntax | Syntax | The parse tree: items, functions, chains of stages, expressions. | 15 objects, 7 arrows |
| Diagnostics | Syntax | Error and warning messages with the place they refer to, whichever stage found them. | 9 objects, 9 arrows |
| Names | Lowering | What names mean while lowering: top-level values, effects, generic sizes. | 6 objects, 4 arrows |
| Types | Flow graph | Mapal's types and number formats, as lowering resolves them and the graph stores them. | 17 objects, 15 arrows |
| Flow | Flow graph | The dataflow graph of a program: objects (values) and morphisms (operations) in sealed functions. | 20 objects, 28 arrows |
| Diagram | Flow graph | Pictures of a graph (Mermaid text): the flow view, category diagrams and string diagrams. | 3 objects, 2 arrows |
| Facts | Facts | Everything the compiler has proven about a graph, stored on the graph and read by every later stage. | 30 objects, 7 arrows |
| Values | Interpreter | What a program computes: scalars, arrays and records, and the error bound of a result. | 11 objects, 5 arrows |
| Target | Hardware facts and rules | A chip as measurable properties (SM count, cache sizes, rates) plus the calibration lines that measured them. | 13 objects, 14 arrows |
| Machine | Machine model | The abstract machine the placement search prices: levels of memory, rates, latencies. | 14 objects, 8 arrows |
| Schedule | Machine model | A way of running a piece of work: tile shapes, launch geometry, residency, placement picks. | 51 objects, 44 arrows |
| Code | LLVM backend | Generated programs: LLVM text, device modules, PTX, object files and executables. | 42 objects, 17 arrows |
| Run | Runtime | A running program: host memory, tasks, device memory, output and exit code. | 32 objects, 28 arrows |
| Driver | Command line | How the command line drives the stages: arguments, side files, sessions. | 5 objects, 2 arrows |
| Editor | Language server and editors | What 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.
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.
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:1crates/mapal-syntax/src/token.rs:1crates/mapal-syntax/src/lexer.rs:1crates/mapal-syntax/src/ast.rs:1crates/mapal-syntax/src/parser.rs:1crates/mapal-syntax/src/parser/tests.rs:1crates/mapal-syntax/src/diag.rs:1crates/mapal-syntax/src/format.rs:1crates/mapal-syntax/src/lib.rs:1
Category Text
Source text and positions in it: .mapal files, strings, spans, line tables.
Objects (6)
| Object | What it is | Defined at | Lives in | Provided by |
|---|---|---|---|---|
| Source file (.mapal) | The program text. | crates/mapal-cli/src/main.rs:215 | disk, then a String on the compiler heap | Command 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:13 | compiler heap: field of Object, Morphism, FuncDef | Facts, Flow graph |
| source: &str | The whole program text, the single source of truth; tokens and names only point into it. | crates/mapal-syntax/src/lexer.rs:23 | compiler process heap: a String read from the .mapal file (or the editor buffer), borrowed by every later stage | |
| LineCol | A 1-based line and column, used only for display. | crates/mapal-syntax/src/loc.rs:49 | stack value, made on demand | |
| LineIndex | A table of where each line starts, so an offset can be turned into a line and column. | crates/mapal-syntax/src/loc.rs:59 | compiler 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:12 | two u32 values, copied inline inside Token, tree nodes and Diagnostic |
Arrows (6)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| at | file, LineIndex, byte offset → 'file:line:col' string | Format a position for a message. | crates/mapal-cli/src/main.rs:194 |
| source_dir | file path → absolute directory | The folder a relative read path resolves against, recorded in the IR. | crates/mapal-cli/src/main.rs:202 |
| SourceLoc::len / empty_at | SourceLoc → u32 / SourceLoc | Length of a span; a zero-width span at a point (for synthesized nodes). | crates/mapal-ir/src/loc.rs:18 |
| LineIndex::line_col | offset (u32) → LineCol | A byte offset becomes its line and column. | crates/mapal-syntax/src/loc.rs:93 |
| SourceLoc::new / empty_at | u32 offsets → SourceLoc | Build a span from two offsets, or an empty span at one point. | crates/mapal-syntax/src/loc.rs:21 |
| slice by span | SourceLoc → &str | A 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)
| Object | What it is | Defined at | Lives in |
|---|---|---|---|
| LexOutput | The token list (always ending in an end-of-file token) together with the lexer's errors. | crates/mapal-syntax/src/lexer.rs:14 | compiler heap: Vec<Token> + Vec<Diagnostic> |
| KEYWORDS | The fixed list of reserved words. | crates/mapal-syntax/src/token.rs:113 | a constant table in the compiler binary |
| GuardKind | Which guard arrow it is: -true->, -false->, -_-> or -42->; the number sits inside the arrow lexeme. | crates/mapal-syntax/src/token.rs:19 | payload of the Guard token kind |
| TokenKind | What a token is: name, literal, keyword, punctuation, operator, guard arrow, error, end of file. | crates/mapal-syntax/src/token.rs:33 | one small tag inside each Token |
| Token | A kind plus its span; the text is not copied. | crates/mapal-syntax/src/token.rs:11 | compiler heap: element of Vec<Token>, a Copy value |
Arrows (2)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| keyword lookup | &str → TokenKind | A 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_string | Token (string lexeme) → String | A 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)
| Object | What it is | Defined at | Lives in | Provided 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:40 | compiler heap, inside Program | Lowering |
| StageKind | What one stage of a chain does: map, fold, call, bind, guard, fan-out and so on. | crates/mapal-syntax/src/ast.rs:303 | compiler heap | |
| Block / BlockItem | A braced body: statements, then an optional final chain that is the value. | crates/mapal-syntax/src/ast.rs:215 | compiler heap | |
| Chain / Stage | A 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:286 | compiler heap | |
| Expr / ExprKind | An expression: literal, name, operator, index, member, struct literal. | crates/mapal-syntax/src/ast.rs:393 | compiler heap | |
| FnDecl | A function: name, size and format parameters, parameters, return type and body. | crates/mapal-syntax/src/ast.rs:62 | compiler heap | |
| GuardArm / GuardDiscr | One arm of a conditional (guard) with the case it matches. | crates/mapal-syntax/src/ast.rs:365 | compiler heap | |
| LoopStmt | A loop statement with its label. | crates/mapal-syntax/src/ast.rs:253 | compiler heap | |
| Name | A bare span; its text is read from the source. | crates/mapal-syntax/src/ast.rs:141 | a SourceLoc inline | |
| ParseOutput | The program tree plus every lexer and parser error, sorted by position. | crates/mapal-syntax/src/ast.rs:21 | compiler heap, handed to lowering, the checker, the formatter-free tools and the language server | |
| Program | The whole parse tree: a list of items. | crates/mapal-syntax/src/ast.rs:28 | compiler process heap, produced by the parser and borrowed by lower | Lowering |
| SizeExpr | A size written as arithmetic over numbers and size names, such as tokens * hidden. | crates/mapal-syntax/src/ast.rs:186 | compiler heap | |
| Ty / TyKind | A written type: a primitive, a named type, an array with a size, or a tuple. | crates/mapal-syntax/src/ast.rs:147 | compiler heap | |
| TypeDecl | A named record type with fields. | crates/mapal-syntax/src/ast.rs:122 | compiler heap | |
| SourceLoc (syntax) | A byte range in the source text; lower keys many tables by its (start,end). | crates/mapal-syntax/src/loc.rs:12 | compiler heap, 8 bytes inline in every node | Lowering |
Arrows (7)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| ir_loc | syntax SourceLoc → IR SourceLoc | Carries 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_text | Name → &str | A name node to its text in the source. | crates/mapal-lower/src/tys.rs:211 |
| src_slice | SourceLoc → &str | A span to the source text it covers. | crates/mapal-lower/src/tys.rs:216 |
| Block to its items and tail | Block → BlockItem / Chain | A body to its statements and its final value chain. | crates/mapal-syntax/src/ast.rs:215 |
| Chain.stages | Chain → Stage | A chain to the ordered stages the value flows through. | crates/mapal-syntax/src/ast.rs:286 |
| Program.items | Program → Item | A program to its top-level items. | crates/mapal-syntax/src/ast.rs:28 |
| every node's span | any tree node → SourceLoc | Each 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)
| Object | What it is | Defined at | Lives in | Provided by |
|---|---|---|---|---|
| TCode | The check stage's error catalogue: T0101 multiple return writers, T0201 effect in a fan-out. | crates/mapal-check/src/diag.rs:15 | a tag value, becomes a &'static str code | Checker |
| Diagnostic (check findings) | The same Diagnostic type as syntax, always severity Error with no fix. | crates/mapal-check/src/diag.rs:33 | compiler heap: Vec<Diagnostic>, in the order exclusivity findings then effect findings | Checker |
| Scope | The 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:77 | compiler heap: stack of name sets, temporary during the walk | Checker |
| 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:55 | the process exit status | Command line |
| LCode | The catalogue of lowering error kinds, each with a stable L-code. | crates/mapal-lower/src/diag.rs:15 | compiler heap, Copy tag | Lowering |
| Severity | Error or warning. | crates/mapal-syntax/src/diag.rs:17 | one tag | |
| DiagCode | A stable code string: L#### lexer, P#### parser, T#### check. | crates/mapal-syntax/src/diag.rs:13 | a &'static str constant | |
| Diagnostic (syntax) | An error with a span, code and message, shared with the parser. | crates/mapal-syntax/src/diag.rs:32 | compiler heap Vec<Diagnostic> | Lowering |
| SuggestedFix | Replace this span with this text, with a label. | crates/mapal-syntax/src/diag.rs:24 | compiler heap, inside a Diagnostic |
Arrows (9)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| diag | (TCode, SourceLoc, message) → Diagnostic | A code, a span and a message become a Diagnostic. | crates/mapal-check/src/diag.rs:33 |
| TCode::code | TCode → DiagCode string | A check error kind to its stable code string. | crates/mapal-check/src/diag.rs:22 |
| to_syntax | mapal_ir SourceLoc → SourceLoc | A source location of the flow graph converts to the syntax span type. | crates/mapal-check/src/exclusivity.rs:18 |
| report | Diagnostic list → stderr lines | Print 'file:line:col error[code] (stage) message'. | crates/mapal-cli/src/main.rs:215 |
| diag | LCode x SourceLoc x message → Diagnostic | Builds a diagnostic. | crates/mapal-lower/src/diag.rs:211 |
| LCode::code | LCode → &str | The code string such as L1201. | crates/mapal-lower/src/diag.rs:113 |
| ir_err | IrError x SourceLoc → Diagnostic | Translates 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) → Diagnostic | Build an error at a span, optionally attach a fix. | crates/mapal-syntax/src/diag.rs:43 |
| Parser::diag / diag_fix | (code, SourceLoc, message) → Diagnostic | The parser records an error, with a cooldown so one mistake does not cascade into many. | crates/mapal-syntax/src/parser.rs:249 |
Transformations (4)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| lex | Text → Tokens Diagnostics | functor | Cuts 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:23 | compiler heap; runs once per source on the main thread |
| parse | Tokens → Syntax Diagnostics | functor | Builds 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:43 | compiler heap; recursion depth capped by DEPTH_LIMIT so deep nesting reports an error instead of overflowing the stack |
| format_source | Text Tokens → Text | process | Re-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:11 | compiler heap: output String; used by `mapal fmt` and the editors' format action |
| source to tree | Text → Syntax Diagnostics | process | The two steps above in order: lex then parse. made of: lex, parse | crates/mapal-syntax/src/parser.rs:43 | compiler heap |
Algorithms, data structures and design patterns (7)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Hand-written recursive-descent parser with depth limit | algorithm | One 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:62 | parse |
| Error recovery with cooldown | design pattern | After an error the parser skips to a safe point and mutes follow-up errors for a short while. | crates/mapal-syntax/src/parser.rs:241 | parse |
| Context-sensitive guard-arrow scan | algorithm | A 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:30 | lex |
| Spans instead of copied text | design pattern | Tokens and names hold only offsets, and text is cut from the one source string when needed. | crates/mapal-syntax/src/token.rs:11 | lex, parse, format_source |
| Line-start index with binary search | data structure | Line starts are stored once, and an offset is found by search. | crates/mapal-syntax/src/loc.rs:59 | lex |
| Token-stream pretty printer | algorithm | The 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:52 | format_source |
| Renderer-free diagnostics | design pattern | Diagnostics 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:32 | lex, parse |
Guarantees of Syntax
| Guarantee (natural transformation) | What must agree | Checked in |
|---|---|---|
| Formatting keeps the tree | Parsing 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 fail | For 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:40crates/mapal-syntax/tests/proptest_parser.rs:310crates/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:1crates/mapal-lower/src/globals.rs:1crates/mapal-lower/src/effects.rs:1crates/mapal-lower/src/tys.rs:1crates/mapal-lower/src/formats.rs:1crates/mapal-lower/src/sizes.rs:1crates/mapal-lower/src/typing.rs:1crates/mapal-lower/src/emit.rs:1crates/mapal-lower/src/scope.rs:1crates/mapal-lower/src/convert.rs:1crates/mapal-lower/src/diag.rs:1
Category Names
What names mean while lowering: top-level values, effects, generic sizes.
Objects (6)
| Object | What it is | Defined at | Lives in |
|---|---|---|---|
| Effects | Which functions are (transitively) effectful, i.e. print, clock or read something. | crates/mapal-lower/src/effects.rs:19 | compiler heap: BTreeMap<String,bool> |
| Binding | What a surface name stands for during emission: its graph object, type, mutability and declaration order. | crates/mapal-lower/src/emit.rs:72 | compiler heap, payload of ScopeStack<Binding> |
| CallLog | What emission saw at generic calls: bindings per site, instances called and requested, and widen checks to prove. | crates/mapal-lower/src/emit.rs:61 | compiler heap in a RefCell shared by rounds |
| Globals / TopItem | The program's top-level values, who reads whom, which are computed before running. | crates/mapal-lower/src/globals.rs:71 | compiler 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:36 | compiler heap: Vec of BTreeMaps; one per function being typed or emitted |
| Instance / SiteKey / Generics | One 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:68 | compiler heap, rebuilt each monomorphization round |
Arrows (4)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| is_effectful | fn name → bool | Whether a call to this function carries the IO token. | crates/mapal-lower/src/effects.rs:26 |
| Globals::used_by | FnDecl → top-level items | Which top-level values a function reads. | crates/mapal-lower/src/globals.rs:95 |
| ScopeStack::poison | name → unreadable name | Marks a name unreadable (reading it later is an error). | crates/mapal-lower/src/scope.rs:135 |
| ScopeStack::resolve | name → Binding | Finds what a name stands for, innermost scope first. | crates/mapal-lower/src/scope.rs:104 |
Transformations (13)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| lower: Syntax -> Flow | Syntax → Flow Diagnostics | functor | The 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 values | Syntax → Names Diagnostics | process | Finds top-level bindings, who reads whom, and rejects effects or cycles among them. | crates/mapal-lower/src/globals.rs:340 | compiler heap; pure |
| compute top-level values before the program runs | Names → Names Types | process | Lowers a small synthetic program and runs its top-level scalars on the interpreter, so they become literals/sizes. | crates/mapal-lower/src/lib.rs:117 | compiler heap; uses the interpreter and a work budget |
| lower with globals | Syntax Names → Flow Diagnostics | process | The 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 analysis | Syntax → Names Diagnostics | process | Walks the call graph to mark effectful functions and reports recursion. | crates/mapal-lower/src/effects.rs:35 | compiler heap; pure |
| build the type table | Syntax → Types Diagnostics | functor | Resolves every declared type, rejecting cycles, bad sizes and duplicates. | crates/mapal-lower/src/tys.rs:87 | compiler heap; pure |
| build function signatures | Syntax Types Names → Types | functor | Gives every function its declared signature, flagged effectful or generic. | crates/mapal-lower/src/typing/sigs.rs:53 | compiler heap; pure |
| typing and size inference | Syntax Types Names → Types Names Diagnostics | process | Per 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:599 | compiler heap; pure per round |
| type one function | Syntax Types → Types | process | Walks a function, unifies literal widths, types map/fold blocks and computes their captures. | crates/mapal-lower/src/typing.rs:229 | compiler heap; WTy variables and union-find per function |
| infer generic sizes and formats | Types → Names | process | Solves the size equations of a generic call to choose its instance. | crates/mapal-lower/src/sizes/infer.rs:229 | compiler heap |
| declare, emit and seal | Syntax Types Names → Flow Diagnostics | process | Declares 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:216 | compiler heap; builder arena |
| emit one function | Syntax Types Names → Flow | process | Binds 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:260 | compiler heap; FnBuilder |
| prove widen exactness | Flow → Diagnostics | process | After sealing, uses the facts to check that each int-to-f32 widen stays within the exact range. | crates/mapal-lower/src/convert.rs:35 | compiler heap; reads facts stored on the sealed graph |
Algorithms, data structures and design patterns (10)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Staged pipeline with fail-fast emission | design pattern | Checks run in stages and are collected; once emission starts the first error stops that function. | crates/mapal-lower/src/lib.rs:378 | lower with globals, declare, emit and seal |
| Fixed-point rounds (monomorphization) | algorithm | Repeat typing and emission up to 32 rounds until every called generic instance was declared. | crates/mapal-lower/src/lib.rs:40 | lower with globals, typing and size inference |
| Union-find over literal types | algorithm | Integer/float literals of unknown width are variables merged into groups, then pinned to a type. | crates/mapal-lower/src/typing/walk_core.rs:376 | type one function |
| Size equation solving (inversion, monotone search, divisor enumeration) | algorithm | Solves expressions like n*2 = 8 for n by inverting or searching. | crates/mapal-lower/src/sizes/infer.rs:477 | infer generic sizes and formats |
| Cycle detection by iterative DFS | algorithm | Finds recursive types and recursive calls with an explicit stack frame. | crates/mapal-lower/src/tys.rs:222 | build the type table, effect analysis |
| Scope stack with poison marks | data structure | Lexical scopes as a stack, with names marked unreadable after a loop. | crates/mapal-lower/src/scope.rs:36 | type one function, emit one function |
| Token threading for effects | design pattern | Effectful functions take and return an IO token so order of print/clock is explicit data. | crates/mapal-lower/src/emit/exprs.rs:444 | emit one function, effect analysis |
| Capture analysis (struct captures flattened to fields) | algorithm | Finds which outer values a map/fold body reads and passes them as leading inputs. | crates/mapal-lower/src/typing.rs:90 | type one function, emit one function |
| Prelude of parsed conversion signatures | design pattern | to/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:201 | emit one function, build function signatures |
| Typed diagnostic catalogue | design pattern | Every error is one LCode variant with a stable code string. | crates/mapal-lower/src/diag.rs:15 | lower: Syntax -> Flow |
Guarantees of Lowering
| Guarantee (natural transformation) | What must agree | Checked in |
|---|---|---|
| The lowered graph means what the program means | For every program, interpreting the lowered graph gives what interpreting the parse tree gives. | crates/mapal-lower/tests/top_level.rs:43crates/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:1crates/mapal-check/src/exclusivity.rs:1crates/mapal-check/src/effects.rs:1crates/mapal-check/src/diag.rs:1
Transformations (3)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| check | Flow Syntax Text → Diagnostics | process | Takes 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:41 | compiler heap; the result is a Vec<Diagnostic> |
| return exclusivity pass | Flow → Diagnostics | process | For 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:26 | reads the sealed CategoryIr on the compiler heap |
| effect legality pass | Syntax Flow Text → Diagnostics | process | Walks 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:34 | compiler heap: a Walk with a Scope stack |
Algorithms, data structures and design patterns (4)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Tree walk keyed by node kind with sticky context | design pattern | A fan-out opens the illegal context, and a sequential block inside it inherits it. | crates/mapal-check/src/effects.rs:104 | effect legality pass |
| Lexical scope stack | data structure | Push on entering a block, pop on leaving, to know whether a name is a local binding. | crates/mapal-check/src/effects.rs:77 | effect legality pass |
| In-edge count on the graph | algorithm | Counts non-pair edges into the return object to find a second writer. | crates/mapal-check/src/exclusivity.rs:26 | return exclusivity pass |
| Deterministic ordering | design pattern | No hash maps; findings come in a fixed order so two runs agree exactly. | crates/mapal-check/src/lib.rs:41 | check |
Guarantees of Checker
| Guarantee (natural transformation) | What must agree | Checked in |
|---|---|---|
| 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. | crates/mapal-check/tests/acceptance.rs:65crates/mapal-check/tests/acceptance.rs:110crates/mapal-check/tests/exclusivity.rs:44crates/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:1crates/mapal-ir/src/ty.rs:1crates/mapal-ir/src/loc.rs:1crates/mapal-ir/src/builder.rs:1crates/mapal-ir/src/validate.rs:1crates/mapal-ir/src/facts.rs:1crates/mapal-ir/src/algo.rs:1crates/mapal-ir/src/access.rs:1crates/mapal-ir/src/residence.rs:1crates/mapal-ir/src/unit.rs:1crates/mapal-ir/src/math.rs:1crates/mapal-ir/src/exp.rs:1crates/mapal-ir/src/split.rs:1crates/mapal-ir/src/narrow.rs:1crates/mapal-ir/src/read.rs:1crates/mapal-ir/src/mermaid.rs:1crates/mapal-ir/src/mermaid_flow.rs:1crates/mapal-ir/src/mermaid_cat.rs:1crates/mapal-ir/src/mermaid_string.rs:1crates/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)
| Object | What it is | Defined at | Lives in | Provided by |
|---|---|---|---|---|
| ExpForm | One exp realization: its algorithm constants and error bound per float width. | crates/mapal-ir/src/exp.rs:30 | consts F32 / F64 in the binary | |
| NarrowForm | Facts of one narrow format: precision bits, exponent range, unit round-off, largest value, whether it saturates. | crates/mapal-ir/src/narrow.rs:30 | computed on demand (NarrowForm::of), no storage | |
| SplitForm / SplitKind | A 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:62 | computed on demand; chosen at compile time by the backend | |
| NarrowFloat | The narrow float formats bf16, f16, f8e4m3, f8e5m2. | crates/mapal-ir/src/ty.rs:192 | compiler heap | Facts |
| Ty / Value | A Mapal type: Int, Float, Narrow, Bool, Unit, Str, IoToken, Tuple, Struct, Array{elem,size}. | crates/mapal-ir/src/ty.rs:23 | compiler heap: field of each Object | Facts |
| Value | A constant: i32, i64, u8, f32, f64, narrow bits, bool, string, unit. | crates/mapal-ir/src/ty.rs:241 | compiler heap: Object.value for Constant objects; constant tables in emitted code later | |
| Arg | One generic argument: a size or a format. | crates/mapal-lower/src/formats.rs:184 | compiler heap | Lowering |
| Format | One concrete number format (f32, bf16, i32, ...), the unit of format generics. | crates/mapal-lower/src/formats.rs:20 | compiler heap, Copy value | Lowering |
| Kind | A class of formats a generic parameter may range over (number, float, int, precision, ...). | crates/mapal-lower/src/formats.rs:111 | compiler heap, Copy value | Lowering |
| GlobalConst | A top-level number computed before the program runs (int, float or bool). | crates/mapal-lower/src/globals.rs:42 | compiler heap, inside Globals.consts | Lowering |
| Equation / Equations | The size equations one call gives (declared dimension = actual length) that inference solves. | crates/mapal-lower/src/sizes/infer.rs:24 | compiler heap, temporary per call | Lowering |
| SizeEnv | The values of size names and format names in scope (n=4, t=bf16). | crates/mapal-lower/src/sizes.rs:34 | compiler 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:125 | compiler heap, only during typing of one function | Lowering |
| BlockSig | The signature of one map/fold body: its input, output and the outer values it captures. | crates/mapal-lower/src/typing.rs:65 | compiler heap, inside TypeInfo.blocks | Lowering |
| FnSig | A function's declared signature (parameter types, return type, effectful?, generic?). | crates/mapal-lower/src/typing.rs:215 | compiler heap: BTreeMap<String, FnSig> | Lowering |
| TypeInfo | What 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:56 | compiler heap, handed from typing to emission | Lowering |
| TypeTable | All declared Mapal types, resolved to fixed-size IR types, with generic declarations kept for instantiation. | crates/mapal-lower/src/tys.rs:28 | compiler heap: BTreeMap<String, Ty> plus the declarations | Lowering |
Arrows (15)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| bf16_from_f32 / f8_from_f32 | f32 → narrow bits | Concrete roundings to bf16 and fp8. | crates/mapal-ir/src/narrow.rs:205 |
| narrow::round / widen | f64 / f32 / u16 bits → u16 bits / f32 | Round a number into a narrow format and read it back. | crates/mapal-ir/src/narrow.rs:138 |
| narrow::widen / round | NarrowFloat bits → f32 | Exact widening and round-to-nearest-even narrowing, the oracle's conversions. | crates/mapal-ir/src/narrow.rs:294 |
| tf32_parts / bf16_parts | f32 → [f32] parts | Cut an f32 into parts a matrix instruction multiplies exactly. | crates/mapal-ir/src/split.rs:278 |
| Ty::Array elem | Ty (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_label | Ty → String | Plain-text name of a type for pictures. | crates/mapal-ir/src/ty.rs:405 |
| Value::ty | Value → Ty | The type of a constant. | crates/mapal-ir/src/ty.rs:257 |
| admit | Verb x Format x Format → Realize | Decides how a to<target>/widen<target> conversion is realized, or why it is refused. | crates/mapal-lower/src/formats.rs:303 |
| embeds | Format x Format → bool | Whether 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::ty | IR Ty → Format | Moves between a format name and its IR scalar type. | crates/mapal-lower/src/formats.rs:79 |
| Kind::admits | Kind x Format → bool | Whether a format belongs to a generic parameter's class. | crates/mapal-lower/src/formats.rs:142 |
| eval (size) | SizeExpr x SizeEnv → u64 | Computes a size expression's number or reports why it cannot. | crates/mapal-lower/src/sizes.rs:262 |
| resolve_tykind | surface Ty → IR Ty | Turns a written type into a resolved type with known sizes. | crates/mapal-lower/src/tys.rs:334 |
| default_of | Ty → Ty | A struct with a default field `_` is read as that field when its context needs it. | crates/mapal-lower/src/tys.rs:57 |
| TypeTable::instance | generic TypeDecl + [Arg] → IR Ty | Instantiates 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, loop | What it is | Where it lives |
|---|---|---|
| Products | Several 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:63crates/mapal-ir/src/graph.rs:68crates/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:91crates/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:158crates/mapal-ir/src/graph.rs:160crates/mapal-ir/src/graph.rs:162crates/mapal-ir/src/graph.rs:38crates/mapal-ir/src/algo.rs:80 |
Operations, the morphisms of Flow (37)
| Operation | From → to | What it does | Defined at |
|---|---|---|---|
| Pair | any value T → product (a, b, ...) | Puts a value into slot i of a product of n slots. | crates/mapal-ir/src/graph.rs:63 |
| Proj | product (a, b, ...) → any value T | Takes component i out of a product. | crates/mapal-ir/src/graph.rs:68 |
| Add | product (a, b, ...) → number | Adds the two numbers of its pair. | crates/mapal-ir/src/graph.rs:72 |
| Sub | product (a, b, ...) → number | Subtracts. | crates/mapal-ir/src/graph.rs:73 |
| Mul | product (a, b, ...) → number | Multiplies. | crates/mapal-ir/src/graph.rs:74 |
| Div | product (a, b, ...) → number | Divides (a zero integer divisor traps). | crates/mapal-ir/src/graph.rs:75 |
| Mod | product (a, b, ...) → number | Remainder. | crates/mapal-ir/src/graph.rs:76 |
| Neg | number → number | Negates a number. | crates/mapal-ir/src/graph.rs:78 |
| Eq | product (a, b, ...) → bool | Equal. | crates/mapal-ir/src/graph.rs:80 |
| Neq | product (a, b, ...) → bool | Not equal. | crates/mapal-ir/src/graph.rs:81 |
| Lt | product (a, b, ...) → bool | Less than. | crates/mapal-ir/src/graph.rs:82 |
| Gt | product (a, b, ...) → bool | Greater than. | crates/mapal-ir/src/graph.rs:83 |
| Le | product (a, b, ...) → bool | At most. | crates/mapal-ir/src/graph.rs:84 |
| Ge | product (a, b, ...) → bool | At least. | crates/mapal-ir/src/graph.rs:85 |
| And | product (a, b, ...) → bool | Both true. | crates/mapal-ir/src/graph.rs:86 |
| Or | product (a, b, ...) → bool | Either true. | crates/mapal-ir/src/graph.rs:87 |
| Not | bool → bool | Negates a truth value. | crates/mapal-ir/src/graph.rs:88 |
| Phi | product (a, b, ...) → any value T | Picks one of two values by a condition: the coproduct (guard) of two branches. | crates/mapal-ir/src/graph.rs:91 |
| Call | any value T → any value T | Calls a named function. | crates/mapal-ir/src/graph.rs:94 |
| Map | array [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 |
| Fold | product (a, b, ...) → any value T | Folds an array into one value from a start value with a function body. | crates/mapal-ir/src/graph.rs:107 |
| Index | product (a, b, ...) → any value T | Reads one element of an array; out of range traps. | crates/mapal-ir/src/graph.rs:113 |
| Zip | product (a, b, ...) → array [T; n] | Pairs two arrays of the same length element by element. | crates/mapal-ir/src/graph.rs:117 |
| Enumerate | array [T; n] → array [T; n] | Pairs every element with its index. | crates/mapal-ir/src/graph.rs:120 |
| Iota | number → array [T; n] | The array 0, 1, ..., n-1. | crates/mapal-ir/src/graph.rs:125 |
| Fill | any value T → array [T; n] | An array of n copies of one value. | crates/mapal-ir/src/graph.rs:129 |
| Update | product (a, b, ...) → array [T; n] | A copy of an array with one element replaced. | crates/mapal-ir/src/graph.rs:134 |
product (a, b, ...) → IoToken | Prints a value and passes the token on. | crates/mapal-ir/src/graph.rs:138 | |
| TimeMs | IoToken → product (a, b, ...) | Reads the clock; gives the next token and the milliseconds. | crates/mapal-ir/src/graph.rs:145 |
| Read | product (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 |
| LoopEnter | any value T → loop state (LoopMerge) | Feeds the loop's start value into the loop state. | crates/mapal-ir/src/graph.rs:158 |
| LoopBack | product (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 |
| LoopExit | product (a, b, ...) → any value T | Sends the loop state out when the condition says stop. | crates/mapal-ir/src/graph.rs:162 |
| Output | any value T → Return | Sends a value to the function's return. | crates/mapal-ir/src/graph.rs:164 |
| Widen | number → number | Exact numeric widening (i32 to i64, f32 to f64, ...). | crates/mapal-ir/src/graph.rs:168 |
| Narrow | number → number | Rounds once to a narrow float format (bf16, f16). | crates/mapal-ir/src/graph.rs:173 |
| Math | number → number | A math builtin on a float: exp, sqrt, sin or cos. | crates/mapal-ir/src/graph.rs:179 |
Kinds of object (5)
| Kind | What it is | Defined at |
|---|---|---|
| Parameter | A function input. | crates/mapal-ir/src/graph.rs:30 |
| Temporary | A computed intermediate. | crates/mapal-ir/src/graph.rs:32 |
| Constant | A literal. | crates/mapal-ir/src/graph.rs:34 |
| Return | The function's output. | crates/mapal-ir/src/graph.rs:36 |
| LoopMerge | The value a loop carries between trips (the feedback point). | crates/mapal-ir/src/graph.rs:38 |
Objects (20)
| Object | What it is | Defined at | Lives in | Provided by |
|---|---|---|---|---|
| Dest | Where the next operation writes: a fresh object, the return slot, or an existing one. | crates/mapal-ir/src/builder.rs:37 | compiler heap, argument only | Lowering |
| FnBuilder | The open builder of one function; emission adds objects and operations through it. | crates/mapal-ir/src/builder.rs:438 | compiler heap, short-lived per function | Lowering |
| FuncKind | Named, MapBody or FoldBody. | crates/mapal-ir/src/graph.rs:264 | field of FuncDef | |
| ObjectKind | Role of a value: Parameter, Temporary, Constant, Return or LoopMerge. | crates/mapal-ir/src/graph.rs:28 | field of Object | |
| Operation | The kind of one graph edge: Map, Fold, Pair, Proj, Phi, Widen, Narrow, ... | crates/mapal-ir/src/graph.rs:60 | compiler heap, tag on each morphism | Facts, 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:288 | compiler heap; created by IrBuilder::seal | Command line, Facts, Lowering, Rewrites |
| FuncDef | A function (named, map body or fold body): one input object, one output object and its list of morphisms. | crates/mapal-ir/src/graph.rs:277 | compiler heap: SlotMap<FuncId, FuncDef> inside CategoryIr | Facts |
| FuncId | Handle naming one function (named function, map body or fold body). | crates/mapal-ir/src/graph.rs:23 | compiler heap: key into SlotMap<FuncId, FuncDef> | |
| MorphismId / Morphism | One operation (an edge) from a source object to a target object, tagged with its Operation and source location. | crates/mapal-ir/src/graph.rs:191 | compiler heap: SlotMap<MorphismId, Morphism> inside CategoryIr | Facts |
| MorphismId | Typed handle naming one operation edge. | crates/mapal-ir/src/graph.rs:21 | compiler heap: key into SlotMap<MorphismId, Morphism> | |
| ObjectId / Object | One 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:43 | compiler heap: SlotMap<ObjectId, Object> inside CategoryIr | Facts |
| ObjectId / FuncId | Typed handle (slotmap key) naming one value in the graph. | crates/mapal-ir/src/graph.rs:19 | compiler heap, index into the arena | Lowering |
| Precision | The set of number formats a float multiplication is allowed to use (full f32, tf32, bf16, f16). | crates/mapal-ir/src/graph.rs:206 | compiler heap: SecondaryMap<MorphismId, Precision> in CategoryIr | Facts |
| Ty (IR) | The IR type of a value: number format, array, struct, token. | crates/mapal-ir/src/ty.rs:23 | compiler heap | Lowering |
| PassId | The seven passes: ConstFold, Cse, Dce, MapFusion, Inline, LiftLoops, Unroll. | crates/mapal-rewrite/src/driver.rs:28 | compiler stack | Rewrites |
| RewriteResult / RewriteReport | The 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:50 | compiler heap | Rewrites |
| NaturalityLaw | A catalogue of Zip/Enumerate naturality equalities, recorded as data with no pass yet. | crates/mapal-rewrite/src/naturality.rs:10 | a const table in the compiler binary | Rewrites |
| FusionSpec / LiftSpec / LiftKind | What to fuse (two map bodies) and what to lift (a counted loop into a captured Fold or Map). | crates/mapal-rewrite/src/plan.rs:45 | compiler heap: values inside RewritePlan | Rewrites |
| RewritePlan | The 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:65 | compiler heap: SecondaryMaps, dropped after replay | Rewrites |
| StaticReport | What compile-time evaluation replaced. | crates/mapal-rewrite/src/statics.rs:19 | compiler heap | Rewrites |
Arrows (28)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| to_mermaid / _flow / _category / _string (+ condensed) | CategoryIr → Mermaid text | The 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/Not | Object (operand tuple) → Object (number or bool) | Arithmetic, comparison and logic; binary ones read a 2-tuple product. | crates/mapal-ir/src/graph.rs:60 |
| Phi | Object (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 / Fill | Object (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 / LoopExit | Object (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 / Read | Object (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 / Narrow | Object (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_edges | ObjectId → [MorphismId] | Adjacency: which arrows leave and enter a value. | crates/mapal-ir/src/graph.rs:348 |
| CategoryIr::owner | ObjectId → FuncId | Which function a value belongs to. | crates/mapal-ir/src/graph.rs:359 |
| out_edges / in_edges | ObjectId → Vec<MorphismId> | From a value to the operations that read it, or the one that makes it. | crates/mapal-ir/src/graph.rs:288 |
| owner | ObjectId → FuncId | Which function a value belongs to. | crates/mapal-ir/src/graph.rs:288 |
| Morphism source / target | MorphismId → ObjectId | The two ends of an operation. | crates/mapal-ir/src/graph.rs:191 |
| Morphism{source,target,op} | ObjectId → ObjectId | The edge record itself: source object, target object, which operation, source span. | crates/mapal-ir/src/graph.rs:191 |
| Emitter::emit_convert | to/widen call → Widen / Narrow morphism | Emits a number-format conversion by what the format pair admits. | crates/mapal-lower/src/emit/collections.rs:275 |
| Emitter::emit_expr_dest | Expr → ObjectId | Emits one expression as an operation writing to a destination. | crates/mapal-lower/src/emit/exprs.rs:14 |
| Emitter::emit_loop | LoopStmt → LoopMerge / LoopBack / LoopExit | Emits a loop with carried state, merge, back edge and exits. | crates/mapal-lower/src/emit/loops.rs:8 |
| Emitter::emit_map_fold | map/fold stage → Map or Fold morphism | Emits 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_read | print/time/read call → token-threaded morphism | Emits effects as operations that take and return the IO token. | crates/mapal-lower/src/emit/exprs.rs:458 |
| Emitter::emit_stage | Stage → ObjectId | Emits one stage of a chain, feeding it the previous stage's value. | crates/mapal-lower/src/emit/chains.rs:161 |
| Emitter::emit_value_match | guard arms → right-folded Phi chain | Emits a match on values as nested Phi choices with the default innermost. | crates/mapal-lower/src/emit/guards.rs:141 |
| RewritePlan::resolve_alias | ObjectId → ObjectId | Follows alias chains to the object a value now stands for. | crates/mapal-rewrite/src/plan.rs:121 |
| old id to new id remap | ObjectId (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)
| Object | What it is | Defined at | Lives in |
|---|---|---|---|
| DNode / DEdge / NodeKind / EdgeKind | One box, one arrow, and their style. | crates/mapal-ir/src/mermaid_diagram.rs:43 | inside Diagram |
| Diagram | Nodes, subgraphs and edges, ready to be printed as Mermaid. | crates/mapal-ir/src/mermaid_diagram.rs:75 | compiler heap, short-lived; ends as a String |
| FlowGraph / FlowAnchor | The plain-values view of the flow: nodes are values or prints, edges are steps, paths are chains. | crates/mapal-ir/src/mermaid_flow.rs:33 | compiler heap, short-lived |
Arrows (2)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| Diagram::render | Diagram → String | Print the Mermaid text. | crates/mapal-ir/src/mermaid_diagram.rs:143 |
| FlowGraph::edge_label | FlowGraph edge → String | Label an arrow in source words. | crates/mapal-ir/src/mermaid_flow.rs:99 |
Transformations (14)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| IrBuilder (declare, build_fn, FnBuilder ops, seal) | Flow: (emptyTypes Text → Flow: (CategoryIr | process | The 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:172 | builder 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: (partialTypes → Flow: (partial | process | Each call appends an object and edge; rejection matrix is IrError. | crates/mapal-ir/src/builder.rs:438 | compiler heap |
| seal | Flow: (partial→ Flow: (CategoryIr | process | Freeze: 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:266 | compiler heap |
| validate | Flow → Diagnostics: (IrViolation list | functor | An independent re-check of every graph rule (ownership, edge types, tokens, loops, references); used as the test oracle. | crates/mapal-ir/src/validate.rs:98 | returns 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 | functor | Each 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:198 | cached in CategoryIr.facts OnceLock slots; per-function |
| sccs / topo_order / loop_structure | Flow → Facts | process | Find the cycles (loops) and a legal execution order, without recursion. | crates/mapal-ir/src/algo/loops.rs:13 | compiler heap: Vec<Vec<ObjectId>>, Vec<MorphismId> |
| to_mermaid / to_mermaid_flow / to_mermaid_category / to_mermaid_string | Flow → Diagram | functor | Three views of the graph (flow, category, string diagram), each condensed or full, printed as Mermaid. | crates/mapal-ir/src/mermaid_flow.rs:232 | short-lived Diagram then String |
| category_diagram | Flow → Diagram | functor | Objects as boxes and morphisms as labelled arrows. | crates/mapal-ir/src/mermaid_cat.rs:104 | short-lived |
| string_diagram | Flow → Diagram | functor | String-diagram view (wires and boxes). | crates/mapal-ir/src/mermaid_string.rs:121 | short-lived |
| lint_mermaid | Diagram → Diagnostics | process | Check that Mermaid text will render. | crates/mapal-ir/src/mermaid.rs:200 | Vec<String> |
| math candidates / admits / choose | Types: (MathFnTarget: (units→ Code: (Choice, Def | process | For 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:502 | compiler 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 | functor | The 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:58 | Vec<Step> on compiler heap; printed as LLVM text or C |
| read::load / decode / encode | Types: (array typeText: (path→ Flow: constants / Values | process | Load a binary file as an array of the declared element type, with exact-size checks and friendly messages. | crates/mapal-ir/src/read.rs:154 | file bytes into a Vec<u8> then Vec<Value> on host heap |
| unit_plan / out_rows | Flow Facts → Facts | functor | Group sites into row blocks and colour on-chip buffers by death. | crates/mapal-ir/src/unit.rs:250 | cached in FuncFacts |
Algorithms, data structures and design patterns (12)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Arena with typed ids (slotmap) | data structure | Objects, 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:288 | IrBuilder (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 pattern | The only mutable form is IrBuilder; sealing returns an immutable graph, and an independent validator double-checks. | crates/mapal-ir/src/builder.rs:172 | IrBuilder (declare, build_fn, FnBuilder ops, seal), seal, validate |
| Fact cache stored on the sealed graph (compute once, read after) | design pattern | One OnceLock per fact and function; dependent facts read stored inputs; never recomputed per call site. | crates/mapal-ir/src/facts.rs:25 | fact queries (tile_plan, loop_plan, last_use_plan, path_plan, precision_plan, elem_plan, access_plan, residence_plan, ...) |
| Iterative Tarjan strongly connected components | algorithm | Finds loops as cycles with an explicit work stack, no recursion. | crates/mapal-ir/src/algo/loops.rs:13 | sccs / topo_order / loop_structure |
| Kahn topological order | algorithm | A legal order of operations by a worklist, with loop back edges cut. | crates/mapal-ir/src/algo/loops.rs:162 | sccs / topo_order / loop_structure |
| Deterministic containers (no HashMap) | design pattern | Insertion-ordered Vecs and slot maps so dumps, orders and snapshots are byte-stable. | crates/mapal-ir/src/lib.rs:1 | IrBuilder (declare, build_fn, FnBuilder ops, seal), to_mermaid / to_mermaid_flow / to_mermaid_category / to_mermaid_string |
| Depth guard on types | design pattern | Type walks are iterative or capped at 64 levels so a hostile deep type cannot overflow the stack. | crates/mapal-ir/src/ty.rs:276 | validate |
| Definition as data (tagless-final Arith trait: run or record) | design pattern | One generic definition of exp/sqrt/sin/cos runs natively (interpreter) or is traced into steps a backend prints. | crates/mapal-ir/src/math.rs:178 | Trace (record a reference definition as data), math candidates / admits / choose |
| Cost-based choice over declared units | design pattern | Realizations are data (Unit, TargetDef) filtered by error bound and ranked by issue cost. | crates/mapal-ir/src/math/target.rs:138 | math candidates / admits / choose |
| Forward error analysis (gamma, bound_coef) | algorithm | A-priori rounding error of a sum of products, per site and per precision member. | crates/mapal-ir/src/algo/precision.rs:83 | fact queries (tile_plan, loop_plan, last_use_plan, path_plan, precision_plan, elem_plan, access_plan, residence_plan, ...) |
| Lifetime colouring of buffers | algorithm | Values that die before another is born share a colour (a buffer). | crates/mapal-ir/src/unit.rs:43 | unit_plan / out_rows |
| Plain-function rendering, no Display | design pattern | Values stay free of printing code; text comes from plain functions like ty_label. | crates/mapal-ir/src/ty.rs:405 | to_mermaid / to_mermaid_flow / to_mermaid_category / to_mermaid_string |
Guarantees of Flow graph
| Guarantee (natural transformation) | What must agree | Checked in |
|---|---|---|
| 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. | crates/mapal-ir/tests/proptest_builder.rs:87crates/mapal-ir/tests/builder_rejections.rs:51 |
| Pictures are stable | Every example graph draws to byte-identical Mermaid text (stored snapshots) and passes the lint. | crates/mapal-ir/tests/golden_mermaid.rs:22crates/mapal-ir/tests/golden_mermaid.rs:91 |
| 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. | crates/mapal-ir/tests/algos/scc.rs:59crates/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.
Guarantees: Facts agree with the interpreter
Files (10)
crates/mapal-ir/src/algo.rs:1crates/mapal-ir/src/facts.rs:1crates/mapal-ir/src/access.rs:1crates/mapal-ir/src/residence.rs:1crates/mapal-ir/src/unit.rs:1crates/mapal-ir/src/split.rs:1crates/mapal-ir/src/exp.rs:1crates/mapal-ir/src/narrow.rs:1crates/mapal-ir/src/read.rs:1crates/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)
| Object | What it is | Defined at | Lives in | Provided by |
|---|---|---|---|---|
| AccessPlan / Hazard | The 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:43 | compiler heap: FuncFacts.access_plan | Flow graph |
| Delta | Which cells of a carried array one loop trip writes: a row range or a repeating set of pieces. | crates/mapal-ir/src/algo.rs:106 | compiler heap: SecondaryMap<ObjectId, Delta> in FuncFacts.write_delta | |
| MovePlan / CellSite / RowFoldSite / LinearSite | Data-move sites, per-cell map sites, one-value-per-row folds and sums of tile sites. | crates/mapal-ir/src/algo/tile_types.rs:336 | compiler heap: FuncFacts.move_plan, cell_plan, trap_cell_plan, row_fold, whole_fold, linear_plan | |
| ElemPlan / ElemSrc | Each array's element as a closed function of its index (index itself, broadcast, load, pair, apply). | crates/mapal-ir/src/algo/plan_types.rs:301 | compiler heap: FuncFacts.elem_plan | Flow graph |
| EmissionPlan / EmissionClass | Which objects need bytes, which dissolve into views, and how many consumers each has. | crates/mapal-ir/src/algo/plan_types.rs:153 | compiler heap: FuncFacts.emission_plan | |
| FootprintPlan / Reach / Edge | What 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:412 | compiler heap: FuncFacts.footprint_plan | |
| GuardSite / GuardArm | Each 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:271 | compiler heap: Vec<GuardSite> in FuncFacts.guard_plan and guard_structure | |
| LastUsePlan | Each 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:15 | compiler heap: FuncFacts.last_use_plan | Flow graph |
| LoopPlan / LoopScc | A 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:80 | compiler heap (fact slots) | Flow graph, Rewrites |
| PathPlan / Task / Checkpoint | Independent parallel tasks, which are splittable bulk operations, and where the host must wait for them. | crates/mapal-ir/src/algo.rs:205 | compiler heap: FuncFacts.path_plan | Flow graph |
| TensorForm | A tile operand described as a dense tensor of at most three axes. | crates/mapal-ir/src/algo/tile_types.rs:124 | compiler heap: computed on demand from a TileRead (TileRead::tensor_form) | |
| TilePlan / TileSite / TileRead | A 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:501 | compiler heap: FuncFacts.tile_plan, tile_plan_strided, tile_plan_post, tile_plan_narrow, tile_plan_radix | Flow graph |
| TripSplit / TripPhase | For 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:53 | compiler heap: Vec<TripSplit> in FuncFacts.trip_split | |
| FoldCombinePlan / FoldCombine / DepLaw | How 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:377 | compiler heap: FuncFacts.fold_combine | |
| StepAlgebra / FmaPair / Regroup | Which 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:61 | compiler heap: FuncFacts.step_algebra | |
| BoundsProof | Which Index reads are proven inside their array, and the integer range of each index. | crates/mapal-ir/src/algo/bounds.rs:49 | compiler heap: FuncFacts.bounds_proof | |
| PrecisionPlan / NarrowStore | The precisions each product admits, where rounding happens once, and each site's error bound. | crates/mapal-ir/src/algo/precision.rs:16 | compiler heap: FuncFacts.precision_plan | Flow graph |
| RadixForm / Digit / RadixTile | An 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:33 | compiler heap: SecondaryMap<ObjectId, RadixForm> in FuncFacts.radix_plan | |
| FinitePlan | Which float values are proven free of infinity and NaN by interval arithmetic. | crates/mapal-ir/src/algo/range.rs:65 | compiler heap: FuncFacts.finite_plan | |
| StaticPlan / StaticRoot / Realize | Which 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:90 | compiler heap: FuncFacts.static_plan | Flow graph |
| StreamPlan / StreamGroup / StreamGuard / GuardBox | A 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:71 | compiler heap: FuncFacts.stream_plan | |
| StreamPlan / StreamGroup | One pass over windows of an axis (attention-like): the role of each member. | crates/mapal-ir/src/algo/stream.rs:412 | cached in FuncFacts | Flow graph |
| UnchangedPlan / CallKeep | For 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:48 | compiler heap: FuncFacts.unchanged_plan and call_keep | |
| ExpForm / NarrowForm / MathForm | The contract of the exponential and of each narrow float format (algorithm constants, error bound, exactness). | crates/mapal-ir/src/exp.rs:30 | compiler heap: plain values; NarrowForm in narrow.rs | |
| FactArms | Switches that turn individual fact rules off, used only to compare against the older behaviour (all on by default). | crates/mapal-ir/src/facts.rs:73 | compiler heap: field of Facts, set by CategoryIr::refacted | Flow 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:25 | compiler heap: SecondaryMap<FuncId, FuncFacts> inside CategoryIr.facts | Flow graph |
| ResidencePlan / Residence | Per 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:34 | compiler heap: FuncFacts.residence_plan | Flow graph |
| SplitForm / AccModel | A 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:62 | compiler heap: plain values built by SplitForm::of | |
| UnitPlan / UnitGroup / UnitMember / RowMap | Groups 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:120 | compiler heap: FuncFacts.unit_plan | |
| UnitPlan / UnitGroup | Row-block groups of sites that can run together on chip. | crates/mapal-ir/src/unit.rs:157 | cached in FuncFacts | Flow graph |
Arrows (7)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| Hazard edges within a loop trip | MorphismId → MorphismId | Which operation must wait for which, with the kind of conflict. | crates/mapal-ir/src/access.rs:96 |
| Fact query by object | ObjectId → Fact entry | Every 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_by | ObjectId / MorphismId → position / ObjectId | Where 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 value | Look 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 value | Return the stored fact, or compute it once from stored inputs and keep it. | crates/mapal-ir/src/facts.rs:226 |
| CategoryIr::refacted | CategoryIr → CategoryIr | Copy the graph with an empty fact store and different arms. | crates/mapal-ir/src/facts.rs:203 |
| ResidencePlan::at | ObjectId → Residence | Place of a value given a cache capacity. | crates/mapal-ir/src/residence.rs:53 |
Transformations (30)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| Seal the graph | Flow → Flow Facts | process | Freezes the builder's graph and pre-allocates one empty fact slot per function. | crates/mapal-ir/src/builder.rs:266 | compiler heap, once per graph |
| Validate the graph | Flow → Diagnostics | process | Independently re-checks the graph's shape rules and lists violations; the test oracle for every pass. | crates/mapal-ir/src/validate.rs:98 | compiler heap, returns Vec<IrViolation> |
| Loop facts | Flow → Facts | functor | Finds 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:425 | FuncFacts slots |
| sccs | Flow → Facts | process | Strongly connected sets of objects, which are the loops. | crates/mapal-ir/src/algo/loops.rs:13 | FuncFacts.sccs |
| topo_order | Flow → Facts | process | A deterministic evaluation order of a function's operations. | crates/mapal-ir/src/algo/loops.rs:162 | FuncFacts.topo_order |
| loop_structure | Facts → Facts | process | Lists each loop and its merge objects. | crates/mapal-ir/src/algo/loops.rs:385 | FuncFacts.loop_structure |
| loop_plan | Facts → Facts | process | Names init, back route, exit and the decide/advance order of each canonical loop. | crates/mapal-ir/src/algo/loops.rs:425 | FuncFacts.loop_plans |
| trip_split | Facts → Facts | process | Cuts a counted loop's trips where guards on the counter change behaviour. | crates/mapal-ir/src/algo/site_plans.rs:336 | FuncFacts.trip_split |
| write_delta | Facts → Facts | process | The contiguous rows or pieces of a carried array that each trip writes. | crates/mapal-ir/src/algo/write_delta.rs:36 | FuncFacts.write_delta |
| unchanged_plan and call_keep | Facts → Facts | process | Carries write deltas through row-local maps to say what stays the same between trips and calls. | crates/mapal-ir/src/algo/unchanged/compute.rs:9 | FuncFacts.unchanged_plan, call_keep |
| static_plan | Facts → Facts | process | Finds values computable before the program runs and prices embedding them against computing them. | crates/mapal-ir/src/algo/statics.rs:137 | FuncFacts.static_plan |
| Lifetime and emission facts | Flow Facts → Facts | functor | Which 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:142 | FuncFacts slots |
| emission_plan | Flow → Facts | process | Classifies each object as materialized, dissolved into a view, inline or named. | crates/mapal-ir/src/algo/site_plans.rs:26 | FuncFacts.emission_plan |
| last_use_plan | Facts → Facts | process | Positions, death points, escapes and loop-carried liveness over two iterations. | crates/mapal-ir/src/algo/last_use.rs:142 | FuncFacts.last_use_plan |
| access_plan | Facts → Facts | process | Reads, writes, storage classes and hazard edges per loop trip. | crates/mapal-ir/src/access.rs:126 | FuncFacts.access_plan |
| residence_plan | Facts → Facts | process | Peak live bytes from producer to last reader, compared to a cache size. | crates/mapal-ir/src/residence.rs:65 | FuncFacts.residence_plan |
| path_plan and guard_plan | Flow Facts → Facts | process | Splits work into independent tasks, finds host checkpoints, and records which conditional arms must be gated. | crates/mapal-ir/src/algo/paths.rs:16 | FuncFacts.path_plan, guard_plan, guard_structure |
| bounds_proof and finite_plan | Flow Facts → Facts | process | Proves 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:9 | FuncFacts.bounds_proof, finite_plan |
| Site recognition | Flow Facts → Facts | functor | Recognizes 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:198 | FuncFacts slots |
| elem_plan and map_law | Flow → Facts | process | Each 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:20 | FuncFacts.elem_plan |
| tile_plan and variants | Flow Facts → Facts | process | Finds sum-of-products sites: plain, strided, with epilogue, narrow-storage, and mixed-radix. | crates/mapal-ir/src/algo/site_plans.rs:198 | FuncFacts.tile_plan*, tile_plan_radix |
| radix_plan | Flow → Facts | process | Writes each integer value as digits of the inputs so strided and implicit-matrix reads are visible. | crates/mapal-ir/src/algo/radix.rs:263 | FuncFacts.radix_plan |
| cell_plan, row_fold, whole_fold, move_plan, footprint_plan | Flow Facts → Facts | process | Per-cell maps, row folds, data-move sites and what each cell reads. | crates/mapal-ir/src/algo/cells.rs:16 | FuncFacts slots |
| Arithmetic freedom facts | Flow Facts → Facts | functor | States 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:108 | FuncFacts slots |
| step_algebra | Flow → Facts | process | Multiply-add pairs that can fuse and fold steps that can regroup. | crates/mapal-ir/src/algo/algebra.rs:108 | FuncFacts.step_algebra |
| fold_combine | Facts → Facts | process | How block partials of a fold combine and how each per-row value is applied. | crates/mapal-ir/src/algo/algebra.rs:428 | FuncFacts.fold_combine |
| precision_plan | Flow Facts → Facts | process | Admitted product precisions, where rounding happens once, and a-priori error bounds per site. | crates/mapal-ir/src/algo/precision.rs:112 | FuncFacts.precision_plan |
| Row-block and streaming facts | Facts → Facts | functor | Groups 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:284 | FuncFacts.unit_plan, stream_plan |
| unit_plan | Facts → Facts | process | Row-block groups with row-closed edges and bytes per row. | crates/mapal-ir/src/unit.rs:284 | FuncFacts.unit_plan |
| stream_plan | Facts → Facts | process | One-pass windowed evaluation of an axis, with mask boxes and per-fold combine laws. | crates/mapal-ir/src/algo/stream.rs:430 | FuncFacts.stream_plan |
Algorithms, data structures and design patterns (13)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Fact cache on the sealed graph | design pattern | Each 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:226 | loop_plan, tile_plan and variants, last_use_plan, unit_plan, stream_plan |
| Arena with typed ids | data structure | Objects, 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:288 | Seal the graph, sccs, topo_order |
| Strongly connected components | algorithm | Loop detection by finding cycles in the object graph. | crates/mapal-ir/src/algo/loops.rs:13 | loop_structure, loop_plan |
| Topological order | algorithm | Evaluation order with insertion-order tie-breaks. | crates/mapal-ir/src/algo/loops.rs:162 | last_use_plan, bounds_proof and finite_plan, path_plan and guard_plan |
| Liveness with two-iteration loop carry | algorithm | Positions and death points of values, with a value live across a loop back edge marked carried. | crates/mapal-ir/src/algo/last_use.rs:142 | residence_plan, unit_plan |
| Interval analysis narrowed by conditions | algorithm | Integer 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:9 | bounds_proof and finite_plan |
| Digit decomposition of indices | algorithm | Index 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:263 | radix_plan, unit_plan, stream_plan |
| Hazard classification (RAW/WAR/WAW) | algorithm | Dependencies between operations from the bytes they read and write, with shared buffers. | crates/mapal-ir/src/access.rs:77 | access_plan |
| Working-set peak over a live interval | algorithm | A value's residence from the peak live bytes between producer and last reader against cache size. | crates/mapal-ir/src/residence.rs:65 | residence_plan |
| A-priori error bound (gamma-n) | algorithm | A closed-form rounding error bound for sums of products used as the correctness gate. | crates/mapal-ir/src/algo/precision.rs:83 | precision_plan |
| Online combine (running max and rescale) | algorithm | Per-block partials combined by the fold's own operator, with exp rescale for a running max. | crates/mapal-ir/src/algo/algebra.rs:290 | fold_combine, stream_plan |
| Independent validator | design pattern | A second pass re-derives the graph invariants without sharing builder code. | crates/mapal-ir/src/validate.rs:98 | Validate the graph |
| Fact arms (OFF switches) | design pattern | Each rule can be switched off for comparison, never per hardware. | crates/mapal-ir/src/facts.rs:73 | bounds_proof and finite_plan, unchanged_plan and call_keep, stream_plan |
Guarantees of Facts
| Guarantee (natural transformation) | What must agree | Checked in |
|---|---|---|
| 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. | crates/mapal-rewrite/tests/stream_plan.rs:135crates/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
Transformations (12)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| rewrite: the fixpoint pipeline | Flow → Flow | functor | Runs 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:70 | compiler heap; returns a new graph |
| Analysis passes | Flow → Flow: RewritePlan | process | Each pass reads the graph and fills plan channels without changing the graph. | crates/mapal-rewrite/src/driver.rs:87 | compiler heap |
| Constant folding and identities | Flow → Flow: RewritePlan | process | Folds constant scalars and forwards identities at the oracle's exact semantics, never folding a trap. | crates/mapal-rewrite/src/equations.rs:24 | RewritePlan.constify, alias |
| Common-subexpression elimination | Flow → Flow: RewritePlan | process | Merges duplicate pure computations; an element view outside guard arms is keyed by constant index value. | crates/mapal-rewrite/src/graph_rewrites.rs:341 | RewritePlan.alias |
| Dead-code elimination | Flow → Flow: RewritePlan | process | Drops dead cones of pure, non-trapping, terminating operations. | crates/mapal-rewrite/src/graph_rewrites.rs:34 | RewritePlan.drop |
| Map fusion | Flow → Flow: RewritePlan | process | Replaces map g after map f by one map, and drops map of identity. | crates/mapal-rewrite/src/functor_laws.rs:32 | RewritePlan.fuse, alias |
| Inlining | Flow → Flow: RewritePlan | process | Strips Call operations by substituting the callee's body when it is small enough (256 morphisms). | crates/mapal-rewrite/src/inline.rs:47 | RewritePlan.inline |
| Loop lifting | Flow → Flow: RewritePlan | process | Recognizes counted accumulator and fill loops and rewrites them as captured Fold or Map. | crates/mapal-rewrite/src/lift.rs:23 | RewritePlan.lift |
| Loop unrolling | Flow → Flow: RewritePlan | process | Replays a short constant-trip loop as its trips one after another, up to 128 trips. | crates/mapal-rewrite/src/unroll.rs:37 | RewritePlan.unroll |
| Static folding | Flow Facts → Flow | process | Computes the static_plan roots with the interpreter and replaces their cones with constants. | crates/mapal-rewrite/src/statics.rs:34 | compiler heap; interpreter run at compile time |
| Replay | Flow Flow: RewritePlan→ Flow | functor | Walks 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:67 | compiler heap; new CategoryIr |
| Canonical-loop guard | Flow → Flow | process | If any loop is outside the canonical shapes, rewrite hands the graph back untouched. | crates/mapal-rewrite/src/replay/support.rs:138 | compiler stack |
Algorithms, data structures and design patterns (10)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Plan then replay | design pattern | Every pass only decides (graph to plan, pure); one shared replayer is the only code that builds graphs. | crates/mapal-rewrite/src/plan.rs:65 | rewrite: the fixpoint pipeline, Inlining, Loop lifting, Common-subexpression elimination |
| Fixpoint iteration with round cap | algorithm | Rounds repeat until all plans are empty or 32 rounds, with validation after each rebuild. | crates/mapal-rewrite/src/driver.rs:87 | rewrite: the fixpoint pipeline |
| Value-numbering CSE | algorithm | Operations 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:395 | Common-subexpression elimination |
| Liveness-based DCE | algorithm | Backward reachability from outputs and effects; anything that may trap or diverge is pinned live. | crates/mapal-rewrite/src/graph_rewrites.rs:34 | Dead-code elimination |
| Functor law as rewrite rule | design pattern | Map 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:32 | Map fusion |
| Body substitution (inlining and fusion synthesis) | algorithm | A 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:13 | Replay, Inlining, Map fusion |
| Evaluate at compile time with the oracle | design pattern | Static values are computed by the interpreter itself, so they are exact on every number face. | crates/mapal-rewrite/src/statics.rs:34 | Static folding |
| By-value intake and no-op shortcut | design pattern | The graph is moved in; an all-empty round returns it without a rebuild. | crates/mapal-rewrite/src/driver.rs:70 | rewrite: the fixpoint pipeline |
| Random program generator (testgen) | design pattern | A 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:203 | Rewrite preserves the interpreter's result, Facts agree with the interpreter |
| Rule data table | data structure | The Zip/Enumerate naturality laws kept as a const table. | crates/mapal-rewrite/src/naturality.rs:30 | rewrite: the fixpoint pipeline |
Guarantees of Rewrites
| Guarantee (natural transformation) | What must agree | Checked in |
|---|---|---|
| Rewrite preserves the interpreter's result | Evaluating the graph before and after rewriting gives the same result, traps included. | crates/mapal-rewrite/tests/property.rs:67 |
| Replaying nothing changes nothing | Replaying 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 idempotent | Rewriting 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:1crates/mapal-interp/src/eval.rs:1crates/mapal-interp/src/loops.rs:1crates/mapal-interp/src/value.rs:1crates/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)
| Object | What it is | Defined at | Lives in | Provided by |
|---|---|---|---|---|
| Bound | A printed value's error bound split by source: member rounding, summation order, fma, comparison flip, math builtin. | crates/mapal-interp/src/bound.rs:60 | Vec<Bound> returned by run_bound, one per print | |
| Tape | Record of every float operation of the exact run: operands, partial derivatives, own deviation. | crates/mapal-interp/src/bound.rs:146 | thread-local TAPE (RefCell<Option<Tape>>) during run_bound | |
| EvalCtx | Working state of one function evaluation: value of each object, staged product slots, guard sites, gated morphisms. | crates/mapal-interp/src/eval.rs:20 | compiler heap, one per function call | |
| RunResult / Outcome / Bound | Output text, how it ended, each printed float's composed bound. | crates/mapal-interp/src/lib.rs:40 | compiler heap | Command line |
| RunResult | Outcome plus the printed output text. | crates/mapal-interp/src/lib.rs:33 | returned by value; output is a String | |
| Abort | Internal early exit (Diverged, Trapped, ReadFailed) threaded as the Err side. | crates/mapal-interp/src/value.rs:86 | Result error; read failure message in a thread-local READ_FAILURE | |
| Outcome | How a run ended: Done(value), Diverged, Trapped(kind), ReadFailed(message). | crates/mapal-interp/src/value.rs:61 | returned by value | |
| RValue | A runtime value: scalar, tuple, struct, array (shared), world token with its log, tracked scalar (for bounds), unit. | crates/mapal-interp/src/value.rs:14 | compiler process heap while the oracle runs; arrays in Rc<Vec<RValue>> | |
| TrapKind | DivZero or IndexOob. | crates/mapal-interp/src/value.rs:51 | inside Outcome | |
| Embedded static value | A value the interpreter computed at compile time and spliced into the graph as constants. | crates/mapal-rewrite/src/plan.rs:65 | compiler heap, then constants inside the new graph | Rewrites |
| RValue / interpreter result | The interpreter's value for a program or call, compared before and after a rewrite (floats within tolerance). | crates/mapal-rewrite/tests/property.rs:47 | test heap | Rewrites |
Arrows (5)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| component | RValue (product) → RValue (slot k) | Take a component of a runtime product. | crates/mapal-interp/src/eval/helpers.rs:64 |
| eval_fn | FuncId and RValue (argument) → RValue (result) | Evaluate one function on an argument. | crates/mapal-interp/src/eval.rs:84 |
| native_observable | RunResult → (stdout, exit code) | What the compiled program must print and exit with. | crates/mapal-interp/src/lib.rs:252 |
| render | Value → String | Print a scalar the way the program shows it. | crates/mapal-interp/src/value.rs:113 |
| Abort::into_outcome | Abort → Outcome | Lift an early exit to the public outcome. | crates/mapal-interp/src/value.rs:97 |
Transformations (8)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| run / run_ordered | Flow → Values: (RunResult | functor | Seed the entry function (world token or unit), walk the graph, return the outcome and output; total, never panics. | crates/mapal-interp/src/lib.rs:40 | compiler heap; fuel is a u64 counter passed by &mut |
| eval_fn_within (walk operations in topological order) | Flow Facts: (topo, guard_plan→ Values | process | For 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:107 | EvalCtx.env SecondaryMap<ObjectId, RValue> |
| run_loop (guard-first loop driver) | Flow: (loop SCCFacts: (loop_plan→ Values | process | Per trip: decide and exit first, advance only if continuing, so speculative reads never happen on the exit step. | crates/mapal-interp/src/loops.rs:31 | EvalCtx.env, staging buffers reset per trip |
| Phi handler (gated arms) | Flow Facts: (guard_plan→ Values | process | Arm work that may trap or is heavy runs only when the condition picks that arm. | crates/mapal-interp/src/eval.rs:107 | EvalCtx.guards and EvalCtx.gated |
| eval_values / eval_values_once / static_cone | Flow Facts: (static roots→ Values | process | Evaluate only the cone of values feeding chosen root objects; used to embed compile-time constants. | crates/mapal-interp/src/lib.rs:127 | SecondaryMap of the wanted objects; results Vec<Option<RValue>> |
| run_bound (record tape, reverse sweep) | Flow Facts: (precision_plan, step_algebra→ Values: (Bound | functor | Run 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:170 | thread-local Tape; Bound per print |
| run_weakest | Flow → Values: (RunResult | process | Run with every admitted reduced-precision multiply taken at its coarsest grid, giving the opposite extreme of the oracle. | crates/mapal-interp/src/lib.rs:85 | thread-local WEAKEST flag in eval.rs |
| Math and Narrow ops via ir Native Arith | Values: (scalarTypes → Values: (scalar | process | Evaluate exp/sqrt/sin/cos and narrow rounding with the same definitions a backend prints. | crates/mapal-interp/src/eval.rs:107 | Native<B> in crates/mapal-ir/src/math.rs |
Algorithms, data structures and design patterns (7)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Fuel (step budget) for total evaluation | design pattern | A u64 budget decremented per step so every run halts with Done, Diverged or Trapped. | crates/mapal-interp/src/eval.rs:62 | run / run_ordered, eval_fn_within (walk operations in topological order), eval_values / eval_values_once / static_cone |
| Result as early-exit channel (Abort) | design pattern | Traps, divergence and read failure travel as Err and are lifted once at the entry. | crates/mapal-interp/src/value.rs:86 | run / run_ordered, eval_fn_within (walk operations in topological order) |
| Guard-first loop evaluation | algorithm | Decide and exit cone evaluated before the advance cone. | crates/mapal-interp/src/loops.rs:31 | run_loop (guard-first loop driver) |
| Reverse-mode derivative tape (first-order error composition) | algorithm | Record partial derivatives forward, sweep backward per output to compose deviations along the program. | crates/mapal-interp/src/bound.rs:249 | run_bound (record tape, reverse sweep) |
| Shared immutable arrays (Rc) with staging slots for products | data structure | Arrays are reference counted; products are assembled in staging buffers slot by slot, matching Pair edges. | crates/mapal-interp/src/eval/helpers.rs:74 | eval_fn_within (walk operations in topological order) |
| Cone evaluation (evaluate only what a root reads) | algorithm | Restrict the walk to the set of objects feeding wanted roots. | crates/mapal-interp/src/lib.rs:201 | eval_values / eval_values_once / static_cone |
| Thread-local recorders (tape, weakest flag, read failure) | design pattern | Optional modes switched by scoped thread-local state so the common path has no extra parameters. | crates/mapal-interp/src/bound.rs:170 | run_bound (record tape, reverse sweep), run_weakest |
Guarantees of Interpreter
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:1benches/gpu/calib.cu:1benches/local/place_calib.cu:1benches/local/place_calib_opt.cu:1benches/local/place_calib.sh:1benches/local/place_calib_facts.py:1benches/results/evidence/local-rtx-5080/calib/rtx-5080.calib:1crates/backends/llvm/src/rules.rs:1crates/backends/llvm/src/rung_replay.tsv:1crates/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)
| Object | What it is | Defined at | Lives in | Provided by |
|---|---|---|---|---|
| calibration line | One 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:1 | a 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_* tables | The 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:66 | compiler process: constants in read-only data | |
| CalibSource | Says where the calibration text for this run came from: a file, the committed line, or none. | crates/backends/llvm/src/profile/calib.rs:7 | compiler 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:87 | inside TargetProfile, same place | |
| Caps | What 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:12 | compiler process: field of Gpu | LLVM backend |
| DeviceCost | Mapal'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:10 | compiler process: Option field of Gpu; values come from a constant or the calibration text | LLVM backend |
| DeviceQuery | What the driver reports about device 0 (compute capability, SMs, registers, shared memory, L2, clocks, memory bus). | crates/backends/llvm/src/profile/calib.rs:61 | compiler process stack, built from cuDeviceGetAttribute answers | |
| Gpu | The 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:113 | compiler process: inside TargetProfile (Copy struct, no heap) | LLVM backend |
| MatrixOp / MmaShape / MmaFmt | One 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:79 | compiler process: static tables inside Caps | LLVM backend |
| PlaceFacts | The 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:220 | compiler process: a static table per part (PLACE_RTX_5080 and others) referenced from TargetProfile::place | LLVM backend |
| TargetProfile | One 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:8 | compiler 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 |
| CostOver | A list of optional overrides, one slot per DeviceCost field, read from a calibration line. | crates/backends/llvm/src/profile/device_cost.rs:367 | compiler process stack | |
| Src | A 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:7 | compiler process: inside every Fact |
Arrows (14)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| calib_line | calibration text, key → CostOver | Reads one device's line into numbers. | crates/backends/llvm/src/profile/calib.rs:264 |
| calib_supply | calibration key → calibration text | Finds the calibration text: env file, cache file, then the committed line, or none. | crates/backends/llvm/src/profile/calib.rs:36 |
| caps_of_cc | compute capability → Caps | Turns the compute capability into the instruction abilities once, at the boundary. | crates/backends/llvm/src/profile/matrix.rs:343 |
| native_gpu | device query + calib file → TargetProfile | Query the driver and read measured calibration; never a name lookup. | crates/backends/llvm/src/profile/native.rs:92 |
| resolve | profile name → &TargetProfile | Named profile or detected native; unknown name is an error. | crates/backends/llvm/src/profile/registry.rs:111 |
| with_host | device and host profiles → combined profile | A GPU build also carries its host's CPU facts. | crates/backends/llvm/src/profile/profiles_host.rs:11 |
| Gpu::matrix_op | Gpu, 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_key | DeviceQuery → 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::device | CUDA driver → DeviceQuery | Asks the driver (libcuda opened at run time) for device 0's attributes. | crates/backends/llvm/src/profile/calib.rs:111 |
| DeviceQuery::profile | DeviceQuery, calibration text → TargetProfile | Builds 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_sm | Gpu → rate | The share of memory bandwidth one SM gets. | crates/backends/llvm/src/profile/plan.rs:526 |
| Gpu::l2_keep_bytes | Gpu → bytes | How many bytes of a repeatedly read set the L2 actually keeps. | crates/backends/llvm/src/profile/plan.rs:382 |
| Gpu::warps_per_scheduler | Gpu, grid size → count | How full a grid keeps the chip's schedulers. | crates/backends/llvm/src/profile/plan.rs:539 |
| TargetProfile::gpu | TargetProfile → Gpu (optional) | Picks out the GPU facts, if this is a GPU profile. | crates/backends/llvm/src/profile/target.rs:586 |
Transformations (6)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| Calibration probes | Target: the physical chip→ Target: calibration line | process | Small 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:1 | runs 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 profile | Target: DeviceQueryTarget: calibration line→ Target: TargetProfile | functor | Query 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:92 | compiler process: one TargetProfile leaked into a OnceLock static at first use |
| Ask the driver | Target: CUDA driver→ Target: DeviceQuery | process | Loads libcuda.so.1 at run time and reads attributes. | crates/backends/llvm/src/profile/detect.rs:8 | compiler process stack |
| Find the calibration | Target: calibration key→ Target: calibration text | process | Env file, cache file, committed line in that order. | crates/backends/llvm/src/profile/calib.rs:36 | reads a file from disk; text kept in the process |
| Assemble the profile | Target: DeviceQueryTarget: CostOver→ Target: TargetProfile | functor | Fills Gpu, Caps and DeviceCost; fills the PlaceFacts fields from the calibration's place.* keys. | crates/backends/llvm/src/profile/calib.rs:149 | compiler process heap, then leaked |
| Choose optimization switches from properties | Target: GpuTarget: site fill→ Schedule: GpuRungs | functor | Maps 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:342 | compiler process, pure function evaluated per site while emitting |
Algorithms, data structures and design patterns (8)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Facts carry provenance | design pattern | Every 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:64 | Assemble the profile, Translate the profile |
| Layered fallback for calibration | design pattern | Try the user's file, then the file in the repository, else run with unmeasured numbers. | crates/backends/llvm/src/profile/calib.rs:36 | Find the calibration |
| Capabilities as geometry | design pattern | Instructions are described by what they move and compute, so rules never compare versions. | crates/backends/llvm/src/profile/caps.rs:12 | Assemble the profile |
| Probe sweep to knee | algorithm | Each 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:1 | Calibration probes |
| Static table per part | data structure | A constant struct per known part, plus a lookup by physical key for new ones. | crates/backends/llvm/src/profile/place_rtx_5080.rs:66 | Assemble the profile |
| Threshold between nearest winner and loser | algorithm | Each 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:342 | Choose optimization switches from properties |
| Plan and replay | design pattern | Decisions are stored as data (a tsv of measurements) and a test replays them against the rule code. | crates/backends/llvm/src/rung_replay.tsv:1 | The rules agree with every cited measurement |
| ON/OFF measurement arms | design pattern | Every 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:544 | Choose optimization switches from properties |
Guarantees of Hardware facts and rules
| Guarantee (natural transformation) | What must agree | Checked in |
|---|---|---|
| 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). | crates/backends/llvm/src/rules/native_tests.rs:50 |
| 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. | crates/backends/llvm/src/rules/tests.rs:124 |
| The rules ignore names | Two 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:1crates/mapal-place/src/fact.rs:1crates/mapal-place/src/machine.rs:1crates/mapal-place/src/schedule.rs:1crates/mapal-place/src/lower.rs:1crates/mapal-place/src/space.rs:1crates/mapal-place/src/eval.rs:1crates/mapal-place/src/reuse.rs:1crates/mapal-place/src/lru.rs:1crates/mapal-place/src/search.rs:1crates/backends/llvm/src/place.rs:1crates/backends/llvm/src/place_replay.rs:1crates/backends/llvm/src/place_replay.tsv:1crates/backends/llvm/src/func/gpu.rs:1
Category Machine
The abstract machine the placement search prices: levels of memory, rates, latencies.
Objects (14)
| Object | What it is | Defined at | Lives in |
|---|---|---|---|
| Bound | Which end of the intervals to read: slow, value or fast. | crates/mapal-place/src/fact.rs:52 | compiler process stack |
| Fact<T> | A value with its source tag and a low and high end. | crates/mapal-place/src/fact.rs:64 | inside every numeric field |
| Cache / Keep / Policy | A 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:253 | boxed inside Place::mgmt |
| Cost | A 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:237 | compiler process stack |
| Dispatch | How work reaches executors: slot start timing, launch costs by mode, atomics, zero pass, clock, barriers. | crates/mapal-place/src/machine/prims.rs:116 | field of Machine |
| Exec / ExecKind | A level of compute: device, unit (SM), scheduler, warp group, lane, with how many instances sit under each parent. | crates/mapal-place/src/machine.rs:36 | Vec<Exec> inside Machine |
| Machine | The whole machine: executors, places, capacity groups, unit resources, issue pipes, operations, movers, dispatch and measured primitives. | crates/mapal-place/src/machine.rs:351 | compiler process heap (Vecs); one per part, cached per process |
| Mover | A 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:65 | Vec<Mover> inside Machine |
| Op | One 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:141 | Vec<Op> inside Machine |
| Pipe / Class | How many instructions of a class (math, matrix, shared, global, barrier) a unit issues per clock. | crates/mapal-place/src/machine/prims.rs:25 | Vec<Pipe> inside Machine |
| Place | Somewhere 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:288 | Vec<Place> inside Machine |
| Prim / PrimOf | A 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:222 | Vec<Prim> inside Machine::prims |
| Reach | An executor's link to a place: bandwidth per instance, total bandwidth, loaded latency, transaction size. | crates/mapal-place/src/machine.rs:275 | Vec<Reach> inside Place |
| Resource | A per-unit capacity a running block occupies (registers, threads, slots, scratchpad bytes); occupancy is derived from it. | crates/mapal-place/src/machine.rs:328 | Vec<Resource> inside Machine |
Arrows (8)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| Fact::rate / Fact::cost | Fact, Bound → number | Read a rate at its slow or fast end, a cost at the opposite end. | crates/mapal-place/src/fact.rs:121 |
| Machine::cost | PrimOf, Bound → Cost | A 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::near | PrimOf → neighbouring measured Prim | Finds the closest measured row to borrow when one is missing. | crates/mapal-place/src/machine/cost.rs:185 |
| Machine::occupancy | threads, registers, bytes → slots per unit | How many blocks fit on a unit given what each takes. | crates/mapal-place/src/machine.rs:475 |
| Machine::reach | Place, ExecKind → Reach | How an executor level gets at a place. | crates/mapal-place/src/machine.rs:442 |
| Machine::rows | Machine → Vec<Row> | Lists every numeric fact with its provenance for the evidence report. | crates/mapal-place/src/machine.rs:511 |
| Exec.parent | Exec → Exec | The level above (lane to warp to scheduler to SM to device). | crates/mapal-place/src/machine.rs:36 |
| Place.backing | Place → Place | Where 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)
| Object | What it is | Defined at | Lives in | Provided by |
|---|---|---|---|---|
| Chain | A chain of dependent launches that become one persistent kernel. | crates/backends/llvm/src/func/calls.rs:267 | compiler heap | LLVM backend |
| Block / Slices / Stage | Rows per block, a row cut over blocks, and the staged shared-memory window. | crates/backends/llvm/src/func/flow.rs:204 | compiler heap | LLVM backend |
| UMember / UKind / USrc | A member (fold, cell, or tile), its kind, and where each input comes from. | crates/backends/llvm/src/func/flow.rs:84 | compiler heap | LLVM backend |
| Unit | A row-block group: one launch, rows threads, ordered members, operands, optional slices or stream. | crates/backends/llvm/src/func/flow.rs:105 | compiler heap, inside ResidentPlan.units | LLVM backend |
| Arithmetic | What the kernel computes with: separate mul-add, ordered FMA, TF32/half/split matrix instructions. | crates/backends/llvm/src/func/gpu/launch_rules.rs:8 | compiler stack | LLVM backend |
| Combine | How partial sums are joined: none, split atomic, workspace, stream-K. | crates/backends/llvm/src/func/gpu/launch_rules.rs:89 | field of Launch | LLVM backend |
| Launch | The concrete kernel choice the emitter uses: tile kind, block size, grid, combine, optimization switches. | crates/backends/llvm/src/func/gpu/launch_rules.rs:60 | compiler process stack, Copy | LLVM backend |
| MmaWalk | Tile grid rounds across SMs versus a stream-K walk on the matrix pipes. | crates/backends/llvm/src/func/gpu/mma_plan.rs:389 | compiler stack | LLVM backend |
| SiteCand | One candidate launch of a site's table with its arms and flipped axes. | crates/backends/llvm/src/func/gpu/site_table.rs:18 | compiler heap | LLVM backend |
| SiteTable | A site's candidate table on its way to the launch point. | crates/backends/llvm/src/func/gpu/site_table.rs:28 | compiler heap; constant table in the host module at run time | LLVM backend |
| Refuse | Why a launch was not added to an open group (args, block, smem, occupancy, waves). | crates/backends/llvm/src/func/horizontal.rs:97 | compiler stack; reported in evidence lines | LLVM backend |
| HzGroup | Launches merged side by side or as a persistent chain, with each member's level. | crates/backends/llvm/src/func/horizontal.rs:63 | compiler heap, inside ResidentPlan.hz | LLVM backend |
| Shape | A launch's grid and resource use, the input of the merge rule. | crates/backends/llvm/src/func/horizontal.rs:84 | compiler stack | LLVM backend |
| DevSite | A device site: a tile site or a row fold. | crates/backends/llvm/src/func/resident.rs:136 | compiler heap | LLVM backend |
| Arena | One device allocation per function, with a byte offset for each member whose lifetime allows sharing. | crates/backends/llvm/src/func/resident.rs:469 | compiler heap (plan); at run time one slab in GPU global memory | LLVM backend |
| Batch | A loop whose skippable first trips are written once by one launch before entry. | crates/backends/llvm/src/func/resident.rs:449 | compiler heap | LLVM backend |
| Carry | A loop state kept on the device across trips: merge, next value, views, exit. | crates/backends/llvm/src/func/resident.rs:71 | compiler heap; at run time one device buffer per carry | LLVM backend |
| Cell | A per-cell map run as its own one-thread-per-cell kernel. | crates/backends/llvm/src/func/resident.rs:273 | compiler heap | LLVM backend |
| DeltaUp | An upload that sends only the rows a trip wrote. | crates/backends/llvm/src/func/resident.rs:121 | compiler heap; a first-pass flag slot on the host stack | LLVM backend |
| Epi | A tile with its epilogue cells grouped so the cell work rides on the tile launch. | crates/backends/llvm/src/func/resident.rs:198 | compiler heap | LLVM backend |
| Gen | A producer computed on the device (id, body function, element count). | crates/backends/llvm/src/func/resident.rs:110 | compiler heap | LLVM backend |
| ResidentPlan | The whole decision record of one function: uploads, keeps, device-built producers, carries, arena, units, merged launches. | crates/backends/llvm/src/func/resident.rs:377 | compiler heap, a pure function of Flow, profile and optimization switches; computed before the walk | LLVM backend |
| RetainCell | A 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:315 | compiler heap | LLVM backend |
| Retained | A tile site over a carried array that recomputes only the rows the last trip wrote. | crates/backends/llvm/src/func/retain.rs:29 | compiler heap | LLVM backend |
| Stream | One 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:52 | compiler heap | LLVM backend |
| GpuArms | The user's measurement flags: which optimization switches to force ON or OFF, plus placement search arms. | crates/backends/llvm/src/gpu_arms.rs:544 | compiler process: options passed down from the command line | Hardware facts and rules, LLVM backend |
| GpuRungs | The 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:31 | compiler process: Copy struct inside each Launch | Hardware facts and rules, LLVM backend |
| PLACE_BAND_PM / PLACE_NULL | The 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:18 | constants 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:9 | compiler stack | LLVM backend |
| Placed | The 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:138 | compiler process heap; cached in a thread-local PICKS map keyed by site, part, arms and order | LLVM backend |
| place_replay.tsv | One 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:1 | text file in the repo; read by tests | |
| Face | The 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:12 | compiler process stack | Hardware facts and rules |
| rung_replay.tsv | One 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:1 | text file in the repo; read by a test | Hardware facts and rules |
| Corner | One choice of slow or fast end for each of compute, cache, memory, dispatch; sixteen corners in all. | crates/mapal-place/src/eval/terms.rs:223 | compiler process stack | |
| Flow | One resource of a loop trip: work, rate, latency and bytes in flight. | crates/mapal-place/src/eval/terms.rs:52 | compiler process stack | |
| Terms / Phase | The 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:112 | compiler process heap; one line written into the emitted module as a ; mapal.place comment | |
| Move | How a slot's panels arrive: register loads, async copies, bulk boxes. | crates/mapal-place/src/lower.rs:13 | field of Declared | |
| Declared | What 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:27 | compiler process heap, paired with each candidate | |
| Grid / Order / Reads | A 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:23 | compiler process stack; results memoized in thread-local hash maps | |
| Fold | How free the order of the k sum is: any, fixed grouping, sequential. | crates/mapal-place/src/schedule.rs:10 | inside Site | |
| Traversal / Comb | The 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:96 | inside Schedule | |
| Level / Home / Bind | A 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:78 | inside Schedule::levels | |
| Schedule | One placement: the operation, tile levels with where each operand lives, groups, traversal, launch mode, cache policies, occupancy. | crates/mapal-place/src/schedule.rs:133 | compiler process heap (Vec of levels) | |
| Site | What 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:26 | compiler process stack or heap, built per site | |
| Opts | Search parameters: how many candidates to keep, error band per bounding term, null, traversal kinds allowed. | crates/mapal-place/src/search.rs:37 | compiler process stack | |
| Cand / Ranked / Stats | A 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:117 | compiler process heap | |
| Verdict | The 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:485 | compiler process stack | |
| Wisdom file line | One stored decision: key, site, pick, repetitions, nanoseconds, kernel names. | crates/mapal-rt/gpu/mapal_choice.h:138 | a tab-separated file wisdom-<device>.tsv under MAPAL_WISDOM, XDG_CACHE_HOME or ~/.cache/mapal | Runtime |
| choice_memo | The pick already decided for a table, found by the table's address. | crates/mapal-rt/gpu/mapal_choice.h:125 | a small direct-mapped array in host static memory | Runtime |
| mapal_cand | One 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:41 | a constant table in the emitted host module (56 bytes each; layout declared by SITE_DECL in the backend) | Runtime |
| mapal_site_reg | A 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:54 | the constant array @mapal_sites in the host module | Runtime |
Arrows (44)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| flag apply | CLI flag text → EmitOpts update | Each --gpu-off=name and similar flag toggles one arm. | crates/backends/llvm/src/flags.rs:8 |
| member source | UMember input slot → USrc | Where 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_id | TileSite, profile, contract → u64 id | Content hash naming a kernel so equal sites share one. | crates/backends/llvm/src/func/gpu/split_plan.rs:325 |
| launch_in | TileSite, TargetProfile, Order, arms → Launch | The launch a site gets under an emission's order. | crates/backends/llvm/src/func/gpu/launch_lines.rs:338 |
| launch_split | TileSite, TargetProfile → Launch (split form) | The launch with the k fold cut or streamed. | crates/backends/llvm/src/func/gpu/launch_rules.rs:198 |
| arena offset | ObjectId → byte offset | Where a member sits in the arena slab. | crates/backends/llvm/src/func/resident/arena.rs:181 |
| chain stream | MorphismId → stream number | Which stream each straight-line device site goes on. | crates/backends/llvm/src/func/resident/plan.rs:405 |
| upload / keep / elem | ObjectId → copy decision | Per object: copy in after producer, never copy out, or copy out one element. | crates/backends/llvm/src/func/resident.rs:377 |
| devgen / skip | MorphismId → Gen or skipped | Per producer: build it on the device, or skip it because every reader is device-built. | crates/backends/llvm/src/func/resident.rs:377 |
| free_after | MorphismId → objects freed | Which device buffers die right after this morphism. | crates/backends/llvm/src/func/resident.rs:377 |
| zero_by / zero_after | atomic site → kernel or step that zeroes its output | The kernel or earliest step that clears an atomic site's output bytes. | crates/backends/llvm/src/func/resident.rs:377 |
| launch_of | Schedule → Launch | Turns a placed schedule back into the kernel geometry the emitter lowers. | crates/backends/llvm/src/place/launch.rs:361 |
| lowering_of | Launch → emitter id | Names which emitter a launch belongs to. | crates/backends/llvm/src/place/search.rs:536 |
| machine_of | TargetProfile → Machine | Reads 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_of | Launch → Schedule | Writes 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_of | Launch / Schedule → Schedule / Launch | The rules' launch as a schedule and back. | crates/backends/llvm/src/place/launch.rs:161 |
| site_of | TileSite (Flow facts) → Site | Reads a dataflow tile site as extents, operand bytes, fold freedom, allowed formats. | crates/backends/llvm/src/place/site.rs:11 |
| table_rungs | TileSite, profile, arms → GpuRungs | The optimization switches the site's table carries beyond the launch. | crates/backends/llvm/src/place/launch.rs:129 |
| warm_of | TileSite → which operands are already resident | Reads the residence facts to know operands kept from the previous call. | crates/backends/llvm/src/place/site.rs:58 |
| Emitter::declare | Machine, Site, Schedule → Declared | Each kernel family states its footprint and per-trip instruction counts. | crates/backends/llvm/src/place/lowering.rs:6 |
| grid_spread_pm | blocks, SMs → per mille | How evenly a grid spreads across SMs. | crates/backends/llvm/src/rules.rs:74 |
| row_split_pays | Gpu, row bytes → bool | Split a long row fold across blocks. | crates/backends/llvm/src/rules.rs:169 |
| rungs | Gpu, warps per scheduler, Face → GpuRungs | The 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_pays | Gpu, tile → bool | Does a split-precision matrix product beat the plain FMA tile at its achieved rate. | crates/backends/llvm/src/rules.rs:229 |
| stream_ld_pays | Gpu, bytes read once → bool | Mark 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_pays | Gpu, operand bytes → bool | Does stream-K with an epilogue pay. | crates/backends/llvm/src/rules.rs:134 |
| vec_cells_pay | Gpu, grids → bool | Do vector cells beat scalar ones given the DRAM share. | crates/backends/llvm/src/rules.rs:91 |
| wide_fma_pays | Gpu, blocks, wave → bool | Does the wider FMA tile win at this grid size. | crates/backends/llvm/src/rules.rs:59 |
| ws_persist_pays | Gpu, tiles, stages → bool | Does a persistent warp-specialized kernel pay. | crates/backends/llvm/src/rules.rs:312 |
| Lowering::slots | Machine, Site, op → Vec<Schedule> | A lowering lists its tile schedules that fit the chip's capacities. | crates/mapal-place/src/lower.rs:125 |
| Lowering::declare | Machine, Site, Schedule → Declared or Refusal | Checks constraints and gives the counts. | crates/mapal-place/src/lower.rs:125 |
| Lowering::search_domain / point | prefix of coordinates → allowed values / Schedule | Exposes the schedule space as coordinates for the branch and bound. | crates/mapal-place/src/lower.rs:125 |
| lru_bytes | trace, keep → Reads | Exact LRU misses over a trace. | crates/mapal-place/src/lru.rs:188 |
| trace | Grid → access trace of slices | The exact order slices are touched, for the simulator. | crates/mapal-place/src/lru.rs:22 |
| reads | Grid, keep bytes → Reads | Bytes a cache misses on a grid's traversal. | crates/mapal-place/src/reuse.rs:101 |
| Schedule::plan | Schedule → String | A short readable name of the placement. | crates/mapal-place/src/schedule.rs:201 |
| Schedule::tiles / panels | Schedule, Site → counts | How many output tiles and k panels a placement makes. | crates/mapal-place/src/schedule.rs:193 |
| ops | Machine, Site → operations the site's formats admit | Step 1 of the space: which instructions can run this site. | crates/mapal-place/src/space.rs:18 |
| traversals | Schedule, Declared → Vec<Traversal> | Step 4: the traversals and their parameters over the slots a footprint allows. | crates/mapal-place/src/space.rs:51 |
| choice_lookup | table bytes, module text → key and stored pick | Hash the table and the module text; look it up in the wisdom file. | crates/mapal-rt/gpu/mapal_choice.h:227 |
| choice_site | table, timing hooks → pick index | The decision rule shared by device and emulator. | crates/mapal-rt/gpu/mapal_choice.h:279 |
| mapal_gpu_site | site, table, pointers → one chosen launch | Run 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_sites | site_reg table → registered tables | The host hands its tables to the runtime before init. | crates/mapal-rt/gpu/mapal_gpu_init.inc:33 |
| sites_resolve / choice_preset | site_reg → decided pick, ready kernels | At 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)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| Generate candidate schedules | Machine Machine: SiteMachine: Lowering→ Schedule: Schedule + Declared | functor | From the machine's facts and the site, list operations, then tiles, then traversals, never from a fixed table. | crates/mapal-place/src/space.rs:129 | compiler process heap, temporary Vec |
| Price a schedule | Machine Machine: SiteSchedule Machine: Declared→ Schedule: Terms (nanoseconds | functor | One 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:35 | compiler process, pure function |
| A trip's steady state | Flow: list→ Machine: ns per trip | process | The 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:92 | compiler process stack |
| Pipeline calculation | Machine: tripsMachine: compute flowsMachine: mover flowsMachine: fillMachine: serial→ Machine: ns | process | fill + trips x (slowest of compute and movement + barriers) + drain. | crates/mapal-place/src/eval/terms.rs:102 | compiler process stack |
| Count misses by distinct bytes | Machine: GridMachine: keep→ Machine: Reads | functor | Closed forms for lockstep waves, walks and staggered starts, counting distinct slices rather than bytes requested. | crates/mapal-place/src/reuse.rs:101 | compiler process; memoized in thread-local hash maps |
| Zero pass, reduce, launches | Schedule Machine → Machine: ns | process | Costs outside the loop: zeroing the output, workspace reduce, launches. | crates/mapal-place/src/eval.rs:55 | compiler process stack |
| Admissible floor | Machine Machine: SiteSchedule → Machine: Terms (lower bound) | functor | The 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:51 | compiler process |
| Evaluate at every corner | Machine: Cand→ Machine: Cand.corners | process | Prices a candidate with each fact group at its slow or fast end, sixteen times. | crates/mapal-place/src/search.rs:401 | compiler process heap |
| Branch and bound search | Machine Machine: SiteMachine: LoweringsMachine: OptsMachine: incumbentMachine: gate→ Machine: Ranked | process | Walks coordinate prefixes in a fixed order and cuts any prefix whose admissible bound is worse than the k-th best so far; the best go through a gate, then are priced at every corner and the minimax pick is taken. made of: Tile bound, Point bound, Post-lowering gate, Evaluate at every corner, Minimax verdict | crates/mapal-place/src/search.rs:496 | compiler process; Best keeps a bounded top list |
| Tile bound | Machine Machine: SiteMachine: opMachine: bmMachine: bn→ Machine: ns lower bound | process | Cheapest any schedule with this slot tile can be: peak compute and the panel stream. | crates/mapal-place/src/search.rs:138 | compiler process stack |
| Point bound | Schedule Machine: Declared→ Machine: ns lower bound | process | Compute at the efficiency this footprint's occupancy reaches. | crates/mapal-place/src/search.rs:192 | compiler process stack |
| Post-lowering gate | Machine: Cand→ Machine: ok or refusal | process | Checks 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:496 | closure called during search |
| Minimax verdict | Machine: times per candidate at valueMachine: times at every corner→ Machine: Verdict | process | Picks 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:420 | compiler process stack |
| Translate the profile | Target: TargetProfile→ Machine: Machine | functor | Executors, 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:7 | compiler process heap; cached per part in a thread-local MACHINES map |
| Place one site | Flow: TileSiteTarget: TargetProfileMachine: rules' Launch→ Schedule: Placed | process | Translates 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:291 | compiler process; result memoized in thread-local PICKS |
| Translate the site | Flow: TileSite→ Machine: Site | functor | Reads the dataflow facts into placement's site. | crates/backends/llvm/src/place/site.rs:11 | compiler process stack |
| Lower to check a candidate | Schedule → Machine: emitted device text or refusal | process | Turns 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:219 | compiler process; the ptxas arm writes temp files and runs llc and ptxas |
| Record the pick | Machine: Placed→ Code: ; mapal.place comment | process | Writes the chosen plan, times at three bounds, counters and terms into the module text. | crates/backends/llvm/src/place/search.rs:291 | a comment line inside the emitted device module |
| Placement at launch time | Machine: rules' LaunchMachine: order→ Machine: Launch | process | Called 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:435 | compiler process; called from func/gpu.rs launch_in and launch_for |
Algorithms, data structures and design patterns (17)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Branch and bound | algorithm | Search with an admissible lower bound that prunes prefixes and points. | crates/mapal-place/src/search.rs:496 | Branch and bound search |
| Minimax regret over intervals | algorithm | Choose the candidate whose largest regret at any corner of the fact intervals is smallest. | crates/mapal-place/src/search.rs:420 | Minimax verdict |
| Exact LRU trace simulation | algorithm | Counts misses of a line-granular LRU using a Fenwick tree over distinct bytes since last use. | crates/mapal-place/src/lru.rs:188 | The closed form equals the LRU simulation |
| Fenwick tree | data structure | A binary indexed tree for prefix sums used by the LRU simulator. | crates/mapal-place/src/lru.rs:162 | The closed form equals the LRU simulation |
| Three-gap progression | algorithm | The 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:11 | Count misses by distinct bytes |
| Closed-form reuse by interval unions | algorithm | Misses by distinct bytes over waves and walk windows, linear instead of simulated. | crates/mapal-place/src/reuse/cross.rs:118 | Count misses by distinct bytes |
| Memo caches in thread locals | design pattern | Pure functions of a grid are memoized in thread-local maps and cleared at a size cap. | crates/mapal-place/src/reuse.rs:101 | Count misses by distinct bytes |
| Little's law flow | algorithm | A 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:52 | A trip's steady state |
| Facts with intervals | design pattern | Every machine number has a low, value and high; evaluation at the ends makes uncertain picks visible. | crates/mapal-place/src/fact.rs:64 | Evaluate at every corner, Minimax verdict |
| Lowering as a trait | design pattern | The backend supplies its kernels as a Lowering that declares constraints and counts; the search is generic over them. | crates/mapal-place/src/lower.rs:125 | Generate candidate schedules, Branch and bound search |
| Incumbent with error band | design pattern | The 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:37 | Branch and bound search |
| Incumbent and candidate | design pattern | The 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:252 | Place one site |
| Memo by search key | design pattern | A 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:252 | Place one site |
| Scoped guards (RAII) | design pattern | WarmScope, ColScope and OrderScope set per-compile context and restore it when dropped. | crates/backends/llvm/src/place/site.rs:97 | Placement at launch time |
| Forced launch for lowering | design pattern | A 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:70 | Lower to check a candidate |
| Plan and replay | design pattern | Measured arms are stored as data and every change is re-scored against them. | crates/backends/llvm/src/place_replay.tsv:1 | The pick agrees with the measured winner, The error band is the replay's residuals |
| Coordinate domains | data structure | A 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:76 | Branch and bound search |
Guarantees of Machine model
| Guarantee (natural transformation) | What must agree | Checked in |
|---|---|---|
| Search equals exhaustive | For 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 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. | crates/mapal-place/tests/props.rs:69 |
| 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. | crates/mapal-place/tests/props.rs:322 |
| The pick does not depend on enumeration order | Reversing 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 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. | crates/backends/llvm/src/place_replay.rs:455 |
| The floor is admissible on every replay arm | For 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 holds | The 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 residuals | The 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:1crates/backends/llvm/src/module.rs:1crates/backends/llvm/src/ty.rs:1crates/backends/llvm/src/loops.rs:1crates/backends/llvm/src/math.rs:1crates/backends/llvm/src/narrow.rs:1crates/backends/llvm/src/reuse.rs:1crates/backends/llvm/src/func/mod.rs:1crates/backends/llvm/src/func/drive.rs:1crates/backends/llvm/src/func/ops.rs:1crates/backends/llvm/src/func/core.rs:1crates/backends/llvm/src/func/frame.rs:1crates/backends/llvm/src/func/bulk.rs:1crates/backends/llvm/src/func/tile.rs:1crates/backends/llvm/src/func/trio.rs:1crates/backends/llvm/src/func/vec.rs:1crates/backends/llvm/src/func/packed.rs:1crates/backends/llvm/src/func/window.rs:1crates/backends/llvm/src/func/conv.rs:1crates/backends/llvm/src/func/sme.rs:1crates/backends/llvm/src/func/hostpar.rs:1crates/backends/llvm/src/func/resident.rs:1crates/backends/llvm/src/func/retain.rs:1crates/backends/llvm/src/func/rowfold.rs:1crates/backends/llvm/src/func/gpu.rs:1crates/backends/llvm/src/profile.rs:1crates/backends/llvm/src/func/flow.rs:1crates/backends/llvm/src/func/stream.rs:1crates/backends/llvm/src/func/horizontal.rs:1crates/backends/llvm/src/func/calls.rs:1crates/backends/llvm/src/func/zero.rs:1crates/backends/llvm/src/rules.rs:1crates/backends/llvm/src/flags.rs:1crates/backends/llvm/src/place.rs:1crates/backends/llvm/src/place_replay.rs:1
Category Code
Generated programs: LLVM text, device modules, PTX, object files and executables.
Objects (42)
| Object | What it is | Defined at | Lives in | Provided by |
|---|---|---|---|---|
| ArenaPlan / ArenaKey | Offset of each buffer in the function's one zone and its capacity. | crates/backends/cuda/src/arena.rs:61 | compiler heap, a pure function of the graph | CUDA backend |
| FnEmit (CUDA) | Per-function host-side emission state. | crates/backends/cuda/src/func.rs:69 | compiler heap | CUDA backend |
| KernelSet | Kernels emitted for a function, deduplicated by structural shape. | crates/backends/cuda/src/kernel/kernels.rs:98 | compiler heap | CUDA backend |
| Qualifiers / FnQual | Host, device or both for each function. | crates/backends/cuda/src/kernel.rs:94 | compiler heap | CUDA backend |
| Site | A launch-form bulk operation and its kernel name k<fn>_<site>. | crates/backends/cuda/src/kernel/sites.rs:198 | compiler heap | CUDA backend |
| TrapCaps | Which functions and launches can trap, so only they get a readback check. | crates/backends/cuda/src/kernel.rs:262 | compiler heap | CUDA backend |
| EmitError (CUDA) | Unsupported feature with a SourceLoc, or internal. | crates/backends/cuda/src/lib.rs:74 | compiler stack | CUDA backend |
| CUDA translation unit | The .cu text; the String is the artifact. | crates/backends/cuda/src/lib.rs:111 | compiler heap String; later a file on the GPU box | CUDA backend |
| EmitOpts (CUDA) | Only a perf-timing switch. | crates/backends/cuda/src/lib.rs:87 | compiler stack | CUDA backend |
| ProdStruct | A struct generated for a product type. | crates/backends/cuda/src/module.rs:302 | compiler heap; a struct definition in the .cu | CUDA backend |
| @mapal_gsync | The grid barrier used between levels of a persistent kernel. | crates/backends/llvm/src/func/calls/kernel.rs:13 | device function in the device module; barrier counter in GPU global memory | |
| UnitGen | Builder for the kernel text of a unit. | crates/backends/llvm/src/func/flow.rs:443 | compiler heap, short-lived | |
| UnitKernel | Kernel text of one unit plus the helper bodies it calls. | crates/backends/llvm/src/func/flow.rs:383 | compiler heap | |
| LoopBuf | How 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:313 | compiler heap, decided before the walk | |
| Root | Whose bytes a view points at: an object, a loop-state position, or outside the function. | crates/backends/llvm/src/func/frame.rs:337 | compiler heap, map keys | |
| Loop | A canonical loop of the function: its LoopPlan and the set of morphisms in its body. | crates/backends/llvm/src/func/frame.rs:328 | compiler heap, Vec inside FnEmit | |
| ParOrder | For the parallel entry: which task each morphism belongs to and which tasks come before which. | crates/backends/llvm/src/func/frame.rs:346 | compiler heap | |
| %mapal_site_reg | Registry row of a table, handed to the runtime before init. | crates/backends/llvm/src/func/gpu.rs:160 | private constant @mapal_sites in the host module | |
| %mapal_cand | One 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:8 | constant table in the host module; C twin read by the runtime | |
| device module text | The nvptx64 LLVM unit: one kernel per live site, cell, generator, row fold, unit. | crates/backends/llvm/src/func/gpu/device_text.rs:9 | compiler heap String; <exe>.dev.ll on disk | |
| CellGeo | Grid and shape of a one-thread-per-cell kernel. | crates/backends/llvm/src/func/gpu/cell_kernels.rs:270 | compiler stack | |
| EpiSite / EpiKernel | A tile kernel with epilogue cells folded into it. | crates/backends/llvm/src/func/gpu/epi_rowfold.rs:73 | compiler heap | |
| Kernel text builder | String builder for one kernel, separate from the host function around the site. | crates/backends/llvm/src/func/gpu/kernel_geom.rs:580 | compiler heap, short-lived | |
| HzSpec | Parsed merged-launch description read back from the host text. | crates/backends/llvm/src/func/horizontal/device.rs:8 | compiler heap | |
| FnAttrs | Per 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:40 | compiler 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:254 | compiler heap, one per function, dropped after emit_ordered returns its text | |
| HostEmit | Where the host waits for tasks: checkpoints, pinned tasks, waits that must fire before a loop. | crates/backends/llvm/src/func/mod.rs:240 | compiler heap, inside FnEmit | |
| TileCtx | The per-site numbers a CPU matrix tile is emitted with: tile sizes, packing, offsets. | crates/backends/llvm/src/func/mod.rs:705 | compiler 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:93 | compiler stack; carries a SourceLoc (Diagnostics) | |
| Order | How a tile's sum over k may be ordered: sequential, fixed split, or free. | crates/backends/llvm/src/opts.rs:22 | compiler stack | |
| ; mapal.* comment lines | Evidence lines in the module text (plan, host, ptx) read by the checker scripts. | crates/backends/llvm/src/emit.rs:172 | comments inside .ll text | |
| Emission | Host LLVM IR text, optional device LLVM IR, resolved profile name, fold orders. | crates/backends/llvm/src/opts.rs:198 | compiler heap Strings | Command 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:48 | compiler stack (Copy struct) | |
| FoldOrder | A split fold compiled in fixed order, kept so the interpreter can replay the same grouping. | crates/backends/llvm/src/opts.rs:40 | compiler heap, Vec inside Emission | |
| StrGlobal | One string literal turned into a private LLVM global with its byte length. | crates/backends/llvm/src/module.rs:12 | compiler heap: SecondaryMap<ObjectId, StrGlobal>; at run time a constant in the module's read-only data | |
| Ptx | The PTX ISA version and SM a module declares and llc is told by -mattr. | crates/backends/llvm/src/profile/caps.rs:80 | compiler stack; a ; mapal.ptx comment | |
| Reuse | How a tile operand is reused across the i axis (new row each step, same row, shifting window). | crates/backends/llvm/src/reuse.rs:27 | compiler stack | |
| mapal_gpu.c / mapal_choice.h as embedded text | The C runtime and its header are embedded into the mapal binary and written next to each GPU build. | crates/mapal-cli/src/main.rs:378 | include_str! in the mapal executable; written to <exe>.mapal_gpu.c | Runtime |
| PTX file | The device program made by opt and llc. | crates/mapal-cli/src/main.rs:378 | disk <exe>.ptx; its path goes to the program in MAPAL_PTX | Command line |
| Executable | The linked native program. | crates/mapal-cli/src/main.rs:378 | disk | Command line |
| libmapal_rt.a | The Rust runtime as a static library. | crates/mapal-rt/Cargo.toml:1 | file in target/<profile>/ next to the mapal binary | Runtime |
| zero_ptx | PTX text of the runtime's own zero-fill kernel. | crates/mapal-rt/gpu/mapal_gpu_fills.inc:39 | a static string in the C runtime; loaded to the device at init | Runtime |
Arrows (17)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| arena offset | ArenaKey → byte offset | 256-byte aligned offset within the zone. | crates/backends/cuda/src/arena.rs:70 |
| collect_sites | FuncId → Vec<Site> | Launch-form bulk operations in topological order. | crates/backends/cuda/src/kernel/sites.rs:222 |
| lower_ty | Ty (Types) → C++ type text | Mapal type to CUDA C++ type. | crates/backends/cuda/src/ty.rs:42 |
| kernel_name | u64 id → kernel symbol | Deterministic kernel name. | crates/backends/llvm/src/func/gpu/epi_rowfold.rs:84 |
| site_registry | host text → @mapal_sites constant | One registry row per distinct table the host launches. | crates/backends/llvm/src/func/gpu.rs:124 |
| compose | member kernel texts → merged kernel text | Joins member kernels into one grid, each on its own block range. | crates/backends/llvm/src/func/horizontal/device.rs:248 |
| attrs | FuncId (Flow) → clean / loopy flags | Which functions may be marked readonly nounwind (willreturn when loop-free). | crates/backends/llvm/src/func/mod.rs:46 |
| slot | ObjectId (Flow) → LLVM alloca name | Each materialized object has one stack slot; erased objects (tokens, unit) have none. | crates/backends/llvm/src/func/mod.rs:254 |
| fnames | FuncId (Flow) → LLVM function name | The entry becomes @mapal_main, every other function @fn<ordinal>, so output is deterministic. | crates/backends/llvm/src/emit.rs:217 |
| collect_str_globals | CategoryIr (Flow) → StrGlobal per string object | One global per string literal object. | crates/backends/llvm/src/module.rs:299 |
| i_reuse | TileSite, TileRead (Facts) → Reuse | Classifies how an operand moves across tile rows. | crates/backends/llvm/src/reuse.rs:53 |
| mark / pack of capture paths | Ty (Types) → array pointer paths | Which arrays inside a function input arrive by address. | crates/backends/llvm/src/ty.rs:67 |
| lower_ty | Ty (Types) → LLVM type text | A Mapal type becomes the LLVM type string of its slot. | crates/backends/llvm/src/ty.rs:23 |
| emit | CategoryIr → Emission | Call the LLVM emitter; turn an Unsupported error into a source position message. | crates/mapal-cli/src/main.rs:273 |
| write | text → file | Write a side file. | crates/mapal-cli/src/main.rs:317 |
| scan PTX for entries | PTX text → fn_entry table | Find every kernel name and resolve it once at load. | crates/mapal-rt/gpu/mapal_gpu_modscan.inc:166 |
| scan PTX for tensor-map recipes | PTX text → tmap_e table | Read 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)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| emit_detailed | Flow: CategoryIr (Flow)Code: EmitOptsTarget: TargetProfile (Target)→ Code: Emission | process | The 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:21 | compiler process, pure over its inputs (profile is an explicit input) |
| emit_module | Flow: CategoryIr (Flow)→ Code: Emission.text (Code) | functor | Flow 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:217 | compiler heap; output String |
| FnEmit::emit_ordered | Flow: FuncDef (Flow)→ Code: LLVM function text (Code) | functor | One function: allocate slots, walk morphisms in topological order, then return and free. made of: emit_morphism | crates/backends/llvm/src/func/drive.rs:130 | compiler heap |
| emit_morphism | Flow: Operation (Flow)→ Code: LLVM instructions (Code) | functor | The operation table: each Flow operation becomes its instructions, applied one morphism at a time. | crates/backends/llvm/src/func/ops.rs:15 | compiler heap |
| emit_loop | Facts: LoopPlan (Facts)→ Code: header / advance / exit blocks (Code) | functor | A canonical loop becomes guard-first branches: decide cone, branch, advance cone, back edge. | crates/backends/llvm/src/loops.rs:22 | compiler heap |
| emit_parallel | Facts: PathPlan (Facts)→ Code: task functions + mapal_par_* calls (Code) | process | Splits independent paths into tasks launched on the mapal-rt pool and waits where the plan says. | crates/backends/llvm/src/func/drive/parallel.rs:6 | emitted code runs on host threads; handle on host heap |
| emit_tiled_map (tile ladder) | Facts: TileSite (Facts)→ Code: CPU tile loop nest (Code) | functor | Picks 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:36 | compiler heap |
| emit_tiled_map_blocked | Code: TileSite→ Code: register-blocked nest | functor | Rows blocked in registers so one b load serves several rows. | crates/backends/llvm/src/func/tile.rs:402 | compiler heap |
| emit_tiled_map_blocked_1d | Code: TileSite→ Code: window nest | functor | The dual for 1-D windows such as FIR: blocks over lanes. | crates/backends/llvm/src/func/window.rs:18 | compiler heap |
| emit_tiled_map_conv | Code: TileSite→ Code: unrolled tap nest | functor | Conv micro-kernel with the k split constant-folded. | crates/backends/llvm/src/func/conv.rs:16 | compiler heap |
| emit_tiled_map_sme | Code: TileSite→ Code: SME streaming-mode tile | functor | ARM streaming matrix unit realization of a tile. | crates/backends/llvm/src/func/sme.rs:155 | compiler heap |
Algorithms, data structures and design patterns (8)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Slot per object, mem2reg left to LLVM | design pattern | Every value gets a stack cell written once; LLVM turns them into registers. | crates/backends/llvm/src/func/mod.rs:254 | FnEmit::emit_ordered, emit_morphism |
| Guard-first loop CFG | design pattern | The loop header decides first, so the exit trip still runs the decide cone. | crates/backends/llvm/src/loops.rs:22 | emit_loop |
| Fixpoint over the call graph (attribute capability) | algorithm | A function is clean only if every callee is clean; loops block willreturn. | crates/backends/llvm/src/func/mod.rs:46 | FnEmit::emit_ordered |
| Arena of typed ids (SecondaryMap) | data structure | Per-object and per-morphism side tables keyed by slotmap ids. | crates/backends/llvm/src/func/mod.rs:254 | emit_module, FnEmit::emit_ordered |
| Declare only what is used | design pattern | Runtime declarations are added by searching the emitted text for the call. | crates/backends/llvm/src/emit.rs:217 | emit_module |
| Strategy ladder with a predicate per optimization switch | design pattern | Each 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:526 | emit_tiled_map (tile ladder) |
| Loop buffer colouring | algorithm | Next-state bytes take a spare buffer not read while they are written. | crates/backends/llvm/src/func/frame/loop_buffers.rs:52 | emit_loop |
| Text builder as the artifact | design pattern | The String is the translation unit; no intermediate LLVM object model. | crates/backends/llvm/src/opts.rs:198 | emit_module |
GPU memory residency
Which values live on the device, when they are copied or freed, and how device buffers share memory.
Transformations (9)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| resident_plan | Facts: tile_plan, last_use_plan, path_plan, loop_plan, unchanged_plan, access_plan (Facts→ Schedule: ResidentPlan (Schedule) | functor | Reads 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:7 | compiler heap |
| placement | Facts: TileSite set (Facts)→ Code: device / host choice per site | functor | Per tile site: device or host, by the cost rules and the machine facts. | crates/backends/llvm/src/func/gpu/placement.rs:69 | compiler heap |
| chains | Facts: access_plan edges (Facts)→ Code: stream per site, uploads per chain | functor | Independent sites go on different streams; uploads ride the chain that reads them. | crates/backends/llvm/src/func/resident/plan.rs:405 | compiler heap |
| arena | Facts: last_use_plan births and deaths (Facts)→ Code: Arena offsets | functor | Lifetime colouring packs buffers into one slab. | crates/backends/llvm/src/func/resident/arena.rs:52 | compiler heap |
| color / color_by | Code: (birth, death, bytes) intervals→ Code: offsets, total bytes | process | First-fit interval colouring. | crates/backends/llvm/src/func/resident.rs:486 | compiler stack |
| emit_site_resident | Code: DevSite, ResidentPlan→ Code: host calls: alloc, h2d, launch, d2h (Code) | process | Emits the host-side calls that run one device site. | crates/backends/llvm/src/func/resident/emit_site.rs:259 | emitted code runs on host; effects on GPU |
| row folds on device | Facts: RowFoldSite (Facts)→ Code: device row-fold launch | functor | A 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:1 | compiler heap |
| retained_sites | Facts: Delta (Facts)→ Code: Retained | functor | Inside a loop recompute only the rows the previous trip wrote. | crates/backends/llvm/src/func/retain.rs:48 | compiler heap |
| host-par | Code: split bulk sites on a GPU build→ Code: pool tasks | functor | Host-placed bulk work in a GPU build runs on the CPU task pool. | crates/backends/llvm/src/func/hostpar.rs:1 | host threads |
Algorithms, data structures and design patterns (4)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Plan then replay | design pattern | A pure plan record is computed first; emission only reads it. | crates/backends/llvm/src/func/resident.rs:377 | resident_plan, emit_site_resident |
| First-fit interval colouring | algorithm | Buffers with disjoint lifetimes share bytes. | crates/backends/llvm/src/func/resident.rs:486 | color / color_by, arena |
| Delta transfer | design pattern | Only the rows a trip wrote are uploaded or recomputed. | crates/backends/llvm/src/func/resident.rs:121 | retained_sites |
| Lazy allocation through a slot | design pattern | The runtime fills the slot on first use, so the host emits no branch. | crates/mapal-rt/gpu/mapal_gpu_memory.inc:46 | emit_site_resident |
GPU kernels
Kernels, the device module, and the table of candidate kernels a program picks from when it loads.
Transformations (9)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| launch_in | Facts: TileSite (Facts)Target: TargetProfile (Target)→ Schedule: Launch (Schedule) | functor | Chooses a kernel and its grid from the site and the hardware properties. | crates/backends/llvm/src/func/gpu/launch_lines.rs:338 | compiler heap |
| site_cands | Code: TileSiteCode: Launch→ Code: Vec<SiteCand> | functor | A table of candidate launches, the rules' choice first. | crates/backends/llvm/src/func/gpu/site_table.rs:105 | compiler heap |
| device_module | Code: Launch, cells, gens, epis, units, rowfolds→ Code: device module text (Code) | functor | Collects every live kernel and writes the nvptx module. made of: lowered_text / Kernel | crates/backends/llvm/src/func/gpu/device_text.rs:9 | compiler heap |
| lowered_text / Kernel | Code: Launch + TileSite→ Code: kernel LLVM text | functor | Writes one tile kernel: panel loops, FMA or matrix instructions, epilogue. | crates/backends/llvm/src/func/gpu/kernel_geom.rs:539 | compiler heap |
| cell_kernel_text | Schedule: Cell (Schedule)→ Code: cell kernel text | functor | One thread per output cell, the host's own body text. | crates/backends/llvm/src/func/gpu/cell_kernels.rs:90 | compiler heap |
| site_call | Code: SiteTable→ Code: call @mapal_gpu_site | process | Emits the host call with the table constant. | crates/backends/llvm/src/func/gpu/emit_site.rs:10 | emitted host code |
| init_call | Code: host rungs→ Code: call @mapal_gpu_init(flags) | process | First call of main: hands the runtime its flags after registering site tables. | crates/backends/llvm/src/func/gpu.rs:97 | emitted host code |
| opt then llc | Code: device module text→ Code: PTX file | process | opt -O3 then llc for the profile's arch, with the declared PTX attribute. | crates/mapal-cli/src/main.rs:378 | external tools; files <exe>.dev.ll, .dev.opt.ll, .ptx |
| load-time dispatch | Code: @mapal_sitesCode: PTX→ Code: picked candidate per site | process | At module load the runtime resolves each table to one candidate from shared-memory limits and occupancy. | crates/mapal-rt/gpu/mapal_gpu_init.inc:33 | host heap in the runtime |
Algorithms, data structures and design patterns (5)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Candidate table, chosen at load | design pattern | Compile time lists launches; the runtime picks one from device limits. | crates/backends/llvm/src/func/gpu/site_table.rs:28 | site_cands, site_call, load-time dispatch |
| Content-hashed kernel ids | algorithm | FNV hash of body and profile names a kernel so equal kernels merge. | crates/backends/llvm/src/func/gpu/site_table.rs:256 | device_module |
| Rule table over hardware properties | design pattern | Choices read geometry (SMs, registers, L2, bandwidth), never a part name. | crates/backends/llvm/src/rules.rs:342 | launch_in |
| Stream-K / split-K | algorithm | Cut the k fold across blocks, add partials atomically or via workspace. | crates/backends/llvm/src/func/gpu/launch_rules.rs:89 | launch_in, lowered_text / Kernel |
| Software-pipelined panels | algorithm | Next panel loads while this one computes (cp.async, TMA). | crates/backends/llvm/src/func/gpu/kernel_geom.rs:580 | lowered_text / Kernel |
Merged launches
Row-block units, one-pass streaming, merged launches and zero-fill folding.
Transformations (9)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| unit_of (flow) | Facts: UnitGroup, footprint_plan, Reach (Facts)→ Schedule: Unit (Schedule) | functor | A 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:289 | compiler heap |
| block_choice / geo | Code: UnitCode: TargetProfile→ Code: Block, Geo | functor | Rows 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:329 | compiler heap |
| unit_kernel | Code: Unit→ Code: UnitKernel (Code) | functor | One 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:8 | compiler heap |
| stream_geo | Facts: StreamGroup (Facts)→ Code: Stream, Geo | functor | Walks one axis in windows with running max and sum so axis-wide values are never stored. | crates/backends/llvm/src/func/stream.rs:429 | compiler heap |
| mma_fmt | Code: Unit members, roles, Gpu→ Code: matrix format or none | functor | Whether every product in the stream fits one warp matrix instruction. | crates/backends/llvm/src/func/stream.rs:97 | compiler stack |
| side_by_side | Code: Vec<Shape>Code: Gpu→ Code: merged blocks or Refuse | functor | Whether launches with no hazard between them fit one grid at no loss in waves. | crates/backends/llvm/src/func/horizontal.rs:150 | compiler stack |
| hz_launch | Code: HzGroup→ Code: one merged launch call | process | Captures each member's launch and issues the group after its last member. | crates/backends/llvm/src/func/horizontal/emit.rs:396 | emitted host code |
| persistent_fit / chain_ns | Code: levels of ShapesCode: Gpu→ Code: grid size or Refuse; time | functor | A chain is one co-resident kernel when it fits and beats separate launches. | crates/backends/llvm/src/func/calls.rs:80 | compiler stack |
| zero-fold / zero-hoist | Facts: access_plan hazards (Facts)Code: atomic sites→ Code: zero_by, zero_after | functor | A 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:645 | compiler heap |
Algorithms, data structures and design patterns (6)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Footprint rule (producer cells read lie inside the unit) | design pattern | Group membership is decided only by what each work unit reads, not by an operator name. | crates/backends/llvm/src/func/flow/units.rs:289 | unit_of (flow) |
| Online softmax / running rescale | algorithm | A running maximum and sum are rescaled as windows arrive. | crates/backends/llvm/src/func/stream.rs:52 | stream_geo |
| Tree and warp-shuffle reduction | algorithm | Row totals by tree in shared memory or by shuffles. | crates/backends/llvm/src/func/flow/gen_slices.rs:322 | unit_kernel |
| Hazard graph (RAW/WAR/WAW) as the merge test | design pattern | Launches merge only if the access plan leaves them unordered. | crates/backends/llvm/src/func/horizontal.rs:150 | side_by_side, persistent_fit / chain_ns |
| Grid barrier | algorithm | A level barrier inside a persistent kernel. | crates/backends/llvm/src/func/calls/kernel.rs:13 | persistent_fit / chain_ns |
| Ticket (last block combines) | algorithm | The last block to finish a row combines partial states. | crates/backends/llvm/src/func/gpu/k_streamk.rs:326 | stream_geo |
Switches and placement
How the rules' switches and the machine-model search reach the emitter.
Transformations (5)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| rules::optimization switches | Target: Gpu (Target)Code: Face→ Code: GpuRungs | functor | Each optimization switch decides from properties such as FFMA per DRAM byte, registers per thread, L2 per SM. | crates/backends/llvm/src/rules.rs:342 | compiler stack |
| arms applied over rules | Code: GpuRungsCode: GpuArms→ Code: effective GpuRungs | process | on forces, off removes; default arms are empty. | crates/backends/llvm/src/func/gpu.rs:275 | compiler stack |
| placed (machine-place search) | Code: TileSiteMachine → Code: Placed | functor | A 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:435 | compiler heap; thread-local memo |
| machine_of | Target: TargetProfile (Target)→ Machine | functor | Profile facts become machine facts with source and spread. | crates/backends/llvm/src/place/machine.rs:7 | compiler heap, cached per profile |
| profile::resolve | Code: name→ Code: TargetProfile | process | Detects the host (sysfs, sysctl) or device (driver query plus calibration) and returns a static profile. | crates/backends/llvm/src/profile/registry.rs:111 | process static |
Algorithms, data structures and design patterns (5)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Plan + replay | design pattern | Rules are checked by replaying every cited measurement. | crates/backends/llvm/src/rules/tests.rs:124 | The rules agree with every cited measurement |
| ON/OFF measurement arms | design pattern | Every optimization switch has an off arm for A/B; defaults come from rules, not flags. | crates/backends/llvm/src/gpu_arms.rs:544 | arms applied over rules |
| Roofline cost | algorithm | Time is the larger of flops over rate and bytes over bandwidth. | crates/backends/llvm/src/profile/tiles.rs:550 | placed (machine-place search), rules::optimization switches |
| Candidate search with admissible floor | algorithm | The search prunes candidates whose lower bound cannot beat the best. | crates/backends/llvm/src/place/search.rs:252 | placed (machine-place search) |
| Memoization by key (thread-local) | data structure | Searches and machines are cached per key inside one emission. | crates/backends/llvm/src/place/search.rs:96 | placed (machine-place search) |
Guarantees of LLVM backend
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:1crates/backends/cuda/src/func.rs:1crates/backends/cuda/src/kernel.rs:1crates/backends/cuda/src/loops.rs:1crates/backends/cuda/src/arena.rs:1crates/backends/cuda/src/module.rs:1crates/backends/cuda/src/ty.rs:1
Transformations (5)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| emit_with_opts | Flow: CategoryIr (Flow)→ Code: CUDA translation unit (Code) | functor | Flow 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:111 | compiler heap |
| emit_kernel_set | Code: Site→ Code: __global__ kernel + host launch | functor | One kernel per structural shape; each site launches it. | crates/backends/cuda/src/kernel/kernels.rs:111 | compiler heap |
| emit_loop | Code: LoopPlan→ Code: host guard-first loop | functor | Decide, guard, advance, back edge; in-place updates where the last-use plan allows. | crates/backends/cuda/src/loops.rs:61 | compiler heap |
| arena_plan | Code: CategoryIrCode: FuncId→ Code: ArenaPlan | functor | Give every non-loop buffer the next aligned offset. | crates/backends/cuda/src/arena.rs:99 | compiler heap |
| nvcc compile and run | Code: .cu text→ Code: executable and output | process | Built on a GPU box and linked with mapal-rt. | crates/backends/cuda/tests/differential/harness.rs:74 | external nvcc; files on the box |
Algorithms, data structures and design patterns (4)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Shape-deduplicated kernels | design pattern | One definition per structural shape, launched from many sites. | crates/backends/cuda/src/kernel/kernels.rs:111 | emit_kernel_set |
| Capability fixpoint (TrapCaps) | algorithm | A launch may trap if any reachable callee may. | crates/backends/cuda/src/kernel.rs:262 | emit_kernel_set |
| Fn-scope arena zone | design pattern | One allocation and one release per function, escape-checked. | crates/backends/cuda/src/arena.rs:99 | arena_plan |
| Host-driven loop | design pattern | The loop runs on the host; each trip launches kernels. | crates/backends/cuda/src/loops.rs:61 | emit_loop |
Guarantees of CUDA backend
| Guarantee (natural transformation) | What must agree | Checked in |
|---|---|---|
| A CUDA run agrees with the interpreter | Outputs and traps equal the interpreter's. | crates/backends/cuda/tests/differential/basics.rs:11crates/backends/cuda/tests/differential/basics.rs:168 |
| CUDA emission is deterministic | Stored .cu snapshots pin the text. | crates/backends/cuda/tests/golden_cu/basics.rs:6crates/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:1crates/mapal-rt/gpu/mapal_gpu.c:1crates/mapal-rt/gpu/mapal_choice.h:1crates/mapal-rt/gpu/mapal_gpu_emu.c:1crates/mapal-rt/tests/read.rs:1
Category Run
A running program: host memory, tasks, device memory, output and exit code.
Objects (32)
| Object | What it is | Defined at | Lives in | Provided by |
|---|---|---|---|---|
| arena zone | One cudaMalloc per function covering non-loop buffers, released at function exit unless an escape points into it. | crates/backends/cuda/src/arena.rs:99 | GPU global memory | CUDA backend |
| device twin | __device__ copy of a token-free function used inside kernels. | crates/backends/cuda/src/kernel.rs:461 | GPU code; per-thread locals in registers or local memory | CUDA backend |
| loop buffer | A per-buffer cudaMalloc inside loop cones; carried arrays swap pointers at the back edge. | crates/backends/cuda/src/loops.rs:61 | GPU global memory | CUDA backend |
| packed panel | A right-hand matrix repacked tile by tile for the CPU matmul loop. | crates/backends/llvm/src/func/core/packs.rs:8 | host heap/stack scratch, 64-byte aligned | LLVM backend |
| heap array buffer | Bytes of an array result, allocated and freed at last use. | crates/backends/llvm/src/func/core/ptrs.rs:367 | host heap via mapal-rt @mapal_rt_alloc | LLVM backend |
| per-object slot | The stack cell of one value, written once by its producing operation. | crates/backends/llvm/src/func/frame.rs:197 | host stack (alloca in the entry block); registers after LLVM mem2reg | LLVM backend |
| tile registers / shared memory | Accumulators sit in registers; panels staged in shared memory (cp.async or TMA). | crates/backends/llvm/src/func/gpu/kernel_geom.rs:580 | GPU registers and shared memory | LLVM backend |
| %Frame | The struct holding every object's value of one function call. | crates/backends/llvm/src/func/mod.rs:196 | host stack frame, or the mapal-rt frame arena when too large (@mapal_rt_frame_alloc) | LLVM backend |
| device arena slab | The function's one cuMemAlloc, aligned to 256 bytes. | crates/backends/llvm/src/func/resident.rs:461 | GPU global memory | LLVM backend |
| task pool run | The handle of one parallel run of split tasks. | crates/backends/llvm/src/module.rs:284 | host 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:35 | a host stack or frame slot owned by the emitted code; the bytes are in GPU global memory | LLVM backend |
| stream chain | A CUDA stream a chain of dependent sites runs on. | crates/mapal-rt/gpu/mapal_gpu_memory.inc:183 | CUDA driver state | LLVM backend |
| PinnedRange | A host array locked in memory so uploads can be asynchronous. | crates/mapal-rt/gpu/mapal_gpu_transfer.inc:5 | host memory registered with the driver; a static array of (pointer, bytes) | |
| mapal_gpu_site | The 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:161 | host code; kernels in GPU code memory | LLVM backend |
| module trap word | A device cell records a trap here; the next host checkpoint reads it. | crates/mapal-rt/gpu/mapal_gpu_gen.inc:100 | GPU global memory | LLVM backend |
| Module and fn_entry | The 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:166 | GPU module in the driver; table is a malloc'd array on the host | |
| Stream slots and events | Eight non-blocking chains plus the default stream, each joined to program order by an event. | crates/mapal-rt/gpu/mapal_gpu_fills.inc:5 | CUDA driver objects; the counters are static C arrays | |
| mapal_dev_trap word | A 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:109 | GPU global memory inside the module | |
| Trace totals | Counters of time and bytes per phase, printed at exit under MAPAL_GPU_TRACE. | crates/mapal-rt/gpu/mapal_gpu.c:1 | a 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:42 | GPU 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:23 | host heap; encoded descriptors are passed as kernel arguments | |
| TaskState | Waiting, Running or Done. | crates/mapal-rt/src/sched.rs:39 | one atomic byte per task | |
| FrameSlot (FRAME) | Scratch memory of one function call, released when the call returns. | crates/mapal-rt/src/mem.rs:149 | host heap; per-thread Vec of (address, layout) in a thread_local | |
| Trap | A 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:98 | a 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:55 | host heap; the list of (address, layout) is a Vec behind one global mutex | |
| ReadFailure | A failed file read: a message and a position in the program order; exit code 103. | crates/mapal-rt/src/read.rs:100 | host heap, a Mutex<Vec<(i64, String)>> | |
| FlowParRun | The opaque handle the emitted code holds for a Run. | crates/mapal-rt/src/sched.rs:113 | host heap; the pointer sits in an emitted stack slot | |
| Pool | The worker threads, one queue and one parking spot per lane. | crates/mapal-rt/src/sched.rs:145 | process-wide (global_pool); queues are Mutex<VecDeque<Work>> | |
| Run | One parallel region: its tasks, the frame pointer they share, the first trap, and a wake-up signal. | crates/mapal-rt/src/sched.rs:90 | host heap behind an Arc | |
| TaskDef | What one parallel task is: its kernel function, element count, rank, slice size, width. | crates/mapal-rt/src/sched.rs:14 | host heap, filled by the emitted program's mapal_par_task calls | |
| TaskBuild / TaskRt | A 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:79 | host 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:117 | host heap, inside a per-lane VecDeque |
Arrows (28)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| trap check after launch | launch that can trap → readback and mapal_trap | Only launches that can trap read back. | crates/backends/cuda/src/kernel.rs:262 |
| Index with guard | Index morphism → bounds branch + trap or bare load | A proven in-bounds index drops its trap check. | crates/backends/llvm/src/func/ops/index.rs:6 |
| Operation to instructions | MorphismId (Flow) → LLVM instructions over slots | Each morphism loads its input slots, computes, and stores its output slot. | crates/backends/llvm/src/func/ops.rs:36 |
| resident_after | MorphismId → frees and copy-outs | After each morphism, free what died and copy out what the host reads. | crates/backends/llvm/src/func/resident/emit_site.rs:8 |
| resident_instead | MorphismId → device alloc + launch instead of host op | A producer placed on the device is replaced by its device call. | crates/backends/llvm/src/func/resident/arena.rs:376 |
| mapal_gpu_init / load_module | flags, MAPAL_PTX file → Module, context | Start 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_arena | DeviceSlot, bytes → device address | Allocate a buffer, or carve the shared arena. | crates/mapal-rt/gpu/mapal_gpu_memory.inc:46 |
| mapal_gpu_d2h / d2h_on | device bytes → host bytes | Copy back; also a checkpoint that reads the device trap word. | crates/mapal-rt/gpu/mapal_gpu_memory.inc:152 |
| mapal_gpu_event | two stream slots → ordering | Make one stream wait for work on another. | crates/mapal-rt/gpu/mapal_gpu_memory.inc:183 |
| mapal_gpu_free | DeviceSlot → nothing | Release the buffer (members of an arena are only emptied). | crates/mapal-rt/gpu/mapal_gpu_gen.inc:33 |
| mapal_gpu_gen | kernel id, count → device array | Compute a producer array on the device. | crates/mapal-rt/gpu/mapal_gpu_gen.inc:9 |
| mapal_gpu_h2d / h2d_async / h2d_on | host bytes → device bytes | Copy 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_l2 | kernel id, pointers, grid → queued kernel run | Find 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_launchv | id, stream, pointers, grid → kernel launch | Launch over any number of device pointers. | crates/mapal-rt/gpu/mapal_gpu_launch.inc:362 |
| mapal_gpu_sync | streams → idle device | Wait for all device work. | crates/mapal-rt/gpu/mapal_gpu_gen.inc:119 |
| mapal_gpu_trap_arm / trap_poll / trap_word | device trap word → host trap | After 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_for | device bytes → zeroed bytes | Zero 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 / emit | value → stdout text | Print a value with the same formatter the interpreter uses, and flush. | crates/mapal-rt/src/lib.rs:53 |
| mapal_par_begin | task count → FlowParRun | Open a parallel region. | crates/mapal-rt/src/par.rs:46 |
| mapal_par_dep | two task indexes → dependency edge | Say that one task must finish before another starts. | crates/mapal-rt/src/par.rs:98 |
| mapal_par_launch / pin / wait / finish | FlowParRun → FlowParRun | Start 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_task | FlowParRun, TaskDef → FlowParRun | Add a task to the region. | crates/mapal-rt/src/par.rs:60 |
| mapal_par_trap / mapal_par_check | Trap → Run.trap | Record 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_task | path, bytes → array bytes | Read 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_alloc | size and alignment → ArenaBlock | Get a block that lives until the program ends. | crates/mapal-rt/src/mem.rs:65 |
| mapal_rt_frame_mark / alloc / release | FrameSlot stack → FrameSlot stack | Remember the stack height, push a block, pop back to the remembered height. | crates/mapal-rt/src/mem.rs:141 |
| mapal_rt_free_all | all ArenaBlocks → nothing | Release every block. | crates/mapal-rt/src/mem.rs:124 |
| mapal_time_ms / mapal_perf_begin / mapal_perf_end | nothing → milliseconds | The clock the program can read and the optional timing window. | crates/mapal-rt/src/mem.rs:34 |
Transformations (14)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| Run a parallel region | Run: TaskDefRun: FlowParRun→ Run: RunRun: Trap | process | The 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:118 | host threads of the global Pool; frame shared through Run.frame |
| Build the graph | Run: TaskDef→ Run: TaskBuild | process | Collect tasks and edges while the program issues them. | crates/mapal-rt/src/par.rs:60 | |
| Seal | Run: TaskBuild→ Run: TaskRt | process | Turn the mutable build list into immutable tasks with atomic counters. | crates/mapal-rt/src/run.rs:39 | |
| Slice and queue | Run: TaskRt→ Run: Work | process | Cut 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:119 | slice_ranges decides the cuts |
| Worker loop | Run: Work→ Run: TaskState | process | Each 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 finish | Run: TaskState→ Run: FlowParRun | process | The caller helps run work until its tasks are done, then checks for a trap. | crates/mapal-rt/src/run.rs:297 | |
| Allocate host memory | Run: size→ Run: ArenaBlockRun: FrameSlot | process | Whole-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 trap | Run: value→ Run: stdoutRun: exit code | process | A 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 module | Code: PTX file (MAPAL_PTXSchedule: mapal_site_reg→ Run: ModuleSchedule: choice_memo | process | On 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:56 | helper pthread then host heap and the GPU context |
| Move bytes | Run: host bytesRun: DeviceSlot→ Run: device bytes | process | Allocate, 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 kernel | Schedule: mapal_candRun: DeviceSlot→ Run: device bytes | process | Look 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:362 | driver call cuLaunchKernel; arguments built on the host stack |
| Pick a candidate for a site | Schedule: mapal_candSchedule: Wisdom file line→ Schedule: choice_memo | process | Use 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:279 | trial timed with events on the device; result appended to the wisdom file |
| Carry a device trap to the host | Run: mapal_dev_trap word→ Run: Trap | process | A 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:81 | the hook is a function pointer in the Rust runtime's CHECKPOINT atomic |
| Emulate the device on the CPU | Run: device (GPU→ Run: device (host memory | functor | Same 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:1 | host heap filled with 0xA5; blocks run as threads that meet at barrier functions |
Algorithms, data structures and design patterns (14)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Task graph with dependency counters | data structure | Each task counts unmet dependencies; at zero it becomes ready. | crates/mapal-rt/src/sched.rs:79 | Slice and queue, Worker loop |
| Work-stealing pool with spin then park | design pattern | Per-lane queues; idle workers steal, spin briefly, then sleep on a condition variable. | crates/mapal-rt/src/sched.rs:145 | Worker loop |
| Epoch counter plus condition variable | design pattern | A counter bumped on every change lets waiters re-check without missing a wake-up. | crates/mapal-rt/src/run.rs:67 | Wait and finish |
| Build then seal | design pattern | A mutable list while being built, an immutable lock-free array afterwards. | crates/mapal-rt/src/run.rs:39 | Build the graph, Seal |
| Arena with one teardown | design pattern | Allocate often, free everything once; per-call frames use a mark and release stack. | crates/mapal-rt/src/mem.rs:65 | Allocate host memory |
| Pure-function parsing of quotas | design pattern | Thread count from MAPAL_PAR and cgroup limits is computed by small pure functions so it can be tested. | crates/mapal-rt/src/sched.rs:385 | Run a parallel region |
| Autotune with memo and persistent cache (plan then replay) | algorithm | Time 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:279 | Pick a candidate for a site |
| FNV-1a hash | algorithm | The key of a site decision. | crates/mapal-rt/gpu/mapal_choice.h:130 | Pick a candidate for a site |
| Direct-mapped memo by table address | data structure | A decided site costs one pointer compare. | crates/mapal-rt/gpu/mapal_choice.h:125 | Pick a candidate for a site |
| Init on a helper thread, join at first use | design pattern | Driver start-up overlaps with host work before the first site. | crates/mapal-rt/gpu/mapal_gpu_init.inc:128 | Load the device module |
| Kernel lookup by id with preloaded table | data structure | A hash table from kernel id to function handle built from the PTX text. | crates/mapal-rt/gpu/mapal_gpu_modscan.inc:155 | Launch a kernel |
| Stream join by events | design pattern | A 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:167 | Launch a kernel |
| Deferred trap checkpoint | design pattern | The device error is read only at points where the host would observe a value. | crates/mapal-rt/gpu/mapal_gpu_gen.inc:81 | Carry a device trap to the host |
| Baton scheduling in the emulator | algorithm | Cooperative 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:219 | Emulate the device on the CPU |
Guarantees of Runtime
| Guarantee (natural transformation) | What must agree | Checked in |
|---|---|---|
| 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. | crates/backends/llvm/tests/large_gemm.rs:253crates/backends/llvm/tests/streamk_epi.rs:270 |
| Print agrees with the interpreter | Compiled and interpreted programs print the same text, because both use the same formatter and trap codes. | crates/backends/llvm/tests/differential/basics.rs:53crates/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.
Guarantees: A compiled run agrees with the interpreter, Rewrite and no-rewrite agree
Category Driver
How the command line drives the stages: arguments, side files, sessions.
Objects (5)
| Object | What it is | Defined at | Lives in |
|---|---|---|---|
| EmitOpts | The emitter's flags: target profile, face, order, optimization switch on/off settings. | crates/backends/llvm/src/opts.rs:48 | compiler heap, inside Args |
| Options (fmt) | check or stdout mode and the list of files. | crates/mapal-cli/src/fmt.rs:23 | compiler 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:290 | disk, next to the executable (or in $TMP/mapal-<pid>/ for run and test) |
| Args | Command, file, output path, mode flags, emitter options, face flags. | crates/mapal-cli/src/main.rs:58 | compiler heap; built by parse_args from the command line |
| Session / Entry / Repl | The REPL's remembered definitions and statements, replayed as one program each time. | crates/mapal-cli/src/repl.rs:79 | compiler heap; history in a file from history_file |
Arrows (2)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| main | Args → exit code | Dispatch to fmt, repl, lsp, build, run, dump-ir or test. | crates/mapal-cli/src/main.rs:83 |
| parse_args | command line → Args | Read the command, file and flags. | crates/mapal-cli/src/main.rs:128 |
Transformations (20)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| frontend (source to checked IR) | Text: Source file (.mapal→ Flow: CategoryIr | functor | parse, then lower, then check; any diagnostic stops with exit 1. made of: parse, lower, check | crates/mapal-cli/src/main.rs:215 | compiler heap, one process |
| parse | Text: Source file (.mapal→ Syntax: Program | functor | Source text to parse tree. | crates/mapal-syntax/src/parser.rs:43 | |
| lower | Syntax: Program→ Flow: CategoryIr | functor | Parse tree to the IR; also records the source directory. | crates/mapal-lower/src/lib.rs:52 | |
| check | Flow: CategoryIr→ Diagnostics: Diagnostic | process | Rules on effects and exclusivity. | crates/mapal-check/src/lib.rs:41 | |
| rewritten (static folding then rewrite) | Flow: CategoryIr→ Flow: CategoryIr | functor | Compute what is known before the run, then apply the rewrite rules. | crates/mapal-cli/src/main.rs:252 | |
| emit | Flow: CategoryIrDriver: EmitOpts→ Code: Emission | functor | Plan and write LLVM text for host and device. | crates/mapal-cli/src/main.rs:273 | |
| build (emit, tools, link) | Code: Emission→ Code: PTX fileCode: Executable | process | Write <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:378 | child processes opt, llc, clang; files on disk |
| Write host .ll | Code: Emission→ Code: <exe>.ll | process | Save the host text. | crates/mapal-cli/src/main.rs:317 | |
| Optimize device IR | Code: <exe>.dev.ll→ Code: <exe>.dev.opt.ll | process | opt -O3. | crates/mapal-cli/src/main.rs:352 | |
| Device IR to PTX | Code: <exe>.dev.opt.ll→ Code: PTX file | process | llc -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 | process | clang -O2 -c. | crates/mapal-cli/src/main.rs:347 | |
| Link | Code: <exe>.oCode: libmapal_rt.aCode: mapal_gpu.c→ Code: Executable | process | clang links host, runtime library, and on GPU the C runtime with -lcuda from MAPAL_CUDA. | crates/mapal-cli/src/main.rs:358 | |
| run | Flow: CategoryIr→ Run: stdoutRun: exit code | process | Compile 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_temp | Flow: CategoryIr→ Run: exit code | process | Make the temp directory, build, give the executable command to a closure, remove the directory. | crates/mapal-cli/src/main.rs:519 | |
| dump-ir | Flow: CategoryIr→ Code: text on stdout | process | Print the IR at a chosen stage (lowered, rewritten, llvm, device) or as a Mermaid diagram. | crates/mapal-cli/src/main.rs:651 | |
| test | Flow: CategoryIr→ Diagnostics: PASS/FAIL line | process | Run 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:724 | child process stdout through a pipe, read by wait_boxed |
| Interpreter run (oracle) | Flow: CategoryIr→ Values: RunResult | process | run, run_ordered, run_weakest or run_bound, then native_observable. | crates/mapal-interp/src/lib.rs:49 | |
| fmt | Text: Source file (.mapal→ Text: Source file (.mapal | process | Format files in place, check, or print to stdout; rejects invalid input. | crates/mapal-cli/src/fmt.rs:1 | |
| repl | Driver: Session→ Values: RunResult | process | Keep 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:206 | compiler heap; history file on disk |
| lsp | Editor: requests→ Editor: responses | process | Start the language server on stdin and stdout. | crates/mapal-lsp/src/server.rs:116 |
Algorithms, data structures and design patterns (8)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Pipeline of stages with a single error type | design pattern | Each stage returns Result<_, u8> with the exit code; the message is already printed. | crates/mapal-cli/src/main.rs:55 | frontend (source to checked IR), build (emit, tools, link), run, test |
| Artifacts named after the executable | design pattern | Every side file is <exe><ext>. | crates/mapal-cli/src/main.rs:290 | build (emit, tools, link) |
| Embedded runtime source | design pattern | The 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:378 | build (emit, tools, link) |
| Temporary build directory | design pattern | A private folder per process, removed even on failure. | crates/mapal-cli/src/main.rs:519 | run, test |
| Differential testing against an oracle | design pattern | The interpreter is the specification; test_cmd checks the native program against it. | crates/mapal-cli/src/main.rs:724 | test |
| Timeout by polling a child | algorithm | Run the program with piped stdout and kill it after N seconds. | crates/mapal-cli/src/main.rs:839 | test |
| Replay session in REPL | design pattern | State is the list of inputs, not a running machine. | crates/mapal-cli/src/repl/render.rs:96 | repl |
| Toolchain lookup by environment | design pattern | CC, LLVM, MAPAL_RT, MAPAL_CUDA, MAPAL_LD select the tools; missing tools exit 3. | crates/mapal-cli/src/main.rs:352 | build (emit, tools, link) |
Guarantees of Command line
| Guarantee (natural transformation) | What must agree | Checked in |
|---|---|---|
| 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. | crates/mapal-cli/src/main.rs:724crates/mapal-cli/tests/examples.rs:79 |
| Rewrite and no-rewrite agree | The --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:1crates/mapal-lsp/src/analysis.rs:1crates/mapal-lsp/src/server.rs:1crates/mapal-lsp/src/text.rs:1crates/mapal-lsp/src/docs.rs:1crates/mapal-cli/src/main.rs:1
Category Editor
What an editor sees: requests, answers, colors, plugin files.
Objects (15)
| Object | What it is | Defined at | Lives in |
|---|---|---|---|
| Class | The highlight class of a name (function declaration, builtin, binding, parameter, size ...), the shared vocabulary of all editors. | crates/mapal-lsp/src/analysis.rs:156 | one tag per highlighted span |
| DefKind | What a name is: function, type, field, global, local, parameter, body parameter, size parameter, format parameter. | crates/mapal-lsp/src/analysis.rs:45 | one 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:83 | server heap, inside Def |
| Analysis | Everything known about one file: text, parse tree, definitions, uses, highlight spans. A pure function of the text. | crates/mapal-lsp/src/analysis.rs:199 | server heap, rebuilt on each edit and kept per open document |
| Def / DefId | A named thing in the file (function, type, field, parameter, local) and its index in the definitions list. | crates/mapal-lsp/src/analysis.rs:120 | server heap: Vec<Def> inside Analysis; DefId is a usize index |
| Occ / Role | One 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:147 | server heap: Vec<Occ> inside Analysis |
| builtin and primitive docs | Hover text for each builtin function and primitive type. | crates/mapal-lsp/src/docs.rs:5 | constant strings in the binary |
| TOKEN_TYPES / TOKEN_MODIFIERS | The fixed list of semantic token names the server announces to the editor. | crates/mapal-lsp/src/server.rs:41 | constant 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:276 | server heap: map from URI to Doc inside Server |
| LineMap | Line starts so byte offsets can be converted to editor positions counted in UTF-16 units. | crates/mapal-lsp/src/text.rs:7 | server heap, one per document |
| server command | The command used to start the server: the mapal executable plus lsp. | editors/nvim/lua/mapal/lsp.lua:1 | a Lua table in Neovim; a {command, args:[lsp]} object in VS Code |
| Vim syntax groups | The Neovim highlighting rules working without a server. | editors/nvim/syntax/mapal.vim:1 | a Vim script loaded by Neovim |
| highlight class table | One 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:1 | a data file read by tests; its rows are copied into each editor's own files |
| token fixture | A sample program and its expected token classes. | editors/test/fixture.mapal:1 | test file on disk |
| TextMate grammar | The VS Code highlighting rules working without a server. | editors/vscode/syntaxes/mapal.tmLanguage.json:1 | a JSON file inside the extension |
Arrows (9)
| Arrow | From → to | What it does | Defined at |
|---|---|---|---|
| Analysis::class_of | Occ → Class | A use to its highlight class. | crates/mapal-lsp/src/analysis.rs:273 |
| Analysis::occ_at / def_at | offset → Occ / DefId | A byte offset to the use under it, then to its definition. | crates/mapal-lsp/src/analysis.rs:263 |
| Analysis::occurrences | DefId → Occ list | A definition to every place it is used (go to references, rename, highlight). | crates/mapal-lsp/src/analysis.rs:268 |
| Analysis::visible_at | offset → DefId list | An offset to the definitions whose name can be written there (completion). | crates/mapal-lsp/src/analysis.rs:315 |
| to_lsp_diagnostic | Diagnostic → lsp Diagnostic | A compiler diagnostic to an editor diagnostic. | crates/mapal-lsp/src/server.rs:258 |
| token_of | Class → (type, modifier) | A highlight class to the editor's semantic token type and modifier. | crates/mapal-lsp/src/server.rs:54 |
| LineMap::position / offset / range | SourceLoc / offset → lsp Position / Range | Convert between byte offsets or spans and editor positions or ranges. | crates/mapal-lsp/src/text.rs:38 |
| semantic token to Vim group | LSP semantic token → Vim group | The server's token type maps back to a class's Vim group. | editors/nvim/lua/mapal/lsp.lua:1 |
| semantic token to TextMate scope | LSP semantic token → TextMate scope | The same mapping into scopes through the extension manifest. | editors/vscode/package.json:1 |
Transformations (8)
| Name | From → to | Kind | What it does | Defined at | Lives in |
|---|---|---|---|---|---|
| Analysis::new | Text Syntax Tokens → Editor | functor | Parses 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:212 | server heap |
| compile_diagnostics | Text → Diagnostics | process | Runs 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:229 | a 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 | process | Reads 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:124 | main server thread; messages are JSON over stdio |
| mapal lsp command | Editor → Editor | process | The CLI subcommand that starts the server on stdin/stdout. made of: serve (the request loop) | crates/mapal-cli/src/main.rs:83 | an OS process started by the editor |
| encode_tokens | Editor → Editor | functor | Turns the classified spans into the editor's delta-encoded semantic token array. | crates/mapal-lsp/src/server.rs:646 | server heap: Vec<SemanticToken> in the reply |
| Neovim starts the server | Editor → Editor | process | On 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:1 | a child OS process talking over stdio |
| VS Code starts the server | Editor → Editor | process | The 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:126 | extension host process spawning a child process |
| format on request | Text → Text | process | The editors send buffer text to the formatter (through the server or `mapal fmt -`) and replace the buffer. | editors/nvim/lua/mapal/format.lua:1 | buffer text in the editor, formatter in the mapal process |
Algorithms, data structures and design patterns (9)
| Name | Kind | What it is | Defined at | Used by |
|---|---|---|---|---|
| Pure analysis, rebuilt per edit | design pattern | Analysis depends only on the text; no incremental state to keep in sync. | crates/mapal-lsp/src/analysis.rs:199 | Analysis::new |
| Scope-frame stack walker | algorithm | The 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:379 | Analysis::new |
| Definition table plus occurrence list | data structure | Definitions 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:147 | Analysis::new, Rename keeps meaning |
| Background worker with coalescing queue | design pattern | Diagnostics run on their own thread, and a burst of edits to one document collapses to the latest. | crates/mapal-lsp/src/server.rs:176 | compile_diagnostics |
| UTF-16 position mapping | algorithm | Editors count columns in UTF-16 units while the compiler counts bytes, so a line table converts between them. | crates/mapal-lsp/src/text.rs:7 | serve (the request loop) |
| Request dispatch by method name | design pattern | One match routes each protocol method to a handler. | crates/mapal-lsp/src/server.rs:384 | serve (the request loop) |
| Single class table checked by three tests | design pattern | One table drives tests in Neovim, VS Code and the server crate so they cannot drift. | editors/test/classes.tsv:1 | Same highlighting everywhere |
| Layered highlighting (static grammar, then server tokens) | design pattern | The grammar gives instant colours; the server's semantic tokens refine names once it is running. | editors/vscode/syntaxes/mapal.tmLanguage.json:1 | Same highlighting everywhere |
| Executable discovery order | algorithm | Setting first, bundled binary second, PATH last. | editors/vscode/extension.js:1 | VS Code starts the server |
Guarantees of Language server and editors
| Guarantee (natural transformation) | What must agree | Checked in |
|---|---|---|
| Editor errors equal build errors | For 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 meaning | Renaming a definition edits exactly its occurrences, so every name still resolves to the same definition. | crates/mapal-lsp/tests/protocol.rs:382 |
| Same highlighting everywhere | For 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:324crates/mapal-lsp/tests/highlight.rs:394editors/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.
| Name | Kind | Component | What it is | Defined at | Used by |
|---|---|---|---|---|---|
| Hand-written recursive-descent parser with depth limit | algorithm | Syntax | One 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:62 | parse |
| Error recovery with cooldown | design pattern | Syntax | After an error the parser skips to a safe point and mutes follow-up errors for a short while. | crates/mapal-syntax/src/parser.rs:241 | parse |
| Context-sensitive guard-arrow scan | algorithm | Syntax | A 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:30 | lex |
| Spans instead of copied text | design pattern | Syntax | Tokens and names hold only offsets, and text is cut from the one source string when needed. | crates/mapal-syntax/src/token.rs:11 | lex, parse, format_source |
| Line-start index with binary search | data structure | Syntax | Line starts are stored once, and an offset is found by search. | crates/mapal-syntax/src/loc.rs:59 | lex |
| Token-stream pretty printer | algorithm | Syntax | The 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:52 | format_source |
| Renderer-free diagnostics | design pattern | Syntax | Diagnostics 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:32 | lex, parse |
| Staged pipeline with fail-fast emission | design pattern | Lowering | Checks run in stages and are collected; once emission starts the first error stops that function. | crates/mapal-lower/src/lib.rs:378 | lower with globals, declare, emit and seal |
| Fixed-point rounds (monomorphization) | algorithm | Lowering | Repeat typing and emission up to 32 rounds until every called generic instance was declared. | crates/mapal-lower/src/lib.rs:40 | lower with globals, typing and size inference |
| Union-find over literal types | algorithm | Lowering | Integer/float literals of unknown width are variables merged into groups, then pinned to a type. | crates/mapal-lower/src/typing/walk_core.rs:376 | type one function |
| Size equation solving (inversion, monotone search, divisor enumeration) | algorithm | Lowering | Solves expressions like n*2 = 8 for n by inverting or searching. | crates/mapal-lower/src/sizes/infer.rs:477 | infer generic sizes and formats |
| Cycle detection by iterative DFS | algorithm | Lowering | Finds recursive types and recursive calls with an explicit stack frame. | crates/mapal-lower/src/tys.rs:222 | build the type table, effect analysis |
| Scope stack with poison marks | data structure | Lowering | Lexical scopes as a stack, with names marked unreadable after a loop. | crates/mapal-lower/src/scope.rs:36 | type one function, emit one function |
| Token threading for effects | design pattern | Lowering | Effectful functions take and return an IO token so order of print/clock is explicit data. | crates/mapal-lower/src/emit/exprs.rs:444 | emit one function, effect analysis |
| Capture analysis (struct captures flattened to fields) | algorithm | Lowering | Finds which outer values a map/fold body reads and passes them as leading inputs. | crates/mapal-lower/src/typing.rs:90 | type one function, emit one function |
| Prelude of parsed conversion signatures | design pattern | Lowering | to/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:201 | emit one function, build function signatures |
| Typed diagnostic catalogue | design pattern | Lowering | Every error is one LCode variant with a stable code string. | crates/mapal-lower/src/diag.rs:15 | lower: Syntax -> Flow |
| Tree walk keyed by node kind with sticky context | design pattern | Checker | A fan-out opens the illegal context, and a sequential block inside it inherits it. | crates/mapal-check/src/effects.rs:104 | effect legality pass |
| Lexical scope stack | data structure | Checker | Push on entering a block, pop on leaving, to know whether a name is a local binding. | crates/mapal-check/src/effects.rs:77 | effect legality pass |
| In-edge count on the graph | algorithm | Checker | Counts non-pair edges into the return object to find a second writer. | crates/mapal-check/src/exclusivity.rs:26 | return exclusivity pass |
| Deterministic ordering | design pattern | Checker | No hash maps; findings come in a fixed order so two runs agree exactly. | crates/mapal-check/src/lib.rs:41 | check |
| Arena with typed ids (slotmap) | data structure | Flow graph | Objects, 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:288 | IrBuilder (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 pattern | Flow graph | The only mutable form is IrBuilder; sealing returns an immutable graph, and an independent validator double-checks. | crates/mapal-ir/src/builder.rs:172 | IrBuilder (declare, build_fn, FnBuilder ops, seal), seal, validate |
| Fact cache stored on the sealed graph (compute once, read after) | design pattern | Flow graph | One OnceLock per fact and function; dependent facts read stored inputs; never recomputed per call site. | crates/mapal-ir/src/facts.rs:25 | fact queries (tile_plan, loop_plan, last_use_plan, path_plan, precision_plan, elem_plan, access_plan, residence_plan, ...) |
| Iterative Tarjan strongly connected components | algorithm | Flow graph | Finds loops as cycles with an explicit work stack, no recursion. | crates/mapal-ir/src/algo/loops.rs:13 | sccs / topo_order / loop_structure |
| Kahn topological order | algorithm | Flow graph | A legal order of operations by a worklist, with loop back edges cut. | crates/mapal-ir/src/algo/loops.rs:162 | sccs / topo_order / loop_structure |
| Deterministic containers (no HashMap) | design pattern | Flow graph | Insertion-ordered Vecs and slot maps so dumps, orders and snapshots are byte-stable. | crates/mapal-ir/src/lib.rs:1 | IrBuilder (declare, build_fn, FnBuilder ops, seal), to_mermaid / to_mermaid_flow / to_mermaid_category / to_mermaid_string |
| Depth guard on types | design pattern | Flow graph | Type walks are iterative or capped at 64 levels so a hostile deep type cannot overflow the stack. | crates/mapal-ir/src/ty.rs:276 | validate |
| Definition as data (tagless-final Arith trait: run or record) | design pattern | Flow graph | One generic definition of exp/sqrt/sin/cos runs natively (interpreter) or is traced into steps a backend prints. | crates/mapal-ir/src/math.rs:178 | Trace (record a reference definition as data), math candidates / admits / choose |
| Cost-based choice over declared units | design pattern | Flow graph | Realizations are data (Unit, TargetDef) filtered by error bound and ranked by issue cost. | crates/mapal-ir/src/math/target.rs:138 | math candidates / admits / choose |
| Forward error analysis (gamma, bound_coef) | algorithm | Flow graph | A-priori rounding error of a sum of products, per site and per precision member. | crates/mapal-ir/src/algo/precision.rs:83 | fact queries (tile_plan, loop_plan, last_use_plan, path_plan, precision_plan, elem_plan, access_plan, residence_plan, ...) |
| Lifetime colouring of buffers | algorithm | Flow graph | Values that die before another is born share a colour (a buffer). | crates/mapal-ir/src/unit.rs:43 | unit_plan / out_rows |
| Plain-function rendering, no Display | design pattern | Flow graph | Values stay free of printing code; text comes from plain functions like ty_label. | crates/mapal-ir/src/ty.rs:405 | to_mermaid / to_mermaid_flow / to_mermaid_category / to_mermaid_string |
| Fact cache on the sealed graph | design pattern | Facts | Each 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:226 | loop_plan, tile_plan and variants, last_use_plan, unit_plan, stream_plan |
| Arena with typed ids | data structure | Facts | Objects, 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:288 | Seal the graph, sccs, topo_order |
| Strongly connected components | algorithm | Facts | Loop detection by finding cycles in the object graph. | crates/mapal-ir/src/algo/loops.rs:13 | loop_structure, loop_plan |
| Topological order | algorithm | Facts | Evaluation order with insertion-order tie-breaks. | crates/mapal-ir/src/algo/loops.rs:162 | last_use_plan, bounds_proof and finite_plan, path_plan and guard_plan |
| Liveness with two-iteration loop carry | algorithm | Facts | Positions and death points of values, with a value live across a loop back edge marked carried. | crates/mapal-ir/src/algo/last_use.rs:142 | residence_plan, unit_plan |
| Interval analysis narrowed by conditions | algorithm | Facts | Integer 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:9 | bounds_proof and finite_plan |
| Digit decomposition of indices | algorithm | Facts | Index 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:263 | radix_plan, unit_plan, stream_plan |
| Hazard classification (RAW/WAR/WAW) | algorithm | Facts | Dependencies between operations from the bytes they read and write, with shared buffers. | crates/mapal-ir/src/access.rs:77 | access_plan |
| Working-set peak over a live interval | algorithm | Facts | A value's residence from the peak live bytes between producer and last reader against cache size. | crates/mapal-ir/src/residence.rs:65 | residence_plan |
| A-priori error bound (gamma-n) | algorithm | Facts | A closed-form rounding error bound for sums of products used as the correctness gate. | crates/mapal-ir/src/algo/precision.rs:83 | precision_plan |
| Online combine (running max and rescale) | algorithm | Facts | Per-block partials combined by the fold's own operator, with exp rescale for a running max. | crates/mapal-ir/src/algo/algebra.rs:290 | fold_combine, stream_plan |
| Independent validator | design pattern | Facts | A second pass re-derives the graph invariants without sharing builder code. | crates/mapal-ir/src/validate.rs:98 | Validate the graph |
| Fact arms (OFF switches) | design pattern | Facts | Each rule can be switched off for comparison, never per hardware. | crates/mapal-ir/src/facts.rs:73 | bounds_proof and finite_plan, unchanged_plan and call_keep, stream_plan |
| Plan then replay | design pattern | Rewrites | Every pass only decides (graph to plan, pure); one shared replayer is the only code that builds graphs. | crates/mapal-rewrite/src/plan.rs:65 | rewrite: the fixpoint pipeline, Inlining, Loop lifting, Common-subexpression elimination |
| Fixpoint iteration with round cap | algorithm | Rewrites | Rounds repeat until all plans are empty or 32 rounds, with validation after each rebuild. | crates/mapal-rewrite/src/driver.rs:87 | rewrite: the fixpoint pipeline |
| Value-numbering CSE | algorithm | Rewrites | Operations 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:395 | Common-subexpression elimination |
| Liveness-based DCE | algorithm | Rewrites | Backward reachability from outputs and effects; anything that may trap or diverge is pinned live. | crates/mapal-rewrite/src/graph_rewrites.rs:34 | Dead-code elimination |
| Functor law as rewrite rule | design pattern | Rewrites | Map 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:32 | Map fusion |
| Body substitution (inlining and fusion synthesis) | algorithm | Rewrites | A 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:13 | Replay, Inlining, Map fusion |
| Evaluate at compile time with the oracle | design pattern | Rewrites | Static values are computed by the interpreter itself, so they are exact on every number face. | crates/mapal-rewrite/src/statics.rs:34 | Static folding |
| By-value intake and no-op shortcut | design pattern | Rewrites | The graph is moved in; an all-empty round returns it without a rebuild. | crates/mapal-rewrite/src/driver.rs:70 | rewrite: the fixpoint pipeline |
| Random program generator (testgen) | design pattern | Rewrites | A 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:203 | Rewrite preserves the interpreter's result, Facts agree with the interpreter |
| Rule data table | data structure | Rewrites | The Zip/Enumerate naturality laws kept as a const table. | crates/mapal-rewrite/src/naturality.rs:30 | rewrite: the fixpoint pipeline |
| Fuel (step budget) for total evaluation | design pattern | Interpreter | A u64 budget decremented per step so every run halts with Done, Diverged or Trapped. | crates/mapal-interp/src/eval.rs:62 | run / run_ordered, eval_fn_within (walk operations in topological order), eval_values / eval_values_once / static_cone |
| Result as early-exit channel (Abort) | design pattern | Interpreter | Traps, divergence and read failure travel as Err and are lifted once at the entry. | crates/mapal-interp/src/value.rs:86 | run / run_ordered, eval_fn_within (walk operations in topological order) |
| Guard-first loop evaluation | algorithm | Interpreter | Decide and exit cone evaluated before the advance cone. | crates/mapal-interp/src/loops.rs:31 | run_loop (guard-first loop driver) |
| Reverse-mode derivative tape (first-order error composition) | algorithm | Interpreter | Record partial derivatives forward, sweep backward per output to compose deviations along the program. | crates/mapal-interp/src/bound.rs:249 | run_bound (record tape, reverse sweep) |
| Shared immutable arrays (Rc) with staging slots for products | data structure | Interpreter | Arrays are reference counted; products are assembled in staging buffers slot by slot, matching Pair edges. | crates/mapal-interp/src/eval/helpers.rs:74 | eval_fn_within (walk operations in topological order) |
| Cone evaluation (evaluate only what a root reads) | algorithm | Interpreter | Restrict the walk to the set of objects feeding wanted roots. | crates/mapal-interp/src/lib.rs:201 | eval_values / eval_values_once / static_cone |
| Thread-local recorders (tape, weakest flag, read failure) | design pattern | Interpreter | Optional modes switched by scoped thread-local state so the common path has no extra parameters. | crates/mapal-interp/src/bound.rs:170 | run_bound (record tape, reverse sweep), run_weakest |
| Facts carry provenance | design pattern | Hardware facts and rules | Every 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:64 | Assemble the profile, Translate the profile |
| Layered fallback for calibration | design pattern | Hardware facts and rules | Try the user's file, then the file in the repository, else run with unmeasured numbers. | crates/backends/llvm/src/profile/calib.rs:36 | Find the calibration |
| Capabilities as geometry | design pattern | Hardware facts and rules | Instructions are described by what they move and compute, so rules never compare versions. | crates/backends/llvm/src/profile/caps.rs:12 | Assemble the profile |
| Probe sweep to knee | algorithm | Hardware facts and rules | Each 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:1 | Calibration probes |
| Static table per part | data structure | Hardware facts and rules | A constant struct per known part, plus a lookup by physical key for new ones. | crates/backends/llvm/src/profile/place_rtx_5080.rs:66 | Assemble the profile |
| Threshold between nearest winner and loser | algorithm | Hardware facts and rules | Each 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:342 | Choose optimization switches from properties |
| Plan and replay | design pattern | Hardware facts and rules | Decisions are stored as data (a tsv of measurements) and a test replays them against the rule code. | crates/backends/llvm/src/rung_replay.tsv:1 | The rules agree with every cited measurement |
| ON/OFF measurement arms | design pattern | Hardware facts and rules | Every 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:544 | Choose optimization switches from properties |
| Branch and bound | algorithm | Machine model | Search with an admissible lower bound that prunes prefixes and points. | crates/mapal-place/src/search.rs:496 | Branch and bound search |
| Minimax regret over intervals | algorithm | Machine model | Choose the candidate whose largest regret at any corner of the fact intervals is smallest. | crates/mapal-place/src/search.rs:420 | Minimax verdict |
| Exact LRU trace simulation | algorithm | Machine model | Counts misses of a line-granular LRU using a Fenwick tree over distinct bytes since last use. | crates/mapal-place/src/lru.rs:188 | The closed form equals the LRU simulation |
| Fenwick tree | data structure | Machine model | A binary indexed tree for prefix sums used by the LRU simulator. | crates/mapal-place/src/lru.rs:162 | The closed form equals the LRU simulation |
| Three-gap progression | algorithm | Machine model | The 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:11 | Count misses by distinct bytes |
| Closed-form reuse by interval unions | algorithm | Machine model | Misses by distinct bytes over waves and walk windows, linear instead of simulated. | crates/mapal-place/src/reuse/cross.rs:118 | Count misses by distinct bytes |
| Memo caches in thread locals | design pattern | Machine model | Pure functions of a grid are memoized in thread-local maps and cleared at a size cap. | crates/mapal-place/src/reuse.rs:101 | Count misses by distinct bytes |
| Little's law flow | algorithm | Machine model | A 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:52 | A trip's steady state |
| Facts with intervals | design pattern | Machine model | Every machine number has a low, value and high; evaluation at the ends makes uncertain picks visible. | crates/mapal-place/src/fact.rs:64 | Evaluate at every corner, Minimax verdict |
| Lowering as a trait | design pattern | Machine model | The backend supplies its kernels as a Lowering that declares constraints and counts; the search is generic over them. | crates/mapal-place/src/lower.rs:125 | Generate candidate schedules, Branch and bound search |
| Incumbent with error band | design pattern | Machine model | The 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:37 | Branch and bound search |
| Incumbent and candidate | design pattern | Machine model | The 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:252 | Place one site |
| Memo by search key | design pattern | Machine model | A 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:252 | Place one site |
| Scoped guards (RAII) | design pattern | Machine model | WarmScope, ColScope and OrderScope set per-compile context and restore it when dropped. | crates/backends/llvm/src/place/site.rs:97 | Placement at launch time |
| Forced launch for lowering | design pattern | Machine model | A 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:70 | Lower to check a candidate |
| Plan and replay | design pattern | Machine model | Measured arms are stored as data and every change is re-scored against them. | crates/backends/llvm/src/place_replay.tsv:1 | The pick agrees with the measured winner, The error band is the replay's residuals |
| Coordinate domains | data structure | Machine model | A 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:76 | Branch and bound search |
| Slot per object, mem2reg left to LLVM | design pattern | LLVM backend / Host code | Every value gets a stack cell written once; LLVM turns them into registers. | crates/backends/llvm/src/func/mod.rs:254 | FnEmit::emit_ordered, emit_morphism |
| Guard-first loop CFG | design pattern | LLVM backend / Host code | The loop header decides first, so the exit trip still runs the decide cone. | crates/backends/llvm/src/loops.rs:22 | emit_loop |
| Fixpoint over the call graph (attribute capability) | algorithm | LLVM backend / Host code | A function is clean only if every callee is clean; loops block willreturn. | crates/backends/llvm/src/func/mod.rs:46 | FnEmit::emit_ordered |
| Arena of typed ids (SecondaryMap) | data structure | LLVM backend / Host code | Per-object and per-morphism side tables keyed by slotmap ids. | crates/backends/llvm/src/func/mod.rs:254 | emit_module, FnEmit::emit_ordered |
| Declare only what is used | design pattern | LLVM backend / Host code | Runtime declarations are added by searching the emitted text for the call. | crates/backends/llvm/src/emit.rs:217 | emit_module |
| Strategy ladder with a predicate per optimization switch | design pattern | LLVM backend / Host code | Each 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:526 | emit_tiled_map (tile ladder) |
| Loop buffer colouring | algorithm | LLVM backend / Host code | Next-state bytes take a spare buffer not read while they are written. | crates/backends/llvm/src/func/frame/loop_buffers.rs:52 | emit_loop |
| Text builder as the artifact | design pattern | LLVM backend / Host code | The String is the translation unit; no intermediate LLVM object model. | crates/backends/llvm/src/opts.rs:198 | emit_module |
| Plan then replay | design pattern | LLVM backend / GPU memory residency | A pure plan record is computed first; emission only reads it. | crates/backends/llvm/src/func/resident.rs:377 | resident_plan, emit_site_resident |
| First-fit interval colouring | algorithm | LLVM backend / GPU memory residency | Buffers with disjoint lifetimes share bytes. | crates/backends/llvm/src/func/resident.rs:486 | color / color_by, arena |
| Delta transfer | design pattern | LLVM backend / GPU memory residency | Only the rows a trip wrote are uploaded or recomputed. | crates/backends/llvm/src/func/resident.rs:121 | retained_sites |
| Lazy allocation through a slot | design pattern | LLVM backend / GPU memory residency | The runtime fills the slot on first use, so the host emits no branch. | crates/mapal-rt/gpu/mapal_gpu_memory.inc:46 | emit_site_resident |
| Candidate table, chosen at load | design pattern | LLVM backend / GPU kernels | Compile time lists launches; the runtime picks one from device limits. | crates/backends/llvm/src/func/gpu/site_table.rs:28 | site_cands, site_call, load-time dispatch |
| Content-hashed kernel ids | algorithm | LLVM backend / GPU kernels | FNV hash of body and profile names a kernel so equal kernels merge. | crates/backends/llvm/src/func/gpu/site_table.rs:256 | device_module |
| Rule table over hardware properties | design pattern | LLVM backend / GPU kernels | Choices read geometry (SMs, registers, L2, bandwidth), never a part name. | crates/backends/llvm/src/rules.rs:342 | launch_in |
| Stream-K / split-K | algorithm | LLVM backend / GPU kernels | Cut the k fold across blocks, add partials atomically or via workspace. | crates/backends/llvm/src/func/gpu/launch_rules.rs:89 | launch_in, lowered_text / Kernel |
| Software-pipelined panels | algorithm | LLVM backend / GPU kernels | Next panel loads while this one computes (cp.async, TMA). | crates/backends/llvm/src/func/gpu/kernel_geom.rs:580 | lowered_text / Kernel |
| Footprint rule (producer cells read lie inside the unit) | design pattern | LLVM backend / Merged launches | Group membership is decided only by what each work unit reads, not by an operator name. | crates/backends/llvm/src/func/flow/units.rs:289 | unit_of (flow) |
| Online softmax / running rescale | algorithm | LLVM backend / Merged launches | A running maximum and sum are rescaled as windows arrive. | crates/backends/llvm/src/func/stream.rs:52 | stream_geo |
| Tree and warp-shuffle reduction | algorithm | LLVM backend / Merged launches | Row totals by tree in shared memory or by shuffles. | crates/backends/llvm/src/func/flow/gen_slices.rs:322 | unit_kernel |
| Hazard graph (RAW/WAR/WAW) as the merge test | design pattern | LLVM backend / Merged launches | Launches merge only if the access plan leaves them unordered. | crates/backends/llvm/src/func/horizontal.rs:150 | side_by_side, persistent_fit / chain_ns |
| Grid barrier | algorithm | LLVM backend / Merged launches | A level barrier inside a persistent kernel. | crates/backends/llvm/src/func/calls/kernel.rs:13 | persistent_fit / chain_ns |
| Ticket (last block combines) | algorithm | LLVM backend / Merged launches | The last block to finish a row combines partial states. | crates/backends/llvm/src/func/gpu/k_streamk.rs:326 | stream_geo |
| Plan + replay | design pattern | LLVM backend / Switches and placement | Rules are checked by replaying every cited measurement. | crates/backends/llvm/src/rules/tests.rs:124 | The rules agree with every cited measurement |
| ON/OFF measurement arms | design pattern | LLVM backend / Switches and placement | Every optimization switch has an off arm for A/B; defaults come from rules, not flags. | crates/backends/llvm/src/gpu_arms.rs:544 | arms applied over rules |
| Roofline cost | algorithm | LLVM backend / Switches and placement | Time is the larger of flops over rate and bytes over bandwidth. | crates/backends/llvm/src/profile/tiles.rs:550 | placed (machine-place search), rules::optimization switches |
| Candidate search with admissible floor | algorithm | LLVM backend / Switches and placement | The search prunes candidates whose lower bound cannot beat the best. | crates/backends/llvm/src/place/search.rs:252 | placed (machine-place search) |
| Memoization by key (thread-local) | data structure | LLVM backend / Switches and placement | Searches and machines are cached per key inside one emission. | crates/backends/llvm/src/place/search.rs:96 | placed (machine-place search) |
| Shape-deduplicated kernels | design pattern | CUDA backend | One definition per structural shape, launched from many sites. | crates/backends/cuda/src/kernel/kernels.rs:111 | emit_kernel_set |
| Capability fixpoint (TrapCaps) | algorithm | CUDA backend | A launch may trap if any reachable callee may. | crates/backends/cuda/src/kernel.rs:262 | emit_kernel_set |
| Fn-scope arena zone | design pattern | CUDA backend | One allocation and one release per function, escape-checked. | crates/backends/cuda/src/arena.rs:99 | arena_plan |
| Host-driven loop | design pattern | CUDA backend | The loop runs on the host; each trip launches kernels. | crates/backends/cuda/src/loops.rs:61 | emit_loop |
| Task graph with dependency counters | data structure | Runtime | Each task counts unmet dependencies; at zero it becomes ready. | crates/mapal-rt/src/sched.rs:79 | Slice and queue, Worker loop |
| Work-stealing pool with spin then park | design pattern | Runtime | Per-lane queues; idle workers steal, spin briefly, then sleep on a condition variable. | crates/mapal-rt/src/sched.rs:145 | Worker loop |
| Epoch counter plus condition variable | design pattern | Runtime | A counter bumped on every change lets waiters re-check without missing a wake-up. | crates/mapal-rt/src/run.rs:67 | Wait and finish |
| Build then seal | design pattern | Runtime | A mutable list while being built, an immutable lock-free array afterwards. | crates/mapal-rt/src/run.rs:39 | Build the graph, Seal |
| Arena with one teardown | design pattern | Runtime | Allocate often, free everything once; per-call frames use a mark and release stack. | crates/mapal-rt/src/mem.rs:65 | Allocate host memory |
| Pure-function parsing of quotas | design pattern | Runtime | Thread count from MAPAL_PAR and cgroup limits is computed by small pure functions so it can be tested. | crates/mapal-rt/src/sched.rs:385 | Run a parallel region |
| Autotune with memo and persistent cache (plan then replay) | algorithm | Runtime | Time 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:279 | Pick a candidate for a site |
| FNV-1a hash | algorithm | Runtime | The key of a site decision. | crates/mapal-rt/gpu/mapal_choice.h:130 | Pick a candidate for a site |
| Direct-mapped memo by table address | data structure | Runtime | A decided site costs one pointer compare. | crates/mapal-rt/gpu/mapal_choice.h:125 | Pick a candidate for a site |
| Init on a helper thread, join at first use | design pattern | Runtime | Driver start-up overlaps with host work before the first site. | crates/mapal-rt/gpu/mapal_gpu_init.inc:128 | Load the device module |
| Kernel lookup by id with preloaded table | data structure | Runtime | A hash table from kernel id to function handle built from the PTX text. | crates/mapal-rt/gpu/mapal_gpu_modscan.inc:155 | Launch a kernel |
| Stream join by events | design pattern | Runtime | A 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:167 | Launch a kernel |
| Deferred trap checkpoint | design pattern | Runtime | The device error is read only at points where the host would observe a value. | crates/mapal-rt/gpu/mapal_gpu_gen.inc:81 | Carry a device trap to the host |
| Baton scheduling in the emulator | algorithm | Runtime | Cooperative 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:219 | Emulate the device on the CPU |
| Pipeline of stages with a single error type | design pattern | Command line | Each stage returns Result<_, u8> with the exit code; the message is already printed. | crates/mapal-cli/src/main.rs:55 | frontend (source to checked IR), build (emit, tools, link), run, test |
| Artifacts named after the executable | design pattern | Command line | Every side file is <exe><ext>. | crates/mapal-cli/src/main.rs:290 | build (emit, tools, link) |
| Embedded runtime source | design pattern | Command line | The 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:378 | build (emit, tools, link) |
| Temporary build directory | design pattern | Command line | A private folder per process, removed even on failure. | crates/mapal-cli/src/main.rs:519 | run, test |
| Differential testing against an oracle | design pattern | Command line | The interpreter is the specification; test_cmd checks the native program against it. | crates/mapal-cli/src/main.rs:724 | test |
| Timeout by polling a child | algorithm | Command line | Run the program with piped stdout and kill it after N seconds. | crates/mapal-cli/src/main.rs:839 | test |
| Replay session in REPL | design pattern | Command line | State is the list of inputs, not a running machine. | crates/mapal-cli/src/repl/render.rs:96 | repl |
| Toolchain lookup by environment | design pattern | Command line | CC, LLVM, MAPAL_RT, MAPAL_CUDA, MAPAL_LD select the tools; missing tools exit 3. | crates/mapal-cli/src/main.rs:352 | build (emit, tools, link) |
| Pure analysis, rebuilt per edit | design pattern | Language server and editors | Analysis depends only on the text; no incremental state to keep in sync. | crates/mapal-lsp/src/analysis.rs:199 | Analysis::new |
| Scope-frame stack walker | algorithm | Language server and editors | The 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:379 | Analysis::new |
| Definition table plus occurrence list | data structure | Language server and editors | Definitions 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:147 | Analysis::new, Rename keeps meaning |
| Background worker with coalescing queue | design pattern | Language server and editors | Diagnostics run on their own thread, and a burst of edits to one document collapses to the latest. | crates/mapal-lsp/src/server.rs:176 | compile_diagnostics |
| UTF-16 position mapping | algorithm | Language server and editors | Editors count columns in UTF-16 units while the compiler counts bytes, so a line table converts between them. | crates/mapal-lsp/src/text.rs:7 | serve (the request loop) |
| Request dispatch by method name | design pattern | Language server and editors | One match routes each protocol method to a handler. | crates/mapal-lsp/src/server.rs:384 | serve (the request loop) |
| Single class table checked by three tests | design pattern | Language server and editors | One table drives tests in Neovim, VS Code and the server crate so they cannot drift. | editors/test/classes.tsv:1 | Same highlighting everywhere |
| Layered highlighting (static grammar, then server tokens) | design pattern | Language server and editors | The grammar gives instant colours; the server's semantic tokens refine names once it is running. | editors/vscode/syntaxes/mapal.tmLanguage.json:1 | Same highlighting everywhere |
| Executable discovery order | algorithm | Language server and editors | Setting first, bundled binary second, PATH last. | editors/vscode/extension.js:1 | VS Code starts the server |