# BAP MoonBit Port Status

This repository is porting `.repos/bap` from OCaml to idiomatic MoonBit.

## Implemented

- `bitvec`: fixed-width bitvectors with normalization, bit predicates, BAP-style numeric natural ordering helpers, mixed-width comparison rejection, checked integer representation/conversion helpers, unsigned and signed shifts, modular arithmetic, unsigned division/remainder, gcd/lcm/extended-gcd, full-width concatenation plus BAP-style fixed-slice append/repeat/list-concat, bit selection, extraction, hexadecimal and BAP-style string literal parsing/formatting, and endian byte conversion.
- `regular`: printable helpers, deterministic digest wrappers with source-style namespace/add chaining, BAP-style cache load/save delegation, BAP eager sequence helper wrappers for construction including `return`, `init`, `unfold`, `unfold_step`, `unfold_with`, `shift_right`, and exclusive/inclusive ranges, append/concat, positional access plus checked head and `next`, take/drop/split and predicate slicing, map/filter/filter-map/filter-opt/concat-map, fold/delayed-fold/iter with indexed variants, generator-style `return`/bind/map/yield/run helpers, find/find-map/predicates including `all`, comparison, array/list/reverse-list conversion, and rendering, BAP Bytes compatibility regressions for zero-filled creation, copy ownership, UTF-8 string conversion for text-facing `of_string` helpers, constructor/access/subslice/copy/trim/extend/escaped helpers, pure byte set/fill/blit update helpers, byte comparison/hash/container/search/traversal/fold-result/fold-until/map/concat/ASCII-case helpers, and byte-safe textual/binary serialization round trips, format metadata/registry support, and prefix/suffix string tries with `find`, `change`, `remove`, `length`, `fold`/`iter`, and longest-match helpers.
- `future`: BAP-style futures, promises, signals, and streams with fulfillment/peek/upon semantics, newest-first callbacks, applicative and collection helpers, stream sources, subscription/watch hooks, map/filter/merge/apply/split/zip adapters, selector futures, list adapters, fold-window stride/width edge cases, frame/sample timing semantics, and translated BAP future/stream regressions.
- `graphlib`: persistent directed graphs with node/edge operations, BAP-style edge/accessor and adjacency aliases, update-only edge relabeling, directional degree helpers, BAP-style bulk construction, shape comparison, filtered graph materialization, materialized graph views, DOT rendering, and support-type string renderers, BAP-style remove/reinsert coherence regressions, node replacement that preserves incident edges, endpoint-keyed set-style union/intersection with stable left labels, successor/predecessor queries, callback-driven and visitor-style DFS plus edge classification and BAP-style entry/leave/pre/rpost numbering, timestamp interval and ancestor-lemma regressions, forward and reverse-edge reachability plus reachable folds, optional-start whole-forest postorder/reverse-postorder traversal, weighted shortest paths with reverse-edge traversal and checked path endpoint aliases, strong component decomposition with BAP-style partition view, partition refinement plus group/equivalence helpers, forward and reverse-edge dominator-set, immediate-dominator, dominator-tree, tree-input frontier, and frontier-wrapper computation, and dominance frontiers for SSA-style analyses, and Kildall-style fixpoint solutions.
- `relation`: BAP-style persistent bipartite relations with comparator-driven deterministic pair ordering, source-compatible endpoint membership checks, left/right lookup, fold/iter helpers, duplicate-edge suppression, and matching callbacks for saturated edges plus forward/backward non-injective anomalies.
- `types`: BAP-style `Word` wrapper over `bitvec` with signedness-preserving literal parsing including unsuffixed width-literal regressions, BAP-style integer and binary construction/conversion plus `_exn` aliases, checked integer narrowing helpers, generic radix/prefix/suffix value formatting, numeric and byte/bit enumeration aliases, signedness-dispatching division/remainder, BAP-style scaled address `memref` arithmetic and 32/64-bit address arithmetic wrappers, predicates and validation helpers, full word display, BAP arithmetic regressions for complement, shifts, gcd/lcm, and extended-gcd, and BAP byte-enumeration/concatenation/extraction regressions for odd-width and uneven-width words, BAP-style fixed word/address size and full source-compatible architecture alias normalization/defaulting/comparison helpers, comparable size-based value type constructors, variables with BAP-style accessors and SSA index/base helpers, a BIL expression/statement AST with BAP constructor helpers, BAP-style special statement attribute encoding/decoding, including expression-level widening `Extract`, `Concat`, and kinded `Cast` (`pad`, `extend`, `high`, `low`) semantics, BAP operator metadata and word apply helpers, a BAP-style named BIL pass registry with selected transform pipelines, BAP-style BIL result IDs/values plus linear and sparse result storage, persistent BIL result contexts, a BAP-style capacity-backed mutable vector with container-style iteration, custom-equality search/index helpers, result-fold, early-stop folds, list conversion, membership, and min/max helpers, comparable checked type errors and inference, BAP-style expression effect/coeffect analysis, reusable BIL expression/statement fold/find/exists/map traversal helpers, free-variable and reference/assignment predicate helpers, sequence-aware variable/expression substitution, scalar and byte-addressed memory expression evaluation, bounded statement execution over BIL state with translated BAP Bili regressions for let shadowing and Collatz loops, focused BIL simplification with negative-constant normalization, normalize/non-generative expression hoisting/ITE-splitting/condition hoisting/load-memory store hoisting/fold-const/fixpoint aliases, BAP trie-key normalization, and constant store-chain load folding, statement-level constant propagation with static branch facts, jump-aware branch conservatism, definitely-skipped loop facts, BAP-style jump, unknown, effect, and loop propagation/pruning regressions, BAP-style `prune_unreferenced` filters, dead virtual assignment pruning with translated BAP simple-liveness regressions, and a bounded fixpoint optimization pipeline with translated BAP-style full-pipeline regressions, plus an initial IR term layer with tids, BAP-style namespace-labelled tid creation/string parsing, attributes, type-erased term clone and attribute replacement wrappers, BAP-style address and condition attributes, program/sub/block containers and program/sub/block builders, subroutine naming aliases, defs, phis, jumps, calls, labels, arguments, BAP-style def/arg var-value aliases, BAP-style jump guard helpers, BAP-style argument metadata tags, BAP-style label/call access and update helpers, BAP-style phi variable/options aliases, BAP-style phi single-source and unresolved-source fallback helpers, BAP-style interrupt-vector tids and jump destination access/update helpers, BAP-style jump expression enumeration, expression traversal/free-variable/substitution helpers, skip-aware block expression/lhs/element mapping with BAP-style aliases, whole-program IR traversal/find helpers, stable-preorder typed IR term-view fold/find/exists/map helpers with direct-child enumeration plus BAP-style `switch`/`proj`/`cata` class dispatch, single-term class-specific mapping, class-filtered program lookup/parent helpers with shorter BAP-style aliases, event-based IR visitor folds over terms, variables, and expressions, class-filtered direct-child find/update/remove/change helpers with BAP Term-compatible alias names, BAP-style direct-child first/last/next/previous/before/after navigation, direct-child append/prepend insertion helpers, and direct-child map/filter/filter-map/concat-map helpers, BAP-style IR term string renderers, reusable query predicates including address matching, and parent lookup, BAP-style block definition sequence/edit/split/split-while utilities and occurs predicate plus phi, jump, and block update maps, local subroutine CFG helpers over direct jumps, interrupts, and call returns, BAP-style CFG graph wrappers with node insert/remove/update helpers and translated insertion-order graph regressions, edge insert/remove/update helpers, DOT rendering, graph projection aliases, and edge metadata with jump positions/surrounding jumps/edge conditions, BAP-style tid graphs with pseudo start/exit nodes, subroutine dominator/immediate-dominator/dominance-frontier wrappers over local block tids, Trivial Condition Form hoisting for complex jump conditions, direct and resolver-backed callgraphs over program terms, component-based stub-to-implementation alias resolution with `link_only`/`no_link` filters and direct call redirection, phi-aware block liveness and SSA-aware external/free-variable queries over reachable subroutine CFGs, semipruned SSA conversion with dominance-frontier phi insertion and source-order dominator-tree renaming, SSA destruction that lowers phis through edge-copy blocks while stripping SSA indices, BAP sema fixture regressions for free vars, SSA phi edges, and SSA liveness, and BAP-style IR flattening that materializes nested expressions as virtual defs. Universal tagged values (upstream `Value`, `Value.Tag`, `Value.Dict`, `Value.Match`): registered typed tags with name/UUID/typeid, `Value::create`/`get`/`has_tag`/`tagname`, printing, ordering and optional serialization, heterogeneous `Dict`s, and typed term attributes (`Term::set_tag`/`get_tag`) over the string attribute map.
- `knowledge`: a faithful port of `lib/knowledge`. The knowledge base is one immutable state value (classes -> objects with per-class identifiers -> typed heterogeneous records keyed by slot keys, computation status, symbol tables with public sets, and context variables) held by a mutable `State` handle; the `'a knowledge` monad is modeled in direct style as `(State) -> A raise` (conflicts are `Error`s, `run`/`eval`/`catch_`/`transaction`/`with_empty` restore the snapshot of a diverging computation). `collect` implements the upstream evaluator: promises registered on slots run once per object, re-entrant requests for a property under computation return the current approximation and re-schedule the requesting promises, which are iterated until the least fixed point; promises/proposals run under `with_empty` so `require`/`reject`/`guard_`/`proceed`/`on`/`unless` reject them into bottom (rolling back their effects); `provide` joins monotonically (diverging with `NonMonotonicUpdate`) and notifies observers; plus `promising`/`observing`/`propose`/`proposing`/`suggest`/`resolve`, `Value` (get/put/has/join/merge strategies/refine/order/domain/persistent), `run` (computes all promised properties into a value), objects with `create`/`scoped` deletion/`objects`/`repr`/`read`, symbols with `intern_symbol` (public), `in_package`, `import_` (package and qualified imports, strict shadowing, `NotAPackage`/`NotASymbol`), context variables (`Var::new`/`get`/`set`/`update`/`with_`), `Enum`, KB save/load (`serialize`/`deserialize`/`to_bytes`/`of_bytes`, persistent slots and names only) and `pp`. The older pieces remain: names with keyword normalization, persistent codecs, agents and opinions, partial orders, domains (Domain.obj is the upstream total order over identifiers), class/slot metadata and documentation, rules, and `FactTable` as a transactional `Result`-based view of one slot in a `State`. Slot identity is per (class, name): redeclaring a property with the same domain object returns the same slot (shared key, promises and observers, recovered through a typed exchange cell in the domain, no casts); objects are listed once they have knowledge, as upstream; `Class::equal`/`assert_equal` witnesses with `Object::cast`, and `Eq`/`Compare`/`Hash`/`Object::persistent` for objects (`Object.derive`). Redeclaring a property with a *different* domain object fails (aborts) as upstream; all callers declare their domains and slots once as top-level lets. Known gaps: upstream also rejects a same-domain redeclaration (the port returns the same slot, so slot helpers stay cheap), classes are identified by name and may be redeclared, the serialized format is port-native text rather than bin_io, and there is no file-based `load`/`save`.
- `language`: initial high-level language handles with source-style names, unique identity even for repeated names, comparison/equality by handle identity, and generic per-language property tables.
- `strings`: initial BAP strings support with byte-safe scanner `next`/`run` behavior over offset readers, default printable/whitespace stop handling, custom stop predicates, persistent byte-string indexes with configurable key successor/null behavior, ASCII alphabet definitions, byte-oriented dictionary unscrambling/buildability helpers with BAP count-trie result ordering and newline dictionary loading, and MAP-style string-computation detector state transitions with decision/abort/result accessors.
- `core_theory`: symbolic sorts with BAP-style top/value/refinement, application-decomposition, floating-point format/bit extraction helpers, and IEEE754 format parameters/sorts, typed values with the source-compatible Knowledge class handle, public Knowledge domain, resorting, sort-preserving erasure, and match-style refinement combinators, comparable variables with the BAP-style `define_var` constructor alias, definition normalization, scoped immutable let-variable helpers, fresh-counter helpers, identifier parsing, default mutability, version rendering, virtual fresh IDs, sort-preserving erasure, and persistent codecs, comparable effect lattice values with BAP-style built-in effect name and sort aliases plus union/join helpers, comparable program values with a public Knowledge domain and program semantics values with byte-safe instruction-code storage and a public semantics Knowledge domain, labels with BAP-style set-valued aliases, package-aware stable label constructors, opinion-backed possible names, id-based comparison helpers, and total target resolution with unknown fallback, source/compiler/program-unit metadata with comparable languages, BAP-style empty source/program values and source Knowledge domain, BAP-style language unknown helpers, package-qualified language names/hashes/members/domain plus declaration/read helpers, and source-compatible LLVM/P-code architecture encoding language aliases including RISC-V LLVM and x86 P-code aliases, sources, sexp-style compiler descriptors with association-list spec construction and optional compiler Knowledge domain, stable file/region program-unit constructors, id-based program-unit comparison, BAP-style unit bias address conversion helpers, and source-compatible effect/program/source/unit/label/semantics Knowledge class handles plus program/source/unit/label/semantics slot handles, Knowledge-backed source, program-unit, and label fact stores for BAP-style slot observation/collection plus public Knowledge documentation and scalar/source/compiler/unit/label/program/semantics persistent codecs and slot metadata, target metadata with name-based comparison/rendering/hash helpers and a flat Knowledge domain, inheritance/matching helpers with unknown parent sentinels, BAP-style target-sized code/data address and data word constructors plus explicit data/code memory declarations, memory-sort-derived address sizes, BAP-style ARM/AArch64 code alignment metadata, and alignment accessors, BAP-style comparable target metadata enums with expanded endianness/system/ABI/FABI/filetype aliases, unknown helpers, and package-qualified name/hash/member/read/persistent/domain helpers, role names including unknown, package-qualified name/hash/member/read/persistent/domain helpers, blessed register-role parsing/rendering, and the ARM Thumb-mode role, BAP-style register-role namespace aliases, persistent options, and the target-options Knowledge class/domain, family/partition helpers, filtering/selection over system/ABI/FABI/filetype/options constraints including non-strict parent fallback, generated variant registration with package override plus built-in x86/ARM/Thumb/MIPS/PowerPC OS/ABI/FABI/filetype variants including 16-bit x86/MS-DOS calling-convention targets, immutable metadata update helpers, broader BAP system/ABI/FABI/filetype metadata enum parsing/formatting including ELF OSABI system names and architecture calling-convention ABI names, source-level target alias declarations with `Alias::def`/`reg`/`bit`/`unk` mapped into direct, aggregate, partial, and chained alias origins, alias-origin tracking and BAP-style origin introspection including full-width direct alias ranges, sub/sup/set origin casts and register-set projections, x86 byte/word/dword/vector aliases, EFLAGS bit aliases, RFLAGS/EFLAGS subregister provenance, and the IOPL flag-field alias, ARM32 SP/LR/PC and CPSR flag aliases, MIPS GPR aliases, RISC-V ABI aliases, LoongArch GPR ABI aliases, SPARC stack/frame-pointer aliases, AArch64 R/X/W/V/Q/D/S/H/B/FP/LR/SP zero-register aliases plus NZCV flag bits, PowerPC floating-status roles and stack-pointer aliases, and SystemZ stack-pointer aliases, target-aware register role helpers with x86 SIMD floating/vector roles, x86 index/segment roles, x86 EFLAGS integer/control/system bit roles, explicit MIPS/RISC-V/AArch64 pseudo-register role aliases, and ARM/RISC-V/LoongArch/MIPS/PowerPC/SPARC/AArch64/SystemZ integer, floating, vector, status, individual flag, alias, pseudo, special, link, constant/zero, thread, reserved, caller/callee-saved, and calling-convention roles plus BAP-style target variable lookup, alias-origin unaliasing, and multi-role register queries with exclusion and uniqueness checks, broad BAP-style common architecture target declarations including separate ARM, RISC-V, LoongArch, MIPS, and PowerPC family targets, MIPS/PowerPC bi-endian targets, SystemZ9, source-compatible x86 CPU targets from 16-bit `i86` through `i686` with incremental ST/MM/XMM register surfaces, little-, big-, and bi-endian ARM version targets through generic AArch32/AArch64 targets, LoongArch GPR/FPR/PC surfaces, ARM/AArch64 endian-suffixed aliases, MIPS and PowerPC target aliases, and a target registry/declaration/lookup layer with BAP-style `Target` namespace helpers including package-qualified `declare_target`/lookup/read/get plus top-level declaration/lookup/read/filter/select/variant-registration wrappers.
- `core_theory/Theory.Core`: the executable Core Theory. `Value`, `Effect` and `Semantics` are knowledge values (`@knowledge.Value` of the `core:value`/`core:effect` classes refined by the sort, phantom kinds `ValueCls`/`EffectCls`), so any component can declare its own properties (`Value::cls().property(...)`) and properties provided by different theories join independently; `Semantics` is the effect class refined to the top sort with `value`/`insn-code` properties and is the `core:semantics` property of programs; all slots and domains are declared once as top-level lets. Terms are direct-style knowledge computations (`Pure = (State) -> Value raise`, `Eff = (State) -> Effect raise`); a theory is a `Core` record of closures covering every Init/Bool/Bitv/Memory/Effect/Basic/Fbasic/Float/Trans operation (fields for record updates, same-named methods for calls, `var` is `var_`). `Core::empty()` is `Theory.Empty`, `Core::basic()` is `Basic.Make` (Basic from Minimal), `Core::join` is the manager's `Join` (arguments evaluated once, results merged), `Core::desugar` is `Pass.Desugar` (register aliases and constant registers via the label target) with a pass registry. The manager provides `declare_theory` (name/pkg/desc/extends/context/provides), `instance` (context/requires selection, subsumption, join, KB-cached instantiation on `core:theory` objects), `require` (desugared structure), `current` and `with_current`, plus `declared_theories` documentation. `Theory.Parser` is a grammar-record parser (`Parser`, `BitvGrammar`, `BoolGrammar`, `MemGrammar`, `FloatGrammar`, `RmodeGrammar`, `StmtGrammar`, `Core::parse`), with the BIL grammar instance (`bil_parser`, `Core::reflect_bil`). `Core::bil()` is the reference BIL-producing theory (`Bil_semantics.Core`): values carry `bap:exp` (`bil_exp_slot`, `Value::bil`) and effects `bap:bil` (`bil_slot`, `Effect::bil`, `Semantics::bil`); `Var::reify` and `Sort::bil_type` map Core variables to BIL.
- `core_theory/elementary`: BAP elementary floating-point approximation table identifier helpers, including table recognition, checked operation extraction, and source operation naming schemes.
- `core_theory/program units`: file and region program-unit identity and persistence preserve package qualification, while older persistent encodings still decode with the default package.
- `core_theory/alias DSL`: Repeated left-hand-side alias equations now infer part aliases independently of declaration order, covering BAP's documented `r25r24`/`w`/`whi`/`wlo` solver pattern.
- `core_theory/target roles`: Public role helpers include the port's program-counter role alongside BAP register roles, AArch64 return-register helpers cover BAP's `R0`-`R7` and `V0`-`V7` function-return role surface, including the port's `X0`-`X7` aliases, AArch64 floating-register helpers include BAP's `X0`-`X31` alias role surface, ARM/AArch64 condition flags carry BAP's integer status-role metadata, AArch64 zero-register alias provenance uses BAP's `ZR` base for `XZR`/`WZR`, ARM32 VFP `D` registers are limited to BAP's floating-point target surfaces with the source-compatible `D0`-`D15` target-variable surface and VFP3 `d0`-`d31` role aliases, general-register role queries follow BAP target tables across x86, ARM/AArch64, MIPS, RISC-V, LoongArch, SPARC, PowerPC, and SystemZ while excluding status/control flags from `general`, and PowerPC64 big-endian metadata preserves BAP's duplicate `powerpc64+bi` nickname while keeping lookup order anchored on the bi-endian target.
- `core_theory/AArch64 target roles`: AArch64 argument/result and caller-/callee-saved role metadata now covers the ABI boundary registers for `X`/`W`/`R` aliases, frame/stack-pointer aliases, and vector registers, with regressions for alias and caller/callee boundaries.
- `core_theory/MIPS target roles`: MIPS argument role metadata now follows BAP's 32-bit and 64-bit argument register ranges through the port's ABI aliases, covering `A0`-`A3` on 32-bit targets and the `A0`-`A3`/`T0`-`T3` boundary on 64-bit targets.
- `core_theory/PowerPC target roles`: PowerPC stack-pointer aliases now inherit BAP's callee-saved `R1` role surface, so the port's `SP` alias is both a stack pointer and callee-saved register.
- `core_theory/SPARC target roles`: SPARC stack/frame pointer aliases now preserve the saved-register roles of their register-window sources, with `SP`/`O6` caller-saved and `FP`/`I6` callee-saved.
- `memory`: byte-addressed memory regions with BAP-style non-empty creation, native file construction, rebasing, bit-sized views/ranges, raising view/load/get and byte-dereference accessors, endian-aware word loads and stores, source-style input readers over checked word loads, BAP-style complete-word fold/iteration/predicate/search helpers including Result-lifted variants, borrowed byte-buffer exposure, word-token memory tries for R8/R16/R32/R64-style keys, contiguous merges, hexdumps, and a basic interval `MemMap` with BAP lower-bound interval ordering, range-ordered lookup/intersection/dominator queries including BAP pointwise, run-through lookup, duplicate equal-range intersection, checked source-style insertion, table boundary-intersection regressions, source-named address lookup/intersection fold and min/max/next/previous helpers, exact membership, ranged traversal/query helpers, map/filter transformations, `change` command helpers, exact and intersection-based table linking including checked source-style invariants, source-style reverse maps, and exact/interval removal helpers.
- `native_io`: native-target file reading and writing behind a small package boundary, with explicit non-native stubs so pure packages keep checking on wasm/js/llvm.
- `demangle`: BAP-style named demangler registry with package-qualified names, identity and leading-underscore built-ins, duplicate-name checks, lookup/get/available helpers, and target-specific demangler installation/selection with identity fallback.
- `demangle/itanium`: a native Itanium C++ ABI demangler (a port of LLVM's `ItaniumDemangle.h`) with `demangle` (`itaniumDemangle`/`__cxa_demangle`, including `-p` no-params mode and bare types) and `cxxfilt` (the `llvm-cxxfilt` driver: unchanged names on failure, leading `.`, `--strip-underscore`, `--types`, `__imp_` import thunks). Covers nested/local/unscoped names, templates and template parameters (including lambda-level `TL`), all substitutions, CV/ref-qualifiers, function/array/pointer-to-member/vector types, all operators, ctors/dtors (incl. inheriting), special names, lambdas/unnamed/block types, abi tags, vendor qualifiers, clone suffixes, expressions, decltype, packs, folds, requires-clauses and modules. Validated against `llvm-cxxfilt` 22.1.7 on 899,040 names (host LLVM/Clang/LLDB/MLIR and Homebrew C++ library symbols plus the libc++abi test inputs; with/without `-p` and `-t`) with 100% agreement, plus 206,107 names with `--strip-underscore`; a verified table of 3,307 names is committed as tests. `long double` literals follow the reference host (64-bit, 16 hex digits); Rust and D manglings are not demangled.
- `future`: public `bap_future.mli` helper parity for one-shot futures and promises with single-fulfillment enforcement, decided/fulfilled checks, newest-first callback registration through `upon`, `peek`/checked `peek_exn`, bind/map/apply/both/all/all-unit plus two-, three-, four-, and five-input applicative helpers covered by translated `bap_future/test_future.ml` regressions, typed `FutureArgs` adapters for curried `mapN`/`applyN` usage, list-backed `all`/`all_unit` adapters, plus the stream/signal substrate with send/repeat, observe/subscribe/watch/unsubscribe, newest-first subscriber lifecycle and wait hooks, `from`/`repeat`/`unfold`/`unfold_many`/legal `unfold_prime` alias for BAP `unfold'`/`unfold_until`/array-, list-, and iterator-backed finite streams including `of_sequence`, `before`, list-backed selector adapters, lazy derived-stream linking, map/filter/map-many plus legal `map_prime` alias for BAP `map'`, merge/either/apply plus two-, three-, four-, and five-input applicative helpers, typed `StreamArgs` adapters for curried BAP-style variadic stream application, concat/concat-merge with list adapters, split/zip/unzip, once, parse, head/tail, find/find-map, take/nth, upon, last-before, fold-window, frame, and sample regressions from `bap_future/test_stream.ml`.
- `main_event`: initial BAP main event subsystem over `future` streams/signals with a global event stream, send/subscribe behavior, last-registered printer precedence, typed log message/progress events, custom event fallback, MoonBit-friendly section reporters with debug gating and per-task progress total defaults, and target-agnostic BAP main-log `process_events` observers/processors with error-message callbacks.
- `traces`: initial trace event records for memory/register/code/control-flow events with common BAP event tag names/UUIDs, name/UUID tag lookup, constructor, and typed payload extractor helpers, binary/tracer/architecture/file-stat/trace-stat metadata values with common BAP metadata key/UUID and source registration order, name/UUID lookup, and typed accessor helpers, metadata dictionaries with deterministic entry/key enumeration, removal, and typed text/int/bool custom-attribute setters/getters, tool support declarations, UUID-shaped trace IDs, loaded-trace list/iterator registry bookkeeping, callback-backed and array-backed trace sources/readers including BAP-style id-aware reader registration, event reading and filtering with selective read-all/next matching helpers, monitor policies for failing/skipping/stopping/packing/warning on source errors, URI protocol provider registration/probing with no-provider and ambiguous-URI handling, reader/writer dispatch, protocol-aware support checks, deterministic byte snapshot encoding/decoding for current event and metadata variants, public byte round trips, byte-backed in-memory save/load coverage, and native file-backed `trace.binprot` URI save/load coverage translated from `bap_traces/test_traces.ml`.
- `traces/event rendering`: Trace event payloads expose source-shaped textual renderers for movement arrows, byte chunks, syscalls, exceptions, calls, returns, module loads, scalar tags, and mode changes.
- `traces/metadata rendering`: Trace binary, tracer, file-stat, and trace-stat metadata records expose BAP-style textual renderers including source-shaped GMT timestamp formatting, with BAP-style `Binary`/`Tracer`/`File_stats`/`Trace_stats` namespaces for constructing and rendering the port's metadata record values.
- `traces/filter-map`: Trace transformations are pinned to BAP's record-copy semantics: nested filter maps compose over earlier mappers while preserving loaded trace id, protocol, tool, and metadata context.
- `traces/facades`: The loaded-trace repository exposes a MoonBit-legal `Traces::enum_` alias for BAP's reserved-word `Traces.enum` iterator facade, trace events expose `TraceEvent::return_` for BAP's `Event.return` constructor plus typed execution-mode event construction/extraction over `TraceMode`, and BAP-style `Event`/`Meta`/`Mode`/`Monitor`/`Id`/`Reader` namespaces expose trace event tags, metadata tag handles, execution-mode enum/slot access, monitor policy constructors, trace identifier helpers, and callback-backed reader construction over the port's existing tag, Knowledge, trace-monitor, UUID-backed id, and trace-reader models.
- `dwarf`: initial DWARF support with BAP-style LEB128 encoded values, signed and unsigned Int/Int32/Int64 encoding, byte read/write helpers, size reporting, truncation/error checks, immutable byte input cursors with a source-style composable reader facade, null-terminated string, endian word/address/offset, unit-size, address-size, LEB128 code, tag/attribute/form including standard DWARF2-DWARF5 DIE tags and attributes, partial-unit tags, and source-style type constructor aliases, skip, const, block, and standard/GNU indexed-string readers including zero-length block payloads, unsigned fixed block lengths, unsigned `data*`/`udata`, signed `sdata`, and flag forms, abbreviation table parsing with code/tag/children/attribute-form fields and BAP FBI-oriented value-field classification including `implicit_const` and unambiguous indirect forms plus conservative reference-field classification for nested-DIE attributes, plus section-backed table access, section buffers/data plus source-style core-section and cursor aliases for `.debug_info`, `.debug_abbrev`, `.debug_str`, `.debug_line_str`, `.debug_str_offsets`, `.debug_addr`, `.debug_ranges`, `.debug_rnglists`, and `.debug_loclists`, structured `.debug_info` unit-header and DIE-record parsing with per-attribute spans, attribute lookup, reference-attribute enumeration, reference-target resolution, depth-based tree navigation, and basic payload/value readers including resolved local string, address, range-list, location-list, and location-expression values, fixed data16 payloads, unsigned constant values, signed LEB constant values, expression blocks, indexed-form values, typed DIE references including sibling/type/import/common/containing-type/object-pointer attributes, and local reference target lookup, structured `.debug_str` and `.debug_line_str` string-table parsing, ELF32/ELF64 debug-section extraction for little- and big-endian files including extended section counts/name-table indexes, and function-boundary extraction for entry-point/inlined-subroutine/inline/string-table/line-string/standard and GNU indexed-string/indirect-form names with demand-driven `.debug_str` lookup, standard and GNU/MIPS linkage-name fallback, same-compilation-unit and version-aware absolute `DW_AT_specification`/`DW_AT_abstract_origin` name references including indirect-form references plus supplementary/alternate string and reference classification with safe skip fallback, referenced non-function DIE names, and bounded alias chains, low-PC and entry-PC starts, absolute or relative high-PC attributes, DWARF4 range-list summaries with base-address selection plus scope-base and GNU ranges-base handling, structured DWARF4 `.debug_ranges` entry parsing, DWARF5 unit headers including unsupported-unit skipping plus skeleton/split/type header-tail fields, string-offset bases including fixed-width indexed string forms, structured `.debug_str_offsets` parsing with optional `.debug_str` resolution, structured `.debug_addr` address table parsing, standard and GNU address-table bases, fixed-width standard/GNU `addrx` references, and LLVM `addrx_offset` address references, `.debug_rnglists` absolute and indexed range-list summaries including address-indexed entries and scope-relative offset pairs, structured DWARF5 `.debug_rnglists` entry parsing, structured DWARF5 `.debug_loclists` entry parsing with expression payload preservation and location-list base attributes, child-depth-aware range-base scoping, skippable producer metadata forms such as loclist indexes, supplementary and GNU alternate-object references/strings, type-signature references, and zero-length expression payloads, and zero-padded `.debug_info` tail handling, with translated BAP LEB128/input-reader/abbreviation/section-data/ELF/FBI regressions.
- `image`: image metadata over `memory`, including target/arch accessors, target-derived address size, stored or target-derived Ogre specifications, BAP-style `of_bigstring`/`of_string`/`from_spec` constructor aliases over byte loaders and Ogre docs, segments, sections, symbols, symbol values, relocations with optional signed addends and REL memory-addend markers, external references, required libraries, ELF interpreter, SONAME, RPATH/RUNPATH strings, load bias, executable flags, base addresses, checked pure relocation fixup application over image segments including `target + addend`, `target + word_at_fixup`, and `base + addend` handling, memory maps, symbol/section/segment lookup, multi-segment symbol memory chunks, endian-aware `Image.words` extraction with BAP high-base contiguous-address regressions, a MoonBit backend registry with description/extension/priority discovery metadata, a BAP-style Ogre document loader registry for named image loading, and idempotent built-in raw, Ogre, and ELF backend registration that loads bytes/specs into `(Image, warnings)` by explicit backend, filename extension, or native file path, an Ogre document parser with declaration/fact validation and scalar normalization, raw/spec-style Ogre-to-image conversion for entry, target metadata, endian, segment/mapping, code-region, section, function-symbol, `bias`, `is-executable`, `symbol-value`, `require`, `base-address`, `relocation`, `relative-relocation`, and `external-reference` facts, and an ELF32/ELF64 loader for target/endian/entry/base-address metadata including LoongArch machine mapping, target system and ABI refinement from representable OSABI values, executable flag from `ET_EXEC`, optional named sections, absent section-name tables, extended program/section counts and section-name indexes, defined `SHT_SYMTAB`/`SHT_DYNSYM` symbols and symbol-value metadata via linked string tables, `PT_INTERP` interpreter extraction, `SHT_DYNAMIC` and section-header-less `PT_DYNAMIC` required-library, SONAME, RPATH, and RUNPATH extraction from linked/mapped dynamic string tables, relocation-section metadata for defined-symbol, undefined-symbol, known relative entries across x86/x86-64, SPARC/SPARCV9, PowerPC/PowerPC64, SystemZ, ARM, AArch64, RISC-V, and LoongArch, RELA addends, and REL implicit addends, section-header-less `DT_RELA`/`DT_REL`/`DT_JMPREL` relative and dynamic-symbol external relocation metadata that can feed image-level relative relocation application, packed `DT_RELR` memory-addend relative relocation metadata, section-header-less stripped files, zero-filled `PT_LOAD` segments, and alloc-section-backed object files without program headers.
- `macho`: raw Mach-O reader (the part of `llvm::object::MachOObjectFile` the upstream LLVM loader uses): 32/64-bit, little/big-endian headers, load commands (`LC_SEGMENT`/`LC_SEGMENT_64` with their sections, `LC_SYMTAB`, `LC_DYSYMTAB`, `LC_MAIN`, `LC_THREAD`/`LC_UNIXTHREAD` states with the initial program counter of x86, x86-64, ARM, AArch64 and PowerPC, the dylib commands, `LC_LOAD_DYLINKER`, `LC_UUID`, `LC_FUNCTION_STARTS`, others kept raw), `nlist` symbols with names, section and external relocations (scattered ones marked), the indirect symbol table, decoded function starts, and universal (fat, `FAT_MAGIC`/`FAT_MAGIC_64`) binaries with their architectures, slices and `lipo`-style architecture names.
- `coff`: raw PE/COFF reader (the part of `llvm::object::COFFObjectFile` the upstream LLVM loader uses): DOS stub and PE signature, COFF file header, PE32/PE32+ optional headers with data directories, section headers (with `/nnn` long names of objects), symbol records (auxiliary records skipped, string-table names), section relocations (with `IMAGE_SCN_LNK_NRELOC_OVFL`), the import directory (by name and by ordinal, with IAT slots) and the export directory (names, ordinals, forwarders), RVA-to-offset mapping; PE images and COFF objects of the i386, x86-64, ARM, ARM64, PowerPC, MIPS and RISC-V machines.
- `image` Mach-O and PE/COFF loaders (upstream `llvm` loader, `llvm_macho_loader.hpp`, `llvm_coff_loader.hpp` and `Bap_llvm_loader.translate`): the loaders emit the upstream `llvm:*` facts (segment commands, sections, code entries, symbol entries with LLVM's symbol sizes, name references of symbol stubs/pointers and relocations, libraries, base address and entry point; for COFF the virtual section headers, symbols, relocations, exports and imported libraries), and the ported `translate` derives the image facts (`segment`, `mapped`, `section`, `named-region`, `code-region`, `symbol-chunk`, `code-start`, `named-symbol`, `symbol-value`, `external-reference`, `relocation`, `bias`, `base-address`, `entry-point`) the image is built from, with the target of the Mach-O CPU type or the COFF machine. The `llvm` image backend selects the ELF, Mach-O or PE/COFF loader by the file contents; the `macho` and `coff` backends are also selected by file extensions. Port extensions: universal binaries are loaded as the slice of the requested target or of the host (`thin_binary`, `@native_io.host_architecture`); `LC_FUNCTION_STARTS` become `llvm:function-start` facts, `code-start` roots and `sub_<addr>` function symbols; `LC_UNIXTHREAD` gives the entry point; the `LC_MAIN` entry is the virtual address of its file offset (upstream emits the offset); `__mh_execute_header` is not taken for a function; PE import address table slots are name references of the imported functions.
- `elf`: lossless raw ELF reader (upstream `Bap_elf.Std.Elf`): upstream-named class/data/OS-ABI/type/machine/program-header/section-header/flag enumerations with `*_EXT`/`PT_OTHER` variants preserving unknown raw values, program and section header records with every field (physical addresses, alignment, link/info, entry sizes), the header fields upstream drops (`e_flags`, `e_ehsize`, file version, table infos), `from_bytes`/`from_bigstring` with `pos`/`len` and extended numbering, `section_name`, `string_of_section`, and string/symbol/relocation table accessors; it reads relocatable objects, core files and files without program or section header tables, and the `image` ELF backend is built on it.
- `project`: project container over `core_theory`, `types`, `memory`, and `image`, with target/arch/program/memory/symbol/image/disassembly state, BAP instruction code/name/encoding/subinstruction metadata, instruction-kind flags, BAP-style property query/update aliases, and classification helpers on disassembly instructions, typed register/immediate/floating disassembly operands with conversion and normalized matching helpers, normalized first-instruction token/key helpers for block-local disassembly signatures, BAP-style disassembly block views with address/memory/leader/terminator/instruction-pair accessors and address-length comparison, BAP-style disassembly call membership summaries with entries/entry/belongs/siblings queries, initial BAP-style disassembly symbol tables with function span/owner/dominator/intersection lookup and explicit/implicit call maps, BAP-style block-level disassembly CFGs with node/edge degree, predecessor/successor, edge lookup, state-derived construction, and disassembly-edge export, a recursive-disassembly result facade with `cfg`/`errors`/`scan`/`run`/`global_cfg` wrappers over existing project drivers and branchers, CFG-to-symtab disassembly reconstructors with source-style `create`/`run`/`default`/`of_blocks` entry points and call-destination splitting, image/library specification accessors, image-owned relocation/external-reference/required-library/dynamic-link/symbol-value/load-bias/executable/base-address accessors, project-level relocation application that refreshes retained image and memory state, BAP-compatible filename tag lookup, typed storage tags over string-backed storage, whole-storage replacement, including bitvector tags and lossless string-, int-, uint64-, bool-, and bitvector-array tags, memory tagging, BAP-style string substitution for memory annotations over filename, section/symbol/block/address aliases with source-style `$name`/`${name}`/`$(name)` variable forms and escaped-dollar handling, and stored `$asm`/`$bil`/instruction metadata disassembly placeholders, symbol-table replacement, program and term mapping with typed term mark/unmark helpers, project-level wrappers and pass factories/registration for SSA, SSA destruction, IR flattening, Trivial Condition Form, and stub-call resolution transforms, library records with program-unit metadata, project input constructors/loaders with code/data memory union, base-address preservation, library-aware file loading, BAP-style loader registry aliases, symbol propagation, project-level load/file wrappers that realize `ProjectInput` loader results directly while preserving finish hooks and library loading, and BAP-style source-driven project creation that composes rooter, symbolizer, disassembly-driver, brancher, and reconstructor sources over `ProjectInput`, extension/priority metadata plus image-backend discovery and fallback after project-loader failures, idempotent project-facing built-in raw/Ogre/ELF input initialization including BAP's default x86-64 raw input target, BAP-style checked raw byte/string/native-file/binary input with raw offset, length, and entry-point handling, ELF project inputs enriched with DWARF function-boundary debug symbols including names resolved through referenced declaration DIEs when available, file convenience loading, filename/native-file-based selection including ELF image fallback, BAP-style rooters over image entries/project symbol starts/image symbol starts and named block starts, BAP-style symbolizers over callbacks/project symbols/images/named blocks with generated-name fallback, generated-vs-real-name partial ordering, and ambiguity filtering, set-like disassembly block insertion/removal and instruction replacement/removal by memory interval with address-, memory-, and block-scoped instruction lookup helpers plus exact edge removal, branch/CFG edge metadata plus named brancher registration and path-scoped, instruction-aware application over known and unknown disassembly destinations with load-bias address-domain translation for un-biased branchers, disassembly driver registration/discovery/application, explicit candidate-list fallback with per-driver failure reporting, plus idempotent built-in image-root, function-symbol, entry-point, project-root, raw-byte instruction, linear-sweep instruction, Basic instruction, and memory-block drivers for materializing project memory roots as disassembly blocks while keeping image-backed roots constrained to executable segments and raw memory available as byte-granular instruction records for brancher/substitution consumers, BAP-style linear sweep helpers over raw memory with checked and `_exn` entry points plus project wrappers, a low-level Basic disassembler facade with backend registration, predicate/state helpers, one-instruction decode, and raw-memory runs, an initial BAP-style reconstructor with named registration and one-shot project orchestration that maps materialized blocks to address-tagged IR block/subroutine terms including serialized block grouping, project-root and no-incoming-node reachable-edge grouping with known-root traversal boundaries, unrooted cyclic components, block lifting through the port of `bap_sema_lift` (`Blk::of_bil` BIL-to-BIR lowering with two-arm conditionals, loops, calls, interrupts and BIR normalization; `Blk::lift_insn`/`lift_block`/`lift_insns` instruction-boundary splitting, insn/address term attributes, calls with returns from instruction kinds, landing pads, intra/inter fallthroughs and delay slots; `Program::relink_calls`/`insert_synthetic` (also in the default reconstructor) and `reify_externals`; symtab-based `ProjectDisassemblyBlock`/`ProjectDisassemblyFunction`/`ProjectDisassemblySymtab::lift_ir` and `Project::lift_ir`), and disassembly edges (including interior instruction-address sources and targets) as direct IR gotos for blocks without lifted terminators, named dependency-aware pass registry with registration-order enumeration and explicit/autorun/pass-object execution, source-style transform callback and side-effect-only pass registration, run-once passes, pass registration/lifecycle event snapshots, pass run-count telemetry, typed project collators with callback registration, package-qualified registration/discovery, and BAP-style default descriptions for comparing alternative project versions, and typed analysis argument parsers with BAP-style bitvector literals, tuple helpers through five arguments, callback registration, package-qualified analysis registry/application, and BAP-style default descriptions.
- `project/source-driven creation`: Loader-backed, filename-backed, and native-file project creation helpers now compose explicit or named rooter, symbolizer, disassembly-driver, brancher, and reconstructor sources before returning a reconstructed project, attach filename tags to address-bearing reconstructed subroutines, and fold retained library program terms into the final project program with their source-unit filenames.
- `project/DWARF declaration references`: ELF project-loader regressions cover debug symbols named through `DW_AT_specification` and `DW_AT_abstract_origin` declaration references.
- `project/DWARF symbol merge`: ELF project loading merges matching DWARF function-boundary symbols into existing image symbols by name/address, preserving retained image metadata while enriching project symbols with debug status and missing DWARF size information.
- `dwarf/indirect DIE forms`: Public DIE attribute readers unwrap `DW_FORM_indirect` for scalar, string, address, block, flag, data16, range-list, location, index, section-offset, and reference payloads.
- `dwarf/DWARF4 locations`: DWARF data and ELF extraction preserve `.debug_loc`, and location attributes backed by `DW_FORM_sec_offset` resolve legacy DWARF4 location lists.
- `dwarf/FBI facade`: DWARF function-boundary extraction exposes BAP-style `DwarfFbi::create`/`functions` and `DwarfFunction::pc_lo`/`pc_hi` aliases over the existing function parser.
- `dwarf/FBI prefix recovery`: function extraction follows upstream `read_unit`: a malformed DIE or later unit header stops the scan but keeps the functions recovered so far (including earlier DIEs of the failing unit). `DwarfData::scan_functions` returns the prefix plus diagnostics, `DwarfData::iter_functions`/`DwarfFbi::iter` enumerate lazily unit by unit (forward cross-unit name references are yielded at the end) with an `on_warning` callback, and `DwarfData::functions` is an eager wrapper that errors only when nothing was recovered. `DwarfFbi::create` validates only the required sections and the first unit header/abbreviation table, parsing lazily afterwards. Divergences: `.debug_str` stays optional (upstream `Fbi.create` requires it; the port stops at the first `DW_FORM_strp` DIE when it is missing), an empty `.debug_info` is accepted, and function bounds are `UInt64` rather than width-bearing `addr` values (the unit address size is not carried on `DwarfFunction`).
- `dwarf/Fn identity`: DWARF function records expose BAP-style function-boundary identity helpers, including comparable range identity, hashing, rendering, module/version metadata, and a `DwarfFn` alias for source-oriented call sites.
- `dwarf/reference-class attributes`: Generic DIE reference enumeration recognizes additional DWARF5 reference-class metadata attributes for sizes, legacy bit offsets, bounds, counts, allocation/association state, strides, priority, trampoline, and small values, while preserving non-reference metadata such as data locations as non-reference fields.
- `dwarf/indirect high_pc`: Abbreviation value classification preserves `DW_AT_high_pc` fields wrapped in `DW_FORM_indirect`, and function-boundary extraction resolves indirect constant high-PC offsets.
- `project/create package scope`: Source-driven project creation accepts an upstream-style package override and otherwise uses the input filename package for reconstructed main-program TIDs.
- `project/info`: BAP-style project information streams expose realized input metadata, including unnamed-input empty filename events, retained input-level architecture and Ogre specs with empty specs for unknown create/custom and raw byte/string/file inputs, concrete arch/spec metadata for deprecated binary inputs, split code/data input maps, and reconstructed CFG, symtab, and program events over the local `future` stream substrate.
- `project/input metadata accessors`: Project inputs expose retained architecture and Ogre specification metadata directly, so callers can distinguish requested target overrides from image-derived architecture facts and observe empty specs on raw/custom inputs before project realization.
- `project/pass telemetry`: Project pass registration and start/success/failure/finish notifications now expose BAP-style streams while retaining deterministic event snapshots for tests and diagnostics.
- `project/input target overrides`: Image-backed byte, filename, and native-file project input loading now honors caller-provided concrete target metadata while treating explicit `unknown` targets like upstream BAP by deriving target metadata from the image/spec when available, and preserving custom project loader ownership of target selection.
- `project/input custom memory`: `ProjectInput::custom` accepts upstream-style separate code and data memory maps while preserving the port's existing combined memory argument.
- `project/input filename loaders`: Project input loaders can be registered as filename-based loaders, matching upstream loader callbacks that receive the path before any byte-read fallback, BAP-style loader registration aliases replace existing entries like upstream `Hashtbl.set`, filename-backed byte-loader selection preserves the supplied filename when the loader result does not set one, and available-loader enumeration appends project loader names with image backend names using BAP-style duplicate-preserving registry composition.
- `project/input library loading`: File-loaded project libraries carry BAP-style page-aligned program-unit bias metadata derived from the main input and preceding library memory spans, and explicit registered project loaders preserve BAP's `main :: dedup libraries` behavior while image/backend loading continues to deduplicate the main input with libraries.
- `project/state-seeded creation`: Source-driven project creation helpers accept a precomputed project state and reconstruct from it without rerunning disassembly drivers.
- `project/restore_state`: The deprecated upstream project state-restore hook is exposed as an explicit unsupported compatibility result that directs callers to top-level state persistence.
- `project/persistent metadata`: Project exposes an initial persistent codec for target, filename, string storage metadata, annotated memory maps, project symbols, library metadata/memory/symbols, and retained MoonBit IR program/disassembly state as a step toward the upstream `Data.S` project surface.
- `project/disasm accessors`: Project and library values expose BAP-style `disasm` facades over their retained disassembly state.
- `project/top-level API`: BAP-style top-level project facades delegate to the port's existing methods for state, target/arch/specification, program, symbols, storage, memory, disassembly, libraries, source-driven creation, mutation helpers, mapping, substitution, and restore-state compatibility.
- `project/pass run_exn`: Project passes expose a BAP-style raising `run_exn` wrapper that preserves checked pass execution, dependency handling, and lifecycle telemetry.
- `project/pass errors`: Project pass object execution reports BAP-style structured dependency and runtime errors while preserving string-returning project-level convenience runners.
- `project/memory_slot`: Project exposes the BAP-style public `unit-memory` Knowledge slot on program units with a flat memory-map domain and port-native persistence over retained memory annotations.
- `project/state slot`: Project state exposes the BAP-style `disassembly` Knowledge slot on program units with a flat domain and port-native persistence over retained disassembly/subroutine state; upstream bin_io-compatible byte compatibility remains future work.
- `project/collator registry`: Project collators expose BAP-style `desc` aliases and return registered collator metadata in registration order.
- `project/analysis registry`: Project analyses expose BAP-style `desc` aliases and return registered analysis metadata in registration order.
- `project/analysis grammar`: Project analyses expose a BAP-style grammar object with `to_string` rendering while retaining explicit raw-rule accessors for local callers.
- `abi`: BAP-style ABI dispatcher with newest-first project pass registration, stable `abi-name` metadata tag UUID, and an idempotent bridge into the project pass registry.
- `regular/trie`: String prefix and suffix tries retain BAP's byte-token semantics for UTF-8 text: `longest_match` reports byte lengths while the public MoonBit API still accepts and returns `StringView`/`String` keys.
- `bare`: initial Binary Analysis Rule Engine support with S-expression tuple parsing/rendering, rule specification parsing from strings/native files, RHS variable validation including wildcard and lexicographic unbound-variable rejection, BAP-style nonlinear variable matching, retained streaming hypotheses, reset, and translated allocator-rule regressions.
- `byteweight`: initial memory-oriented Byteweight classifier with BAP-style positive/negative substring statistics, max-length training over memory views, longest-signature scanning, threshold-based address discovery, Bayes-factor classification helpers, stats accessors, deterministic local byte codec plus a typed signature-database descriptor for trained deciders, and typed plus legacy signature database lookup/update helpers including alias-matching typed replacement.
- `project/builtins`: one idempotent built-in service registration entry point for loaders, branchers, disassembly drivers, reconstructors, and IR transform passes.
- `project/disassembly`: block-scoped edge lookup helpers for branch facts whose source or target lands at an interior instruction address.
- `project/disassembly-source`: BAP-style disassembly source context helpers for path applicability and bias-aware address creation from label/unit metadata, plus overwriteable rooter, brancher, symbolizer, driver, and reconstructor source registries with checked source wrappers.
- `project/disasm`: BAP-style top-level `Disasm` facade over project disassembly services, including checked and raising constructors for project, memory, image, and file inputs, CFG/error/instruction accessors, and state merge helpers.
- `project/disassembly basic`: (historical; the x86 decoding is now the LLVM 22 reimplementation described under "Decoder validation against LLVM 22", and several opcode names below changed to LLVM's, e.g. `JCC_1`, `CMOV32rr`, `SETCCr`, `TRAP`) The Basic `llvm` backend recognizes the upstream BAP x86-64 fixture instruction forms for `NOOP`, `SUB64ri8`, `CALL64pcrel32`, `MOV32ri`, `MOV64ri`, `MOV32rm`, `ADD64ri8`, and `RET`, including signed `CALL rel32` operands from the `call1` micro-fixture, plus the x86 one- and multi-byte no-op forms `90`, `66 90`, and `0F 1F /0`, plus default-no-op `ENDBR32`/`ENDBR64`, single-byte flag-control `CLC`/`STC`/`CMC`/`CLD`/`STD`, flag-transfer `SAHF`/`LAHF`, flag stack transfer `PUSHF`/`POPF`, software interrupt `INT3` and `INT imm8`, no-operand system `HLT`/`RDTSC`/`CPUID`/`XGETBV`/`SYSENTER` plus x86-64 `SYSCALL`, `B0+r imm8`, `B8+r imm32`, `A0-A3` accumulator absolute memory `MOV` loads/stores, `E8 rel32` call, `C3` return, `0x50+r` register `PUSH`, `0x68`/`0x6a` immediate `PUSH`, `0x86`/`0x87`/`0x90+r` register and memory `XCHG`, `0F B6/B7` `MOVZX`, `0F BE/BF` `MOVSX`, `0F 40-4F` `CMOVcc r,r/m`, `0F 90-9F` `SETcc r/m8`, `0F C8-CF` `BSWAP`, x86-64 `0x63` 32-bit-source `MOVSX` register/memory extension moves, `0x98`/`0x99` accumulator sign-extension forms, and short/near x86 conditional `Jcc` branches plus `JECXZ`/`JRCXZ` rel8 branches, `C6/C7 /0` immediate `MOV r/m`, `FF /2` indirect `CALL`, `FF /4` absolute `JMP`, `FF /6` register/memory `PUSH`, and `0x58+r` register `POP` forms for x86/x86-64 including REX-extended x86-64 registers, x86 one-byte and x86/x86-64 ModRM register and memory `INC/DEC{8,32,64}` forms, x86/x86-64 ModRM register and memory `NOT/NEG{8,32,64}` forms, x86/x86-64 ModRM register `ROL/ROR/RCL/RCR/SHL/SHR/SAR{8,32,64}` count-by-one, count-by-`CL`, and immediate-count forms plus memory-destination `ROL/ROR/RCL/RCR/SHL/SHR/SAR{8,32,64}` forms, x86/x86-64 ModRM register-to-register `MOV{8,32,64}`, arithmetic `ADD/SUB{8,32,64}rr` plus compact `ADD/SUB{8,32,64}rm`/`ADD/SUB{8,32,64}mr`, compact `ADC/SBB{8,32,64}rm`/`ADC/SBB{8,32,64}mr`, logical `OR/AND/XOR{8,32,64}rr` plus compact `OR/AND/XOR{8,32,64}rm`/`OR/AND/XOR{8,32,64}mr`, and comparison/test `CMP{8,32,64}rr` plus compact `CMP{8,32,64}rm`/`CMP{8,32,64}mr` and `TEST{8,32,64}rr` plus memory `TEST{8,32,64}mr` forms, generalized ModRM `ADD/SUB/ADC/SBB{8,32,64}ri8`/`ADD/SUB/ADC/SBB{8,32,64}mi8` and `ADD/SUB/ADC/SBB{32,64}ri32`/`ADD/SUB/ADC/SBB{32,64}mi32`, `OR/AND/XOR{8,32,64}ri8`/`OR/AND/XOR{8,32,64}mi8` and `OR/AND/XOR{32,64}ri32`/`OR/AND/XOR{32,64}mi32`, and `CMP{8,32,64}ri8`/`CMP{8,32,64}mi8`/`CMP{32,64}ri32`/`CMP{32,64}mi32` forms plus accumulator `ADD/SUB/OR/AND/XOR/CMP8ri8`, accumulator `ADD/SUB/OR/AND/XOR/CMP{32,64}ri32`, `TEST8ri8`, and accumulator/register `TEST{32,64}ri32` forms including REX-extended x86-64 operands and signed immediate rendering, generalized simple ModRM/SIB `LEA32r`/`LEA64r` effective-address forms and `MOV8rm`/`MOV32rm`/`MOV64rm` register-memory loads and `MOV8mr`/`MOV32mr`/`MOV64mr` memory stores with base/index/scale/displacement operands, x86 `LEAVE` and x86-64 `LEAVE64` frame teardown, x86-64 `REX.W B8+r imm64` immediate-move, and `EB rel8`/`E9 rel32` direct-jump forms used by project/reconstruction fixtures and structural recognition of the x86 SIMD `pcmp*`, `pmin*`, `pmax*`, and `pshufb` opcode forms from upstream tests, preserving instruction lengths, operand rendering, source-like `$asm`/`$bil` text where fixtures require it, and kind flags while leaving unknown forms and broader BIL AST lift wiring on future work; the built-in Basic project driver now reaches that LLVM-shaped decoder by default for x86/x86-64 project runs.
- `project/disassembly basic x86 SIMD fixture recognition`: The Basic `llvm` fixture decoder recognizes upstream-backed register-form vector moves `MOVUPS`/`MOVAPS`/`MOVDQA`/`MOVDQU`, `PALIGNR`, packed-bit `PAND`/`PANDN`/`POR`/`PXOR`, `PMOVMSKB`, `PAVGB`/`PAVGW`, packed register and immediate shifts including `PSRLDQ`/`PSLLDQ`, `PSUB*`, and `PADD*` forms alongside the existing `pcmp*`, `pmin*`, `pmax*`, and `pshufb` samples.
- `project/disassembly basic BIL lift`: Decoded Basic x86/x86-64 and translated ARM fixture instructions expose an initial typed BIL lift for no-op and default-no-op ENDBR instructions, empty `HLT`, unknown-result `RDTSC`/`CPUID`/`XGETBV`, encoded `syscall` calls for `SYSENTER`/`SYSCALL`, flag-control `CF`/`DF` assignment and `CF` toggle instructions, `SAHF`/`LAHF` low-flag transfers through `AH`, `PUSHF`/`POPF` flag images over the stack, software interrupt CPU-exception statements, 8-, 32-, and 64-bit register and memory-destination `INC/DEC` with x86 flag updates that preserve `CF`, `NOT` assignments and `NEG` arithmetic with x86 flag updates, register and memory-destination `ROL/ROR` with masked counts and guarded `CF`/`OF` updates, register and memory-destination through-carry `RCL/RCR` with masked counts and guarded `CF`/`OF` updates, register and memory-destination `SHL/SHR/SAR` with masked counts and guarded x86 flag updates, register, memory-destination immediate, compact memory/register, and register-register arithmetic for `ADD/SUB` with x86 flag updates plus `ADC/SBB` carry/borrow arithmetic, plus register, memory-destination immediate, and compact memory/register logical assignments with x86 flag updates, BAP-style `CMP` subtraction flag updates and `TEST` logical flag updates for register-register, compact memory/register `CMP`, memory-register `TEST`, memory-destination immediate, and accumulator/register immediate operands over `CF`/`OF`/`AF`/`PF`/`SF`/`ZF`, register and memory `XCHG` exchanges, `MOVZX`/`MOVSX` register and memory casts, `CMOVcc` register and memory-source conditional moves, `SETcc` register and memory condition materialization, `BSWAP` byte reversal, accumulator sign-extension moves, x86/x86-64 register, immediate, and memory-source pushes as stack stores plus stack-pointer updates, register pops as stack loads plus source-compatible stack-pointer updates, frame teardown via `LEAVE`/`LEAVE64`, 8-, 32-, and 64-bit immediate, register, and memory moves plus accumulator absolute memory loads/stores, LEA effective-address assignments, and immediate memory stores over base/index/scale/displacement operands, direct short and near jumps, conditional short and near jumps over BAP-style x86 flag formulas, `JECXZ`/`JRCXZ` zero-counter branches, direct calls with 32- and 64-bit target widths, indirect register/memory calls and jumps, returns, ARM data-processing/load-store forms used by the upstream `strlen` sample, and ARM `B`/`BNE`/`BX LR` control transfers, with block, disassembly-state, `Disasm`, and project-level facades that concatenate lifted statements while preserving explicit unsupported-instruction errors with address context.
- `project/disassembly basic x86 IMUL`: The Basic x86/x86-64 decoder recognizes `0x69`/`0x6b` two-/three-operand immediate `IMUL` forms for 16-, 32-, and 64-bit register and memory sources, including signed imm8/imm16/imm32 operands, operand-size override, REX-extended registers, and memory-source load kind flags; the BIL lift computes signed double-width products, truncates through `low`, sets `OF`/`CF` from truncation, and marks `PF`/`SF`/`ZF`/`AF` undefined like upstream BAP.
- `project/disassembly basic x86 IMUL r/m`: The Basic x86/x86-64 decoder also recognizes `0F AF` two-operand `IMUL r,r/m` forms for 16-, 32-, and 64-bit register and memory sources, including x86-64 default 32-bit operands, operand-size override, REX.W, REX-extended registers, and memory-source load kind flags; the BIL lift reuses the signed double-width product/truncation flag behavior while multiplying the original destination value by the register or memory source.
- `project/disassembly basic x86 MUL`: The Basic x86/x86-64 decoder recognizes `F6/F7 /4` unsigned one-operand `MUL r/m` forms for 8-, 16-, 32-, and 64-bit register and memory sources, including operand-size override, x86-64 default 32-bit operands, REX.W, REX-extended registers, and memory-source load kind flags; the BIL lift multiplies the accumulator by the source, writes the double-width `AX`/`DX:AX`/`EDX:EAX`/`RDX:RAX` result, sets `OF`/`CF` from the high half, and marks `SF`/`ZF`/`AF`/`PF` undefined like upstream BAP.
- `project/disassembly basic x86 one-operand IMUL`: The Basic x86/x86-64 decoder recognizes `F6/F7 /5` signed one-operand `IMUL r/m` forms for 8-, 16-, 32-, and 64-bit register and memory sources, including operand-size override, x86-64 default 32-bit operands, REX.W, REX-extended registers, and memory-source load kind flags; the BIL lift multiplies the accumulator by the source with signed extension, writes the double-width accumulator result, sets `OF`/`CF` from the high half following upstream BAP's one-operand helper, and marks `PF`/`SF`/`ZF`/`AF` undefined.
- `project/disassembly basic x86 DIV/IDIV`: The Basic x86/x86-64 decoder recognizes `F6/F7 /6` unsigned `DIV r/m` and `/7` signed `IDIV r/m` forms for 8-, 16-, 32-, and 64-bit register and memory sources, including operand-size override, x86-64 default 32-bit operands, REX.W, REX-extended registers, and memory-source load kind flags; the BIL lift checks zero divisors, computes double-width quotient/remainder, raises divide exceptions on quotient overflow, writes `AX`/`DX:AX`/`EDX:EAX`/`RDX:RAX` results, and marks arithmetic flags undefined like upstream BAP.
- `project/disassembly basic x86 ADC/SBB`: The Basic x86/x86-64 decoder recognizes compact register-register and register/memory, group-1 register and memory immediate, and accumulator-immediate `ADC`/`SBB` forms for 8-, 16-, 32-, and 64-bit operands including operand-size override, REX-extended registers, memory operands, and sign-extended immediate encodings; the BIL lift preserves source/destination temporaries, incorporates `CF` into carry/borrow arithmetic, updates the register or memory destination, and computes carry/overflow/auxiliary/parity/sign/zero flags with upstream-shaped formulas.
- `project/disassembly basic x86 byte CMPXCHG/XADD`: The Basic x86/x86-64 decoder recognizes `0F B0` byte `CMPXCHG r/m8,r8` and `0F C0` byte `XADD r/m8,r8` register and memory forms, including x86-64 REX-extended byte registers; the BIL lift reuses the compare/exchange and exchange/add helpers over 8-bit operands with the existing x86 flag updates.
- `project/disassembly basic x86 LZCNT/TZCNT`: The Basic x86/x86-64 decoder recognizes `F3 0F BD` `LZCNT r,r/m` and `F3 0F BC` `TZCNT r,r/m` forms for 16-, 32-, and 64-bit operands, including operand-size override, REX.W, REX-extended registers, and memory-source load kind flags; the BIL lift computes leading/trailing zero counts through the existing bit-count helpers, sets `CF` from zero inputs and `ZF` from zero results, and marks the remaining arithmetic flags undefined.
- `project/disassembly basic x86 MOVBE`: The Basic x86/x86-64 decoder recognizes `0F 38 F0/F1` `MOVBE r,m` and `MOVBE m,r` forms for 16-, 32-, and 64-bit operands, including operand-size override, REX.W, REX-extended registers, and memory load/store kind flags; the BIL lift maps these forms to big-endian loads and stores over the existing memory model.
- `project/disassembly basic x86 RDRAND/RDSEED`: The Basic x86/x86-64 decoder recognizes `0F C7 /6` `RDRAND r` and `/7` `RDSEED r` register forms for 16-, 32-, and 64-bit operands, including operand-size override, REX.W, and REX-extended x86-64 destination registers; the BIL lift writes unknown random values, assigns unknown `CF`, and clears `OF`/`SF`/`ZF`/`AF`/`PF`.
- `project/disassembly basic x86 privileged system ops`: The Basic x86/x86-64 decoder recognizes no-operand `INVD`, `WBINVD`, `WRMSR`, `RDMSR`, and `RDPMC`; the BIL lift treats the invalidation/write forms as no-ops and writes unknown `EAX`/`EDX` values for the read forms.
- `project/disassembly basic x86 RDTSCP/MWAIT`: The Basic x86/x86-64 decoder recognizes `0F 01 F9` `RDTSCP`, `0F 01 C8` `MONITOR`, `0F 01 C9` `MWAIT`, and `0F 01 FB` `MWAITX`; the BIL lift writes unknown `EAX`/`EDX`/`ECX` for `RDTSCP` and treats the monitor/wait forms as no-ops.
- `project/disassembly basic x86 UD2`: The Basic x86/x86-64 decoder recognizes `0F 0B` `UD2` as a control-flow-affecting trap and lifts it to invalid-opcode CPU exception vector 6.
- `project/disassembly basic x86 port I/O`: The Basic x86/x86-64 decoder recognizes accumulator port I/O forms `IN{8,16,32}` and `OUT{8,16,32}` over immediate and `DX` ports, including operand-size prefixes and REX-neutral x86-64 encodings; the BIL lift writes unknown accumulator values for `IN` and treats `OUT` as a no-op.
- `project/disassembly basic x86 return variants`: The Basic x86/x86-64 decoder recognizes near and far `RET` forms `C3`, `C2 imm16`, `CB`, and `CA imm16`, preserving optional stack-adjust immediates and lifting them through the existing return special statement.
- `project/disassembly basic x86 PAUSE`: The Basic x86/x86-64 decoder recognizes the `F3 90` `PAUSE` hint instruction and lifts it as a no-op.
- `project/disassembly basic x86 FWAIT`: The Basic x86/x86-64 decoder recognizes the `9B` `FWAIT` wait instruction and lifts it as a no-op, matching the upstream legacy floating-point lifter behavior.
- `project/disassembly basic x86 FPU control word`: The Basic x86/x86-64 decoder recognizes memory-form `FLDCW` and `FNSTCW`; the BIL lift loads and stores the modeled 16-bit `FPU_CONTROL` register.
- `project/disassembly basic x86 string move/store`: The Basic x86/x86-64 decoder recognizes no-repeat `MOVS{8,16,32,64}` and `STOS{8,16,32,64}` forms, including operand-size override and x86-64 REX.W variants; the BIL lift copies or stores through implicit `ESI`/`EDI` or `RSI`/`RDI` memory operands and updates indexes according to `DF`.
- `project/disassembly basic x86 string compare/scan`: The Basic x86/x86-64 decoder recognizes no-repeat `CMPS{8,16,32,64}` and `SCAS{8,16,32,64}` forms, including operand-size override and x86-64 REX.W variants; the BIL lift loads implicit operands, updates indexes according to `DF`, and reuses the existing subtract flag formulas for `CF`/`OF`/`AF`/`PF`/`SF`/`ZF`.
- `project/disassembly basic x86 REP string ops`: The Basic x86/x86-64 decoder recognizes `REP MOVS`/`REP STOS`, `REPE CMPS`/`REPE SCAS`, and `REPNE CMPS`/`REPNE SCAS` forms; the BIL lift wraps the single-step string operation in an `RCX`/`ECX` countdown loop with zero-flag continuation checks for compare/scan repeats.
- `project/disassembly basic x86 fences`: The Basic x86/x86-64 decoder recognizes the `0F AE E8/F0/F8` `LFENCE`/`MFENCE`/`SFENCE` ordering hints and lifts them as no-ops.
- `project/disassembly basic x86 cache flush hints`: The Basic x86/x86-64 decoder recognizes memory-form `0F AE /7` `CLFLUSH`, `66 0F AE /7` `CLFLUSHOPT`, and `66 0F AE /6` `CLWB` cache-line write-back/flush hints, including REX-extended x86-64 memory operands, and lifts them as no-ops.
- `project/disassembly basic x86 PREFETCHh`: The Basic x86/x86-64 decoder recognizes `0F 18 /0-/3` memory-form `PREFETCHNTA`/`PREFETCHT0`/`PREFETCHT1`/`PREFETCHT2` cache prefetch hints, including REX-extended x86-64 memory operands, and lifts them as no-ops.
- `project/disassembly basic x86 PREFETCHW`: The Basic x86/x86-64 decoder recognizes `0F 0D /0-/2` memory-form `PREFETCH`/`PREFETCHW`/`PREFETCHWT1` cache prefetch hints, including REX-extended x86-64 memory operands, and lifts them as no-ops.
- `project/disassembly basic x86 16-bit accumulator absolute moves`: Operand-size-prefixed `A1`/`A3` accumulator absolute memory moves now have x86-64 coverage for 16-bit `AX` data with 64-bit absolute memory addresses, and lift through the existing absolute load/store helpers over `mem64x8`.
- `project/disassembly basic x86 16-bit frame teardown`: Operand-size-prefixed `LEAVE` forms now decode and lift on x86 and x86-64, restoring 16-bit `BP` from the stack while using `ESP`/`mem32x8` or `RSP`/`mem64x8` for the stack-address side of frame teardown.
- `project/disassembly basic x86 16-bit flag stack transfers`: Operand-size-prefixed `PUSHF`/`POPF` forms now decode and lift 16-bit flag images on x86 and x86-64, using `ESP`/`mem32x8` for x86 stack addressing and `RSP`/`mem64x8` for x86-64 stack addressing.
- `project/disassembly basic x86 16-bit conditional moves`: Operand-size-prefixed `CMOVcc` forms now decode and lift for 16-bit register and memory-source moves on x86/x86-64, including x86-64 REX-extended word registers and condition reuse through the existing x86 flag predicate helpers.
- `project/disassembly basic x86 16-bit extension moves`: Operand-size-prefixed `MOVZX`/`MOVSX` forms now cover 16-bit destination register and memory-source extension from 8-bit operands, including x86-64 REX-extended byte registers; the BIL lift routes them through the existing typed unsigned/signed cast helpers.
- `project/disassembly basic x86 16-bit stack movement`: Operand-size-prefixed Basic x86/x86-64 stack forms now cover 16-bit register, immediate, and memory-source `PUSH` plus register `POP`, including x86-64 REX-extended word registers; the BIL lift separates pushed value width from stack address width so x86 uses 16-bit values with `ESP`/`mem32x8` and x86-64 uses 16-bit values with `RSP`/`mem64x8`.
- `project/disassembly basic SIMD semantics`: Decoded Basic x86 SIMD instructions, Basic decoded instruction streams, retained project disassembly states, and top-level projects can be applied to a project-level SIMD state backed by registers and vector memory, covering the translated upstream register-form vector moves `movups`/`movaps`/`movdqa`/`movdqu`, `pcmpeqb`, `pcmpgtb`, `palignr`, `pmin*`, `pmax*`, packed-bit `pand`/`pandn`/`por`/`pxor`, `pmovmskb`, `pavg*`, packed register and immediate shifts including `psrldq`/`pslldq`, `psub*`, `padd*`, and register-form `pshufb` value fixtures plus the `pshufb (%eax)` 16-byte alignment check.
- `project/disassembly basic ARM`: The Basic `llvm` backend recognizes fixed-width ARM fixture instructions for the translated BAP `strlen` sample, including immediate data-processing forms, word load/store forms with pre/post-index fixture writeback, direct `B`/`BNE` branch targets, and `BX LR` return semantics.
- `project/disassembly-rec`: Recursive disassembly refines decoded instruction streams into basic-block memory ranges at in-memory call, terminator, and branch boundaries, and synthesizes call target, direct branch target, and local fall-through edges for the translated BAP one-instruction `RET`/`CALL`, x86/x86-64 `call1; ret; ret; ret`, x86 near-jump target splitting, x86-64 push/jump block splitting, and ARM `strlen` CFG fixtures.
- `project/reconstructor`: reconstructed subroutines are marked with their first block address, image-entry reconstructed subroutines are marked with the BAP-style `entry-point` semantic flag, reconstructed blocks materialize supported Basic BIL assignments including register arithmetic, register logical ops, LEA effective-address calculations, register/immediate/memory-source stack-push stores, stack-pop loads, register moves, memory moves, and frame teardown as IR definitions, and Basic BIL direct/indirect/call/conditional jumps are used as fallback IR jumps for blocks without disassembly CFG edges while preserving CFG-edge jumps when present.
- `project/callgraph`: direct and resolver-backed project callgraph wrappers over IR `Call` jumps.
- `main_event/log facade`: The main event subsystem exposes a BAP-style `Log` namespace for message/progress emission and section reporter creation over the port's existing event stream.
- `image/ELF relocations`: MIPS `R_MIPS_REL32` entries, including `EM_MIPS_RS3_LE` objects, AArch64 P32 `R_AARCH64_P32_RELATIVE` entries, and additional LLVM-defined `RELATIVE` relocation types for M68k, ARC, Xtensa, Hexagon, AMDGPU, VE, and C-SKY are recognized as image-relative relocation metadata alongside the existing architecture-specific relative relocation set.
- `image/ELF dynamic relocations`: Section-header-less `PT_DYNAMIC` fixtures now cover defined dynamic-symbol relocations as image target relocations with explicit addends, alongside relative relocations and undefined-symbol external references.
- `image/ELF target metadata`: ARM ELF inputs now refine to BAP-style ARMv7 target variants, SPARC32PLUS, Hexagon, CUDA/NVPTX, XCORE, and AMDGPU machine tags resolve to existing target metadata, and all preserve ELF OSABI-derived system/ABI metadata and fallback behavior.
- `image/facades`: BAP-style image value tag descriptors expose the source tag names and UUIDs for segments, symbols, sections, code regions, and image specifications, `Segment` and `Symbol` expose Regular-style comparison, equality, hashing, rendering, and module-version metadata, while `Spec::from_arch` and `Spec::slot` mirror the upstream Ogre unit-spec facade with a mergeable, persistent Knowledge domain.
- `image/top-level API`: BAP-style top-level loading and image accessor facades delegate to the port's `Image` methods, including checked total segment and symbol-memory lookup wrappers.
- `image/legacy backends`: The deprecated BAP image backend records for permissions, locations, segments, sections, symbols, and backend images have MoonBit facades, with a bridge that registers legacy byte loaders through the image backend registry while attaching generated Ogre spec metadata.
- `image/loaders`: BAP-style `KB::register_loader` adapts byte- and filename-backed Ogre document callbacks into the image loader registry while preserving duplicate-name rejection, and image backend discovery mirrors BAP's shared backend/loader namespace while retaining backend-only name discovery for local callers.
- `image/symbol lookup`: BAP-style checked facades expose total segment and symbol-memory lookups while preserving optional APIs for missing mappings, including explicit non-contiguous symbol chunks from Ogre specs and legacy image backends.
- `image/Scheme`: BAP-style Ogre scheme descriptors expose image field and attribute names for architecture metadata, regions, symbols, mappings, relocations, and dynamic references, with checked declaration and fact rendering that feeds the local Ogre parser and image loader.
- `traces/API aliases`: Trace registration exposes BAP-style `Trace::register_tool` and `Trace::register_proto` helpers, with tool name and supported-tag accessors over the port's structured trace tool descriptors.
- `traces/registry semantics`: Trace tool, protocol, reader, stream-reader, and writer registration now rejects duplicate names like BAP's `add_exn`-backed registries, while exposing checked `try_register_*` variants for recoverable MoonBit callers.
- `traces/event payloads`: BAP-style event payload constructor facades now cover `Syscall`, `Exn`, `Call`, `Return`, and `Modload` alongside the existing `Move`, `Chunk`, and `Location` helpers, with `Exn` rendering delegated through the trace exception representation.
- `types/attributes`: common BAP-style term metadata and subroutine semantic flags over the string-backed MoonBit IR attribute map.
- `types/lookup`: BAP-style option and checked lookup helpers for subroutine, argument, block, phi, def, and jump terms by tid and direct-child index.
- `types/tids`: Named, address-derived, and interrupt-vector TIDs now preserve package-qualified identity, parse/render escaped package-qualified names, and round-trip package metadata through project IR persistence.
- `types/packed SIMD words`: Word-level packed equality, greater-than, min/max, and x86 `pshufb` byte-shuffle helpers cover the translated upstream x86 SIMD value regressions for `pcmpeqb`, `pcmpgtb`, `pmin*`, `pmax*`, and register-form `pshufb`, providing executable data semantics for later disassembly-lift wiring.
- `types/stub-resolver`: translated BAP alias-graph regressions for dangling aliases, reverse aliases, cross-reference aliases, many independent pairs, ambiguous implementations, and disconnected complex intersections.
- `types/block-edit`: BAP-style term sequence accessors, positioned insertion, before/after slices, and rewrite/change helpers for program subroutines, subroutine arguments/blocks, and block definitions/phis/jumps.
- `types/BIL normalization`: Effectful memory-load branch and loop conditions are hoisted into virtual temporaries, with loop conditions refreshed at the end of the normalized body, expression hoists from `Let` bodies remain scoped under the original bound variable, and `normalize_exp:true` expands wide BIL memory loads/stores into byte-width operations.
- `types/BIL dead virtual pruning`: Translated BAP simple-liveness regressions now cover dead virtual assignments between live definitions and virtuals that remain live only through branch conditions.
- `types/Live`: `Live::compute(sub, keep?)` ports upstream `Bap_sema_free_vars.Live` (backward fixpoint over the tid graph with pseudo start/exit nodes, exit seeded from `keep` and `Out`/`Both` argument free vars, upstream phi convention where the phi lhs is killed/operands used in each predecessor) with `ins`/`outs`/`defs`/`uses`/`fold`/`blks`/`vars`/`solution`/`Show`, plus `Sub::free_vars`/`Sub::compute_liveness`; `sub_liveness`/`sub_live_in_vars`/`sub_external_vars` are wrappers over it. SSA conversion is rooted at the pseudo start node (phis at entry blocks with back-edges, renaming of disconnected components). Known divergences: dominator-tree children and phi operands follow block order rather than upstream `Tid` order (affects index numbering only), let-bound variables are left unrenamed instead of renamed together with their binder, and `Term::sub_free_vars` stays a syntactic union (upstream-equivalent is `Sub::free_vars`).
- `types/BIL constant propagation`: Translated branch/jump regressions cover BAP's selected-branch fact retention when the statically skipped branch exits through a jump.

- `core_theory/RISC-V target roles`: RISC-V floating-point ABI aliases (`FA`, `FS`, `FT`) are included in target variables, alias-origin tracking, and argument/result/caller-saved/callee-saved role helpers, and fixed `gp`/`tp` registers carry reserved-role metadata with `tp`/`x4` as the thread pointer.
- `core_theory/LoongArch target roles`: LoongArch floating-point ABI aliases (`FA`, `FT`, `FS`) are included in target variables, alias-origin tracking, and argument/result/caller-saved/callee-saved role helpers.

- `mc`: shared decoded-instruction (`Insn`/`Op`) model mirroring BAP `Disasm_expert.Basic` operands, plus a target-keyed lifter registry; `project` bridges `ProjectDisassemblyInstruction::to_mc_insn`/`lift_registered_bil` onto it.
- `thumb`: port of `plugins/thumb` emitting BIL from `@mc.Insn` for all 54 upstream opcodes (ALU with NZCV flags, loads/stores incl. pc-relative literal loads, LDM/STM/PUSH/POP incl. pop-to-pc return, B/Bcc/BL/BLX/BX/CBZ/CBNZ, sign/zero extensions); predicated instructions update only their destination through `ite`, matching upstream. Registers `thumb`, `thumbv7`, `llvm-thumb`.
- `systemz`: port of `plugins/systemz` lifter (`LR` low-word register move over 64-bit `R0`..`R15`), registered as `systemz`, `systemz9`, `llvm-systemz`.
- `mips`: port of `plugins/mips` covering all 143 registered opcodes (arithmetic, branch, conditional, divide, load, logic, multiply, shift/rotate, store) for MIPS32/MIPS64 in both endiannesses, via a private RTL layer lowered to BIL with upstream's implicit width/sign casts; delay-slot metadata via `delay_slot`, `lift_checked` type-checking like `mips_main`, the portable GNU calling-convention data from `mips_abi`, and `register()` for `mips`/`mipsel`/`mips64`/`mips64el`. Upstream TODOs (LWL/LWR/SWL/SWR family, EXT/INS) remain unmodeled.
- `ogre`: port of BAP's Open Generic REpresentation with typed `Type`/`Field`/`Scheme`/`Attribute` values (tuple-based schemes replace OCaml variadic schemes), persistent `Doc` documents with upstream-compatible sexplib text parsing/printing (validated byte-for-byte against upstream `Doc.pp`) and YAML output, the query DSL (`select` with `where_`/`join`, expression simplifier, qualified/unqualified field joins), and an `Ogre[A]` monad (`require`/`request`/`foreach`/`collect`/`provide`/`eval`/`exec`) plus a direct-style `Context`. The `Make(M)` functor and file IO helpers are not ported; `image` still carries its own simplified Ogre document model pending migration.
- `arm`: port of `lib/arm` (A32 legacy lifter) with typed opcode enums covering all 192 upstream opcodes (Thumb-2 `t2` names recoded to ARM forms like upstream), BIL lifting with modified-immediate carry rules, flag writes only for `CPSR` flag operands, conditional execution as `ite`/`if`, PC-read `+8` and PC-write jumps; machine-state variables and CPU predicates; plus the self-contained AAPCS32/AAPCS64 argument layout rules from `plugins/arm/arm_gnueabi.ml`. ABI installation over C types/Primus and the AArch64/Thumb Primus-Lisp semantics are pending.
- `arm`/`thumb`/`aarch64` decoders (replacing LLVM MC): native A32 (`@arm.decode_a32`), T32 (`@thumb.decode_t32`, Thumb-1 + Thumb-2 with IT blocks tracked by `ItBlock`) and A64 (`@aarch64.decode_a64`) decoders producing `@mc.Insn` values with LLVM opcode names and operand lists as LLVM's disassemblers build them (pred/cc_out operands, SORegOpc/AM2/AM3 packing, Thumb s_cc_out, AArch64 shifter/extend/logical-immediate encodings, kinds, raw bytes, assembly). A32 covers the ARM lifter's opcodes, T32 the Thumb lifter's and Thumb Lisp semantics' opcodes plus the Thumb-2 data processing/load/store/multiply/branch groups, A64 every opcode of the AArch64 Lisp semantics plus siblings in the same encoding groups. `register_decoder()` in each package registers the decoder (`arm-a32`, `arm-t32`, `aarch64-a64`) with `@mc.register_decoder`, which `ProjectDisassemblyBasic::lookup` (and hence `bap mc`/disassembly) consults. Not decoded: coprocessor, VFP/NEON/SIMD/SVE, saturating/parallel arithmetic and most system instructions.
- `mips` decoder (replacing LLVM MC): `@mips.decode` decodes MIPS32/MIPS64 Release 2 (and, with `r6=true`, Release 6) code in both byte orders into `@mc.Insn` values with LLVM's `Mips` opcode names (including LLVM's quirks such as `TTLTIU`, `DEXT` for `dextm`/`dextu`, OR-ed `clz`/`clo` destination fields), operand orders and register classes (`GPR32`/`GPR64`, `FGR32`/`AFGR64`/`FGR64` by FPU mode, `FCC`, `COP0`/`COP2`, `HWR29`), branch-target operands of `DecodeBranchTarget`, `MCInstrDesc` kinds, and `MipsInstPrinter` assembly with its aliases (`nop`, `move`, `b`, `beqz`, `bal`, `jalr $25`, `lapc`, ...). Covers the integer ISA, COP0 moves/control, COP1/COP1X, MIPS64 paired singles and all Release 6 opcodes the lifter models; differentially checked against `llvm-mc` 22 on ~60k encodings per mode (355 LLVM-verified per-opcode samples in the tests, 345 opcodes). `register_decoder()` installs it in the `@mc` decoder table. The lifter accepts LLVM's spellings of the R6 opcodes and the `*64` MIPS64 variants (`opcode_aliases`), models `AUI` and the one-operand R6 `BAL`, and LLVM's `[rt, rt, base, offset]` store-conditional layout (setting the success flag). Not decoded: EVA, MSA, DSP, microMIPS/MIPS16 and COP2/COP3 arithmetic (upstream's EVA/`NOP`/`NOT`/`JALR64`/`LLX` lifter entries are never produced by LLVM). Semantics deliberately fixed for LLVM's operands are listed under "Deliberate upstream semantic fixes".
- `riscv` decoder (replacing LLVM MC): `@riscv.decode` decodes RV32/RV64 IMAFDC with Zicsr/Zifencei and `mret`/`sret`/`wfi`/`sfence.vma` into `@mc.Insn` values with LLVM's `RISCV` opcode names (compressed instructions as `C_*` opcodes with their LLVM operand lists), `X0`..`X31`/`F*_F`/`F*_D` register names as the Lisp semantics expect, `MCInstrDesc` kinds, and `RISCVInstPrinter` assembly (compressed instructions printed as their expansions, LLVM's aliases, CSR names extracted from LLVM, rounding modes); agrees with `llvm-mc` 22 on every 16-bit encoding and ~100k random 32-bit ones (191 LLVM-verified samples in the tests). `register_decoder()` installs it; the `riscv` plugin registers it when enabled. End-to-end tests decode, lift with the `riscv.lisp` semantics and execute; `bap mc --arch=riscv64/mips/...` decode and lift. Semantics deliberately fixed in `riscv.lisp` are listed under "Deliberate upstream semantic fixes".
- `microx`: port of `lib/microx` with a local open-hook BIL/BIR interpreter (`Expi`/`ExpContext`, Bot semantics, byte-cell storages), a policy-driven concretizer (`Random`/`Fixed`/`Interval`) and the `Conqueror` exploring executor (checkpoints on jump destinations, backtracking to the smallest unvisited checkpoint, `max_loop`/`max_steps` bounds, deterministic mode).
- `bml`: port of `lib/bap_bml` plus the `plugins/map_terms` parser and features: predicate/mapper registries, the standard marker/color/taint/comment library, `term-addr`/`term-tid`/`term-name`/`term-parent`/`def-lhs`/`def-uses`/`unset-attr`, BML surface-syntax parsing with upstream error messages, and `map_program`/`map_terms` over IR programs.
- `text_tags`: port of `lib/text_tags` including a faithful OCaml `Format` pretty-printing engine (boxes, breaks, semantic tags, `print_format` directives) and the html/blocks/attr/none tagging modes with registration and scoped installation; tabulation boxes are not ported.
- `recipe`: port of `lib/bap_recipe` with recipe loading from directories (`option`/`parameter`/`extend`/`command` items, `descr` docs), `Buffer.add_substitute`-style parameter substitution, recursive extension, argv generation and a pluggable native/in-memory filesystem; zipped recipes are reported as unsupported.
- `powerpc`: port of `plugins/powerpc` with an RTL layer lowered to BIL (implicit casts, partial/CR-field assignment, unrolled `foreach`, `switch`), all 13 instruction groups (236 LLVM opcodes plus `_rec` aliases), 32/64-bit register models and CPU predicates, type-checked `lift32`/`lift64`/`lift64le`, the translated upstream `lib_test/powerpc` suites (each fixture is also decoded from its upstream byte encoding), the 32-bit System V argument layout from `powerpc_abi`, and a native decoder replacing LLVM MC (`decode`/`decode_word`, registered as the `powerpc` `@mc` decoder by `register_decoder`) that produces the LLVM opcode names, operand lists, kinds and assembly for every lifter opcode (`gBC`/`BDNZ`/`BLR`-style branches, `_rec` record forms, 32-bit `ADDI`/`ADD4` variants and `X` registers for 64-bit only instructions); other encodings decode as invalid. The Primus-Lisp `powerpc.lisp` semantics are pending.
- `bap_main`: port of `Bap_main.Extension` with typed value converters (OCaml numeric syntax, Cmdliner error messages), `--<plugin>-<name>` configuration parameters/flags with command line > `BAP_*` environment > config file > default precedence, typed command grammars (`Command::args().add(...)`), a Cmdliner-compatible argv parser (prefixes, glued short flags, `--`, `--no-<plugin>`, `--help`, `--version`), plain-text manuals, and a static plugin registry replacing dynlink loading (selected by `requires`/`features`). Recipes are resolved through a callback; wiring it to the `recipe` package is pending.
- `image/ogre migration`: image specifications are now `@ogre.Doc` values; `Scheme` exposes typed Ogre fields/attributes with `Region[A]`, spec derivation reads facts through typed attributes, and images built from metadata (ELF, raw, legacy backends, `Image::create`) describe themselves via `Spec::of_image` (upstream `Legacy.provide_image`). LLVM-specific loader facts and upstream's join-query region matching remain to do.
- `primus`: the Primus machine core (non-Lisp) with an explicit-frame scheduler replacing upstream's continuation monad: fork/switch/kill clone a fork's persistent state bag and control stack in O(1) and take effect at interpreter step boundaries (`then` continuations cover upstream's `fork () >>= k` patterns). Includes the BIR interpreter (sub/arg/blk/phi/def/jmp, call/return prompts, interrupts, all BIL expression forms) with all upstream observations, Env, Memory (banks, regions, permissions, generators), Linker (tid/name/address, unresolved handler), trap handlers, typed per-fork/global/cross-fork states, observations/providers/watchers, MCG generators and iterators, systems (`defsystem` parsing), components, jobs and the legacy `load-binary`/`legacy-main` setup. The Knowledge-bound `Analysis` machine is not ported.
- `c`: port of `lib/bap_c`: the C type AST with qualifiers/attributes and byte-for-byte upstream printer, an open `Ruler` trait for sizes/alignment across data models, `Data`/`Layout` with padding, a `TypeMapper` visitor trait with early-exit search, lossless term attributes (`c.data`/`c.layout`/`c.type`/`c.proto`), default GNU attribute handlers, the external parser registry, and the C ABI layer (`apply` inserting typed/coerced/hidden args, processor/data-model registries, API processor, `Arg[A]` argument-passing DSL with arenas/pairs/split/memory/hidden, `define_abi` via `@abi.register_pass`).
- `c_parser`: a native replacement of the FrontC-based `plugins/frontc_parser` (plugin `c-parser`, provides `api`/`c`/`parser`): a lenient C lexer, a preprocessor subset (comments, line continuations, object- and function-like `#define` with `#`/`##`/`__VA_ARGS__`, `#undef`, `#if`/`#ifdef`/`#ifndef`/`#elif`/`#else`/`#endif` with integer expressions and `defined`, `#include "..."`/`<...>` through the `bap_main` file system and `--c-parser-include` directories, `#pragma once`, `#error`), a recursive-descent parser for C declarations into a FrontC-like `Cabs` AST (typedefs, struct/union/enum definitions and bit fields, prototypes with `...` and old-style identifier lists, pointers/arrays/function pointers, `const`/`volatile`/`restrict` and their GNU spellings, storage classes, GNU `__attribute__((...))`, `__asm__` labels, `__extension__`, `_Static_assert`, skipped function bodies and initializers), and the exact upstream mapping to `@c` types (single-declarator declarations only, tag table with one-level resolution of empty compounds, `const`/`volatile` propagation into structure fields, `[u]intN_t` from the data model, OCaml integer literal reading). Registered in the `@c` parser registry by `provide`. Deviation: no external `--frontc-parser-preprocess` (cannot spawn processes).
- `plugins/api`: port of `plugins/api/api_main.ml`: API specification directories (`<dir>/<lang>/<name>`) from `--api-path`, `BAP_API_PATH`, the bundled site, and the data directories, `--api-list-paths`/`--api-show` (which then exit), and the autorun `api` pass (deps `abi`) that parses the API files of every registered API processor and applies the C prototypes to the subroutines through the target's ABI (the `optimization` and `glibc-runtime` passes depend on it as upstream). The upstream API headers (`c/android.h`, `gnu.h`, `posix.h`, `windows.h`) are embedded (`plugins/api/scripts/embed_api.py` generates `bundled_api.mbt`) and served from `<prefix>/share/bap-common/api` by a `bap_main` file-system overlay. Deviations: the deprecated `--api-add`/`--api-remove` are not ported; an API that cannot be applied fails the pass instead of exiting.
- `plugins/x86_abi` + `plugins/arm_gnueabi`: the C calling conventions that the upstream `x86` (`X86_target.Abi`: cdecl16/pascal16, cdecl, fastcall, pascal, watcom registers, ms64, System V AMD64 with eightbyte classification) and `arm` (`arm_gnueabi.ml`: AAPCS32/AAPCS64 with the ARM data model) plugins install with `C.Abi`, installed by the frontend's service registration. Upstream limitations kept: System V passes integers only in registers (a seventh integer argument rejects the prototype), and parameters passed by a hidden reference make the argument count mismatch so no arguments are inserted.
- `plugins/resolve_indirects`: the `resolve-indirects` pass (plugin of the same name, not autorun) substituting loads from constant addresses with the word stored in the first project memory region containing the address (with the region's endianness; unreadable loads are kept; the address is checked before its own subexpressions are resolved, as with upstream's `Bil.mapper`). Upstream bug: `resolve_indirects_main.ml` does not compile (`main` is a partial application of `Project.map_program` whose mapper refers to the unbound `proj`) and has no `dune` file; the port implements the evident intent.
- `mc/lifter registry`: lifters are `Provider`s selected by a `Context` (core-theory target + encoding language) in a `Registry` (replace-by-name, first non-`Unsupported` provider wins, optional BIL type validation), returning `Lifted` results that carry delay-slot counts and interworking destination encodings. Thumb (`t*`) and ARM (`t2*`) providers compose on the t32 encoding as upstream.
- `project/lift dispatch`: instruction/block/state/project lifting goes through the registry (built-in thumb, arm, mips, powerpc, systemz providers) with fallback to the Basic x86/ARM lifter; delay-slot branches are moved after their delay-slot instructions with condition/target capture; reconstruction keeps per-instruction successes and records failures in `Project::lift_errors()`.
- `core_theory/role query performance`: target register-role tables are memoized per target identity, making `Target::regs`/`reg`/`vars_with_role` cheap enough for ABI and lifter code paths.

- `plugins/optimization`: SSA-based constant propagation and dead-code elimination at levels 0–3 (virtuals, flags, physical registers) with cross-subroutine liveness protection and unreachable-branch/block removal, registered as the autorun `optimization` pass.
- `plugins/callsites`: synthetic argument definitions at call sites (inputs before the call, outputs in the return block) carrying origin/address/insn attributes; pass `callsites` after `abi`.
- `plugins/warn_unused`: `warn-unused-taint`/`-print`/`-mark` and the chained `warn-unused` pass with a string encoding for the per-register taint map.
- `plugins/glibc_runtime`: `__libc_start_main` discovery/creation from the entry point and the `glibc-runtime` pass recovering `main` from the start routine's first argument.
- `plugins/dump_symbols`, `plugins/callgraph_collator`, `plugins/read_symbols`, `plugins/relocatable`, `plugins/report`, `plugins/dependencies`: symbol dumps, callgraph diffs between versions, symbol-file rooters/symbolizers, relocation/PLT-based stub naming and MIPS roots, ANSI progress reporting over `main_event`, and the `dependencies` command (imports/exports/libraries with YAML/sexp/JSON/graph output).
- `plugins/constant_tracker`: the static-constant tracking policy and primitives, not yet attached to the `primus` machine.
- `plugins/cxxfilt`: the `bap:c++filt` demangler (upstream shells out to `c++filt -p`; here the native `demangle/itanium` demangler without parameters) plus `bap:itanium` (with parameters), declared by the `cxxfilt` plugin with the upstream `c++`/`demangler`/`c++filt` tags. `--print-demangled-with` resolves demanglers by unqualified name, as upstream.
- `plugins/print`: upstream-faithful BIR/BIL/expression printers (driven through the `text_tags` Format engine), IR/project ADT, BIL ADT/sexp, callgraph and CFG DOT, symbol tables, asm/decoded listings, `--print-matching` filters, demangling, and a project/term writer registry with the `--print-*` options. The `knowledge` writer and `--print-semantics` are not covered.
- `plugins/phoenix`: phoenix block naming, BIL optimizations, whole-program DOT CFGs, HTML BIL/assembly pages, JSON indexes and site layout rendering, with native-only on-disk storage.
- `plugins/emit_ida_script`: IDA Python script generation for colors, comments and memory annotations with upstream substitution and escaping.
- `taint`: port of `lib/bap_taint` on the `primus` machine: kinds/objects, the per-fork persistent tracker (direct relations by value id, indirect by address), `taint-attached`/`taint-finalize` observations, per-kind propagation policies (by-computation and exact), the conservative GC, and the `tainted-regs`/`tainted-ptrs` attribute codec shared with `bml`.
- `plugins/primus_taint`, `plugins/taint`, `plugins/primus_propagate_taint`, `plugins/propagate_taint`: taint components and a named primitive table for later Lisp binding, strain-based seeding pass, Primus taint intro/mapper/marker components, and the legacy microx-based BIL taint propagator with the `propagate-taint` pass. The `.lisp` taint sources/sinks await Primus Lisp.
- `plugins/primus_*` (Lisp-free): greedy, round-robin, wandering and exploring schedulers; promiscuous mode (forking at trivial-condition branches and direct-return calls, division-by-zero handler); `max-length`/`max-visited` limits; `primus_track_visited` + `primus_mark_visited`; `primus_region`/`primus_dictionary` primitive tables linked into the machine; `primus_random` generators and randomizers; `primus_loader` (stack, argv/envp, segments, relocations, brk/endp); `primus_print` observation tracing and tracebacks; `primus_systems` (embedded `core.asd`, `.asd` loading, listing commands); `primus_x86` register/PLT setup and `primus_powerpc` initialization. The unreleased `lib/bap_primus_machine` prototype is not ported.
- `native_io/file system`: stat/lstat, sorted directory listing, mkdir(-p), removal, rename, chmod, getcwd, temporary files/dirs, atomic writes and flock-based locks (native only, error stubs elsewhere); `recipe`, `phoenix` and `bap_main` use it.
- `regex`, `sexp`, `digest`: shared PCRE-subset regular expressions, sexplib-compatible S-expression reading/compact printing, and MD5 (RFC 1321) backing `regular` digests, replacing per-package copies.
- `plugins/cache`: upstream on-disk cache (`config.3` in upstream's binary layout, read-only `data/<digest>` entries written by atomic rename, size-based random GC with a GC lock, `bap cache` command) installed as `regular`'s cache service.
- `beagle` + `plugins/beagle`: the Beagle prey library (word sets, prey, `beagle-prey`/`beagle` observations, beagle attribute keys, static strings) and the `bap:beagle-hunter` Primus component (stored bytes fed to the `strings` detector per machine, abort on kill, dictionary/word unscrambling cached across machines, printing) with the `beagle` pass and plugin options. Upstream's disabled variable handler is not ported; the attributes are term attributes holding S-expressions instead of value tags.
- `xml`: a small streaming XML reader (Xmlm-style `Dtd`/`ElStart`/`ElEnd`/`Data` signals, namespaces, entities and character references, CDATA, comments/PIs, DOCTYPE, `strip` mode, positions) with a tree API.
- `plugins/patterns`: Ghidra-style byte patterns: the upstream XML parser combinators and grammars (`patternconstraints.xml` tables of contents with compilers, `patternlist` with `pattern`/`patternpairs`, pre/postpatterns, size constraints), ditted bit/nibble patterns with masks, target specifications (BAP names or `arch:endian:bits:variant[:compiler]`), the upstream matcher (including its end-of-memory stop and per-address action pruning), digest-deduplicated repository selection over a pluggable file system, actions dispatched to the Primus Lisp methods of `bap:patterns-action` (the embedded `pattern-actions.lisp` plus user sources, `patterns-attribute` and `promise-function-start` primitives, `(patterns enabled)` context) with the native handlers (`funcstart`/`possiblefuncstart`) as fallback, the outcome as `patterns` rooter/symbolizer sources for an image, and the `match-patterns` command.
- `plugins/bil`: the BIL pass pipeline (`bnf1`, `bnf2`, `constant-folding`, `constant-propagation`, `prune-dead-virtuals`; normalization/optimization levels, `--bil-passes`, `--bil-list-passes`, type-checked fixpoint application, installed as the `bil-passes` post-lift hook of `project` instruction lifting), `--bil-enable-intrinsics` specifications and intrinsic calls, the BIL lifter wrapper over `mc` registries with relocation fixups, reflection of BIL through the effect part of the Core Theory (`EffAlgebra`) into BIL, jump destinations (`jump-dests`), and BIR construction via the shared `@types.Blk::of_bil` lowering. On the Core Theory algebra: the `bap:bil` theory (`Core::bil` with the `let_` simplification) and `bap:bil-fp-emu` (the IEEE-754 emulation of `Bil_float`/`Emulator` as a theory transformer; binary32/64 arithmetic and binary64 square roots match native results, binary32 square roots and `is_inf` keep upstream's bugs), the `bap:bir` (IR graphs of effects) and `bap:jump-dests` theories, the KB rules `bil-lifter` (with `Theory.Pass.Desugar` re-denotation and relocation fixups), `machine-code`, `bil-semantics` and `reify-ir` over `insn`/`bil-code` slots of program objects, and KB-resolved external names. Relocations are provided per unit (`provide_relocations`) instead of being promised from the image specification.
- `bap` executable (`cmd/bap`, `frontend`, command plugins): the upstream `src/bap_frontend.ml` (usage message, `.`, `list <entity> [--filter]`, `config`, exit codes, `--recipe`) over a static plugin table (`frontend/plugins.mbt`, one line per plugin) and a pure `@frontend.run(argv, env?, fs?, out?, err?, read_line?, write_file?, plugins?) -> Int`; `cmd/bap` is the thin native main (C stubs for stdout/stderr, stdin lines and the exit status). Command plugins: `plugins/disassemble` (`disassemble`/`compare`: loader/target/libraries, `-p`/old-style `--<pass>` passes with autoruns and dependencies, `-d<fmt>[-<ver>][:<file>]` dumps through the `print` writers, `--print-missing`, `--project`/`--update` knowledge base as the persisted project, the `recursive` driver (recursive descent over the Basic decoder) plus `--disassembler`/`--rooters`/`--symbolizers`/`--branchers`/`--reconstructor` selection that otherwise combines all registered sources and root providers), `plugins/mc` (`mc` with all input formats and stdin, `--arch`/`--target`/`--encoding`/`--triple` groups, `--show-{insn,bil,bir,sema,kinds,size,addr,memory,invalid}`, `--only-one`, `--stop-on-errors`, trailing data; `objdump`), `plugins/specification`, `plugins/recipe_command` (`recipes`, `print-recipes`), `plugins/analyze` (directives, the core `units`/`subroutines`/`subroutine`/`instructions`/`instruction` commands over the persisted project, scripts and a line-based REPL without line editing/history), `plugins/run` (the Primus job-queue pass with entry points, argv/envp, systems, isolation, repetitions and `until-visited-all`), `plugins/trace`, `plugins/strings`, and `plugins/byteweight` (a root provider of `disassemble`). Knowledge caching through the cache service and the knowledge-base semantics printers (`--show-knowledge`, full `KB.Value` slots) are not available.

- `primus_lisp`: port of Primus Lisp: located s-expression reader and pluggable loaders (embedded library, in-memory, native paths), all top-level forms with macros/substitutions/constants/packages, contexts and five-stage overload resolution, a union-find type checker, a continuation-passing interpreter over the Primus frame stack (forkable mid-function, dynamic scoping via cleanup frames, advice, externals replacing binary subroutines, signals, standard/IO/IEEE754 primitives), documentation index, and a Lisp-to-BIL semantics compiler exposed as `mc` providers for RISC-V, ARM/Thumb/AArch64, PowerPC and x86. All 47 upstream `.lisp` files are embedded; semantics files typecheck cleanly.
- `types/Live` and SSA roots: upstream `Live` liveness (backward fixpoint over the tid graph with pseudo start/exit nodes, exit seeded with `keep` and `Out`/`Both` argument uses, upstream phi-edge convention) with `ins`/`outs`/`defs`/`uses`/`solution` queries; SSA is rooted at the pseudo start node so entry back-edges get phis and disconnected blocks are renamed.
- `dwarf/lazy function extraction`: units are read lazily; function-boundary extraction keeps the valid prefix and reports upstream-style diagnostics when a later DIE or unit header is malformed, and project loading keeps debug symbols from the valid prefix.
- `x86`: port of upstream `plugins/x86` as opt-in `mc` providers: the legacy byte-level decoder/BIL lifter (legacy/REX/VEX prefixes, 16/32/64-bit addressing incl. RIP-relative and FS/GS bases, integer ALU/flags, string ops with rep loops, control flow, SSE/AVX integer set) and the per-opcode LLVM-name lifters (btx, mov, mov_offset, cmpxchg, cdq family, endbr). A differential test against the Basic lifter documents upstream divergences from Intel semantics (rotates, 32-bit BTS/BTR/BTC zero-extension, CMPXCHG8B halves, XADD operand order), which are kept for fidelity; the Basic lifter stays the default. The legacy x87 lifter is not ported (upstream gates it behind a flag; x87 semantics come from Primus Lisp intrinsics).
- `project/Basic x86-64 REX fix`: the Basic decoder no longer falls back to 32-bit one-byte INC/DEC for REX prefixes in 64-bit mode.
- `knowledge/KB state and evaluator`: one central KB state (persistent per-class object tables with typed heterogeneous records, symbols/packages with public/private visibility and imports, context variables) with O(1) snapshots and transactional rollback; least-fixed-point `collect` following upstream's Sleep/Awoke/Ready promise scheduling, promise rejection into bottom (`require`, `require_some`, `reject`, `guard_`, `on`, `unless`, `with_empty`), monotonic `provide` with observers, `run`/`eval`, knowledge `Value`s with join/merge/refine, `Enum`, and persistent-state round trips. The KB monad maps to direct-style `(State) -> A raise` functions.
- `primus_lisp integration`: plugin primitive tables (taint, constant tracker, region, dictionary) are bound into Lisp; upstream taint/constant-tracker/primus-test/approximation `.lisp` files load and typecheck with core+posix; synchronous `loading`/`storing` signal methods run before memory accesses.
- `plugins/primus_lisp`, `plugins/primus_test`, `plugins/primus_approximation`, `plugins/riscv`: the Lisp plugin frontend (documentation/dump/typecheck/add/load/semantics/channel options), incident traces and the `incident-*` primitives/components, the `approximate` sin/cos primitive, and the RISC-V C ABI plus Lisp semantics provider; all semantics directories load together and select definitions by context, typechecking cleanly for riscv32/64, x86_64, i386, arm, thumb, aarch64, powerpc and powerpc64. `primus_symbolic_executor` is ported over the `z3` binding (see below).
- `z3`: a binding to the Z3 SMT solver (contexts, bitvector/boolean terms with all BIL operators, extraction/extension/rotation/`ite`/equality/`distinct`, simplification, incremental solvers with scopes and timeouts, models read back as `@types.Word`, hash-consed term identity). The library is `dlopen`ed at run time (`load_library`, then `BAP_Z3_LIBRARY`, then the loader path and the Homebrew/`/usr/local` locations), so nothing is needed to build it and every package keeps building without Z3; reference-counting contexts with a non-aborting error handler, all objects are MoonBit external objects that keep their context alive. On non-native targets, or when the library is missing, `Context::new` raises `Unavailable("SMT solver unavailable: ...")` and the native tests skip.
- `plugins/primus_symbolic_executor`: port of `primus_symbolic_executor_main.ml`: the `bap:symbolic-computer` (formulas for every value computed from generated variables/memory cells), `bap:symbolic-path-constraints`, `bap:symbolic-path-explorer` (master machine forking one worker per satisfiable task, LIFO worklist, cutoff per branch, visited-edge pruning via `primus_track_visited`, model values stored into the worker's variables/memories) and `bap:symbolic-lisp-primitives` (`symbolic-value`, `symbolic-memory`, `symbolic-memory-read`/`-write`, `symbolic-assume`, `symbolic-assert` with the `assert-failure` observation) components, the `executor-debug` observation, the `--primus-symbolic-executor-cutoff-level`/`-timeout` options, and the upstream `symbolic-stdio.lisp`/`symbolic-stdlib.lisp` (embedded in `primus_lisp` under `symbolic-executor/`, loadable as the `symbolic-stdio` feature). As upstream, at a block with several jumps a task is queued only for a conditional jump that was not taken (the jumps after a taken one are not queued), and the constraints of a task are those of the worker's own task plus the new branch condition (not the whole path).
- `primus/fini`: `fini` runs exactly once per machine and `system-stop` observer frames execute before `run` returns.
- `types/project BIL-to-IR lowering`: port of `bap_sema_lift`: `Blk::of_bil` lowers BIL into structured IR blocks (guarded jumps, if/else diamonds, while loops, calls, interrupts) with upstream block contraction/ordering; `Blk::lift_insn`/`lift_block`/`lift_insns` split blocks at instruction boundaries with `insn`/`address` attributes, call return labels, fallthroughs and barriers; `Program::relink_calls`/`insert_synthetic`; project reconstruction and `Project::lift_ir` (block/sub/program lifting from the symbol table) use it, with delay-slot-aware per-instruction segments.
- `knowledge/slot identity`: same-name properties declared with the same domain object share one slot (rules and facts), objects are listed once they have knowledge, and class-equality witnesses support object casts; objects are hashable/comparable keys.
- `primus_lisp/host IO`: native user semantics/library folders are enumerated via `native_io`, and redirected host files back `channel-open`/`flush`/`close`.
- `beagle` + `plugins/beagle`: Primus-based string/word recovery (prey observations/statements, per-machine string detectors, dictionary unscrambler, `beagle` pass and options).
- `xml`: streaming Xmlm-style XML reader (namespaces, entities, CDATA, comments, PIs, DOCTYPE, positions) with a small tree API.
- `plugins/patterns`: Ghidra byte-pattern files (bit/nibble masks, pattern pairs, target specs, digest-deduplicated file selection) with upstream matching quirks, `funcstart`/`possiblefuncstart` actions, per-image `patterns` rooter/symbolizer and `match-patterns` command.
- `plugins/bil`: BIL pass pipeline (`bnf1`, `bnf2`, constant folding/propagation, dead-virtual pruning) with normalization/optimization levels and `--bil-passes`, intrinsic generation, and a pass-applying lifter wrapper; the BIL `Theory.Core` instances and KB rules await the Core Theory algebra.
- `frontend` + `cmd/bap`: a working native `bap` executable (`moon build --target native`, `_build/native/debug/build/cmd/bap/bap.exe`) porting `bap_frontend.ml` over `bap_main` with every ported plugin registered in one table; commands `disassemble` (default; loaders, targets, passes, `-d<fmt>` dumps, `--project`/`--update`), `mc`, `specification`, `recipes`, `analyze`, `list`, `config`, plus Primus `--run`, strings, trace and byteweight plugins. A test-only `fixtures` package builds tiny ELF binaries.
- `core_theory/Theory.Core`: an executable Core Theory: `Value`/`Effect`/`Semantics` as extensible KB values with independently joining properties; the full operation algebra (Init, Bool, Bitv, Memory, Effect, Basic, Fbasic, Float, Trans; ~150 direct-style `(State) -> Value raise` operations) with Empty, Basic (derived from Minimal), Join and a reference BIL-producing instance; the theory manager (`declare_theory`, context/feature-based `instance` selection with subsumption and KB caching, `require`, `current`, `with_current`); the desugaring pass; and the generic `Theory.Parser` with a BIL grammar (`Core::reflect_bil`). BIL floating-point emulation is not yet ported.
- `mc/decoder registry` + `project/Basic`: `@mc.Decoder` registry (`Decoded`/`Invalid`/`Truncated`) consulted by the Basic disassembler before the built-in llvm (x86/ARM fixture) decoder; undecodable bytes are reported as invalid instructions instead of `.byte`; `Basic::run` is the upstream callback machine.
- `knowledge/strict properties`: every package declares each knowledge domain once, and redeclaring a property with a different domain aborts as upstream.
- `powerpc/decoder`: native PowerPC decoder producing LLVM `PPC` opcode names/operands for every opcode the lifter supports (32/64-bit, both endiannesses, `_rec` forms, `gBC*`/CTR/LR branches, SPR moves), registered in the `bap` frontend; the upstream `lib_test/powerpc` byte encodings now go through decode→lift→evaluate.
- `plugins/bil/theories`: `bap:bil` (Core BIL theory with let simplification) and `bap:bil-fp-emu` (upstream `Bil_float` emulation for binary16/32/64/80/128), `bap:bir`/`bap:jump-dests` theories, and the `bil-lifter`/`machine-code`/`bil-semantics`/`reify-ir` KB rules, with desugaring of lifted code and KB-resolved external names.
- `image/typed memory` + `elf`: upstream typed universal values (`Tag`/`Value`/`Dict`, typed term attributes); `Image::memory` annotated with typed segment/symbol/section/code-region values; a lossless raw ELF reader package (`elf`) with unknown-enum preservation for non-loadable files, used by the image loader, whose specs now carry upstream `llvm:*` ELF facts.
- `project/relocations` (upstream `bil-fixup-relocator` and the `relocatable` plugin's `plt-symbolizer`): the ELF loader emits the relocations of relocatable objects (only those of executable sections, section-relative, against function/object/untyped symbols; RISC-V call relocations cover the `auipc`/`jalr` pair) and the `relocation`/`external-reference` facts; the recursive driver attaches the unit relocations to the decoded instructions and `ProjectDisassemblyInstruction::lift` redirects their jumps to relocation targets or turns them into calls of the external symbols (`name:external` in stubs), so calls in `.o` files resolve to `sq`/`printf` on x86-64, AArch64, ARM, MIPS, PowerPC, RISC-V, Mach-O and COFF objects without splitting the callers; stubs are named after their externals; external tail calls are barriers; instructions without semantics that are returns/barriers (arm64e `retab`) end their blocks; `-dasm`/`-dbil` lift with the project lifters. Temporary labels (ELF `.L*`, Mach-O `l*`/`L*`) and COFF section symbols are not symbols. Gaps: sections of objects all live at address 0 (as upstream), so objects with several code sections (`-ffunction-sections`) still alias; IR jump targets inside subs print as `@0x...` labels (pre-existing).

## Decoder validation against LLVM 22

The native decoders are checked differentially against libLLVM 22 (the
`llvm-mc -disassemble -show-inst` disassembler, plus the `MCInstrDesc`
flags upstream's `llvm_disasm.cpp` turns into instruction kinds): opcode
name, operand list, printed assembly and kinds, over random words,
encoding-class sweeps and clang output (synthetic C files, musl libc
sources, dlmalloc/miniz/..., and host binaries). The comparison tools
are throwaway; each ISA commits a table of LLVM-verified samples
(`<isa>/decode_llvm_test.mbt`, `mips` and `riscv` included). As for
upstream BAP, LLVM's `SoftFail` encodings are valid instructions.

- A32 (`arm/decode_llvm_test.mbt`, 809 samples, 210 opcodes) and T32
  (`thumb/decode_llvm_test.mbt`, 630 samples, 265 opcodes, and IT-block
  streams): no mismatch on any instruction both decode (100k random words,
  49k-word class sweeps, every 16-bit Thumb encoding, 98k Thumb-2
  encodings, ~370k instructions of compiled ARM/Thumb code). Kinds are the
  opcode's `MCInstrDesc` (`@arm.llvm_kinds`, generated table). LLVM
  conventions reproduced: unsigned 32-bit patterns for negative 12-bit
  offsets and bit field masks (`#-0` is `2147483648`), AM3 index-mode bits,
  unpredicated `BL`, `SMLAL<x><y>` tied sources, `ADDri`/`SUBri` rather
  than `ADR`, Thumb shifts by 32 as 0, unscaled `t2LDREX`/`t2STREX`
  offsets, `t2ADDspImm`, `MOVr_TC`, nested IT blocks resuming the outer
  block. A32 VFP, NEON, coprocessor, media, saturating and parallel
  arithmetic instructions are decoded by tables learned per ARM ARM
  encoding class from libLLVM (`arm/decode_ext.mbt`,
  `arm/decode_llvm_ext_test.mbt`: 1536 samples, 1256 opcodes; `VLDM`/`VSTM`
  and `sysLDM`/`sysSTM` by hand): llvm-only words go from 2115 to 0 on
  clang -O2/-O3 FP/NEON code (armv7 hard-float), 1617 to 0 and 56 to 0 on
  the two compiled corpora, 124,385 to 232 on 500k random words (`MSR`
  immediates with non-canonical rotations, a few `PLI`/`PLD`/`CPS` forms).
  The same tables decode the Thumb-2 VFP, NEON and coprocessor encodings
  (`@arm.decode_t32_ext`, with the IT condition as predicate), and further
  Thumb-2 tables the bit field, saturation, multiply, parallel arithmetic,
  `REV`/`CLZ`, unprivileged load/store and `UDF` instructions
  (`thumb/decode_llvm_ext_test.mbt`: 1074 samples, 856 opcodes, and an
  IT-block stream): llvm-only words go from 2107 to 0 on clang Thumb-2
  FP/NEON code, 21,980 to 0 on the Thumb-2 corpus and 121,201 to 9 on
  600k random 32-bit Thumb words.
  The Basic `llvm` backend's built-in ARM decoder (used only by
  `Basic.create "armv7"` with the `llvm` backend) is not validated.
- A64 (`aarch64/decode_llvm_test.mbt`, 994 samples, 549 opcodes, and
  `aarch64/decode_llvm_simd_test.mbt`, 2342 samples, 2009 opcodes), with
  upstream's features `+v8.1a,+v8.2a,+v8.3a`: exact on the whole
  instruction set LLVM decodes with them (LSE, pointer authentication,
  system registers from an LLVM-generated table, `SYS` aliases, scalar
  floating point and conversions, all AdvSIMD classes, SIMD&FP loads and
  stores including the structure `LD1`..`LD4R`/`ST1`..`ST4`). The
  SIMD/FP part is table driven (`aarch64/simd.mbt`): each ARM ARM encoding
  class maps a key to the LLVM name and operand/assembly templates learned
  from, and swept against, libLLVM (200k-word class sweeps per class,
  500k random words, and the 11.4M words of the `__text` of every
  `/usr/bin` arm64e binary of macOS 26: 256,519 llvm-only words in 509
  opcodes before, none after). SVE/SME and the extensions upstream does
  not enable (FP16 arithmetic, dot product, crypto) are invalid, as in
  LLVM. FlagM (`CFINV`/`RMIF`/`SETF*`) is decoded although LLVM needs
  `+flagm`. SIMD/FP instructions have no Lisp semantics: they lift as
  `Unsupported` (empty BIL in a project), which keeps the CFG intact.
- PowerPC 32/64, both byte orders (`powerpc/decode_llvm_test.mbt`, 576
  samples, 261 opcodes): exact for every opcode the decoder knows (the
  lifter's); LLVM 22 conventions: raw zero-extended D-form displacements,
  `LI`/`LIS`, printer mnemonics, no `bctar`. The instructions the lifter
  does not know are decoded by tables (`powerpc/decode_ext.mbt`,
  `powerpc/decode_llvm_ext_test.mbt`: 1639 samples, 1171 opcodes) learned
  per instruction format from, and swept against, libLLVM: classic FP
  (loads/stores, arithmetic, compares, `fmr`, `mffs`/`mtfsf`), AltiVec,
  VSX, `isel`, traps, `sync`/`lwsync`/`isync`/`eieio`, `mftb`,
  `mfocrf`/`mtocrf`, cache/TLB/system instructions, decimal floating point
  and most of Power10. Compiled PowerPC code (a 142k-word corpus: 4952
  llvm-only words before, 0 after; clang -O2 FP/AltiVec/VSX code for
  ppc32, ppc64 (pwr9) and ppc64le (pwr10): 0) and 1M random words (253,934
  llvm-only before, 367 after: Power10 AES/MMA/`xvtstdc*`, embedded TLB
  and DCR instructions) agree exactly. They lift as `Unsupported`.
- x86/x86-64 (the Basic `llvm` backend, `project/disassembly_basic_x86*.mbt`;
  `project/disassembly_basic_llvm_test.mbt`, 1947 samples): a
  reimplementation of LLVM's X86 disassembler (LLVM's prefix handling,
  VEX/XOP/3DNow!, 16/32/64-bit and RIP-relative addressing) with opcode,
  operand, kind and AT&T-template tables generated from libLLVM 22; size,
  name, MCInst operands (tied sources, condition-code operands, LLVM
  register numbers), AT&T assembly and kinds match `llvm-mc` on ~400k
  instructions of compiled musl/clang code, ~530k of macOS binaries, random
  bytes, opcode sweeps and the `x86/semantics` corpora. `code` is the LLVM
  opcode number and the encoding `llvm-x86`/`llvm-x86_64`. EVEX (AVX-512)
  and APX (REX2) are invalid. The Basic BIL lifter keeps its historical
  names through an adapter (`disassembly_basic_x86_legacy.mbt`); new cases
  (`TEST mi`, `LODS`, `LOOP*`, `ENTER`, `POP m`, `CMPXCHG16B`) are keyed on
  LLVM names (`disassembly_basic_bil_x86_ext.mbt`), and memory operands
  cover RIP-relative, absolute, `EIZ`/`RIZ`, `FS`/`GS` and narrow address
  forms. The recursive disassembler stops fall-through only at barriers
  (LLVM marks conditional branches as terminators).

## Deliberate upstream semantic fixes

Where upstream semantics are wrong for the operands of the current LLVM
decoders (which the port's native decoders reproduce) or for the ISA, the
port follows the ISA. Each fix has a regression test that decodes real
bytes (checked with `llvm-mc`), lifts them and executes the BIL
(`mips/isa_semantics_test.mbt`, `plugins/riscv/riscv_isa_test.mbt`; for
x86, the Unicorn differential tables of `x86/semantics`).
The `unicorn_diff` package differentially tests the PowerPC, MIPS, RISC-V,
SystemZ, ARM (A32 and Thumb, IT blocks included) and AArch64 lifters against Unicorn 2.1.4: about 4900 single
instructions assembled by `llvm-mc` 22 with random initial states
(registers, `CR`/`XER`, `HI`/`LO`, memory) and the states Unicorn
computed are decoded with the native decoders, lifted with the
registered providers (the native lifters and the Primus Lisp semantics)
and executed with `@types.exec_stmts`, comparing the whole register file,
the next PC and the touched memory; architecturally undefined outputs are
skipped. Unicorn's PowerPC core is a 32-bit CPU in a 64-bit build (no
64-bit mode, no ISA 2.06+ opcodes, `XER` not readable directly), so the
tables use its full-width registers in 32-bit mode for the common
opcodes, recompute the 64-bit `CR0`/`CA` of record/carrying forms, and
take the 64-bit-only and ISA 2.06+ opcodes from a Python model of Power
ISA 3.0B; little-endian PowerPC memory accesses run on the big-endian
core with the accessed bytes reversed. Unicorn cannot run the MIPS
Release 6 PC-relative opcodes (`ADDIUPC`, `AUIPC`, `ALUIPC`, `LWPC`,
`LWUPC`, `LDPC`), whose fixes are covered by `mips/isa_semantics_test.mbt`
only.

- PowerPC (`powerpc/`):
  - D/DS-form loads and stores sign-extend the low 16 bits of the displacement (`Operands::disp`), correct for LLVM 22's raw zero-extended D-form operand and the older signed one; `ldu` sign-extends its DS displacement (upstream reads it unsigned).
  - `LI`/`LIS` (LLVM 22 decodes `addi`/`addis` with `ra = 0` as them) sign-extend in 64-bit mode, like `addi`/`addis` (upstream zero-extends).
  - Record forms copy `XER[SO]` into `CR0[SO]` (upstream leaves it unchanged).
  - `addc`/`adde`/`addme`/`addze`/`addic[.]`/`subfc`/`subfe`/`subfme`/`subfze`/`subfic` set `CA`/`CA32` to the carries out of the (word) sum; upstream compares the result with an operand, which inverts the carries of subtractions, misses carries when the other addend and the carry-in wrap, and sets `subfme`/`subfze` carries unconditionally.
  - `cmpw`/`cmplw` compare the low words of both operands (upstream compares the low word of `ra` with the whole `rb`).
  - `mullw` produces the doubleword product of the signed low words (upstream multiplies the zero-extended words: the upper half is wrong on 64-bit targets).
  - Wrapping masks (`mb > me`) of `rlwinm`/`rlwnm`/`rlwimi` include bits `mb` and `me`, and those of `rldic`/`rldimi` are the union of the two halves (upstream leaves out the boundary bits, resp. clears the result).
  - `sld`/`srd` by 64 to 127 produce zero (upstream shifts by the low six bits).
  - `powerpc.lisp` defines `NOP` in the `powerpc` package, so that `llvm-powerpc32` instructions resolve to it (upstream defines it in the default package, where no instruction name resolves).

- MIPS (`mips/`):
  - `CLO`/`CLZ` read `rs` and write `rd` (LLVM's `[rd, rs]`) and count from the most significant bit.
  - `LSA`/`DLSA` shift by LLVM's operand (already the encoded amount plus one).
  - `LWPC`/`LWUPC`/`LDPC` use LLVM's already scaled offsets; `LDPC` aligns the PC to 8.
  - `J`/`JAL`/`JALX` jump into the 256 MB region of the delay slot address (LLVM's operand is the in-region offset).
  - Branches on signed comparisons compare signed (upstream's comparisons are unsigned); `BGTZ`/`BGTZL` test `> 0` (upstream: `>= 0`); `SLTI` compares signed with a sign-extended immediate.
  - `SEB`/`SEH` sign-extend the least significant byte/halfword of `rt` into `rd` (upstream: the most significant one, operands swapped).
  - Multiplies compute at twice the operand width, so `MUH`/`MUHU`/`MULT`'s `HI`/`DMUH`/`DMUHU` are the true high halves; `MADD[U]`/`MSUB[U]`/`DMULT[U]` and `MFHI`/`MFLO`/`MTHI`/`MTLO` are modeled.
  - 32-bit operations (arithmetic, shifts, rotations, multiplies, divides, `LUI`, `WSBH`, `BITSWAP`, `EXT`/`INS`) compute on the low words and sign-extend their results into MIPS64 registers; variable shifts use the low 5 (words) or 6 (doublewords) bits of `rs`; `ROTR` rotates the low word.
  - Branch-and-link forms link unconditionally; the compact ones (`*ALC`, `BALC`, `JIALC`) link `cia + 4` and have no delay slot; `JIC`/`JIALC` sign-extend LLVM's unsigned 16-bit offset; `JALR` reads its target before linking.
  - Store-conditionals (LLVM's `[rt, rt, base, offset]`) set the success flag.
  - The hardwired zero register reads as zero and writes to it are discarded (upstream reads and writes a `ZERO` variable).
  - Modeled although missing or unregistered upstream: `BLTZ`, `BLTZL`, `BGEZL`, `BNEL`, `BLEZL`, `BLTZAL`, `BGEZALL`, `BLTZALL`, `BC`, `BALC`, `JALX`, the hazard-barrier jumps, R6 `DIV`/`DIVU`, `DSDIV`/`DUDIV`, `MOVZ`/`MOVN`, `EXT`/`INS`/`DEXT`/`DINS`, `DSHD`, `DROTR*`, `AUI`, `AUIPC`, `DADD`/`DADDi`, `DCLO`/`DCLZ`, and the no-op hints.
  - Remaining gap: the "likely" branches do not nullify their delay slot when not taken (this needs support from the disassembler's delay-slot handling).
- RISC-V (`primus_lisp/lisp/semantics/riscv/riscv.lisp`, deviations marked `port:`):
  - `JALR` jumps to `(rs1 + offset) & ~1`, read before the link register is written (upstream: `pc + rs1 + offset`); `C_JR`/`C_JALR` likewise clear bit 0 of the target, and `C_JALR` reads it first.
  - `AUIPC` adds `imm << 12` (upstream: `imm`); `LUI`/`C_LUI`/`AUIPC` sign-extend the 32-bit value on RV64.
  - `LW`/`LH`/`LHU`/`LWU` load and `SW`/`SH` store 32/16 bits (upstream derives the widths from XLEN, which is wrong on RV32).
  - `SLTI` compares `rs1` signed (upstream compares the destination, unsigned); `BLT`/`BGE` compare signed (upstream: unsigned).
  - Added: `ADD`, `AND`, `OR`, `XOR`, `SLT`, `SLTU`, `SLTIU`, `SLL`/`SRL`/`SRA` (amounts masked to XLEN), `SUBW`, the `*W` shifts, `BLTU`/`BGEU`, the M extension (`MUL`, `MULH[S][U]`, `DIV[U]`, `REM[U]`, `MULW`, `DIV[U]W`, `REM[U]W`, with the ISA's division-by-zero results), `C_AND`/`C_OR`/`C_XOR`/`C_ANDI`/`C_SUBW`/`C_SW`/`C_SWSP`/`C_LWSP`/`C_JAL`, and the fences.
- ARM (`arm/`, marked `port:`; the `unicorn_diff` A32 tables, about 1400 cases over the 189 lifted opcodes with random `NZCV`/`Q`, conditions, all shift forms and memory accessed anywhere in the address space, and a 9500-case stress run agree with Unicorn's Cortex-A15):
  - Shifts follow `Shift_C`/`DecodeImmShift`: immediate `LSR`/`ASR` (and `PKHTB`) amounts of 0 encode 32 (upstream shifts by 0), register-specified amounts are the low byte of the register, amounts of 32 or more shift all bits out (`ASR`: sign) with the matching carry, rotations use the amount modulo 32, and a zero amount leaves the carry unchanged (upstream shifts by the whole register and derives the carry from bit `amount - 1`, also for 0). The shift register is read before the destination is written.
  - The carry of logical instructions with a modified immediate is unchanged for unrotated constants and the constant's bit 31 otherwise, for A32 and T32 (upstream: an unknown value or 0, and garbage for T32).
  - Loads read a register offset before writing the destination (`ldr r0, [r1], r0` writes back `r1 + old r0`), and dual loads read both words before writing the first register (which may be the base).
  - `Q` is sticky: `SMLABB`/`SMLAD`/`SMUAD`/`SMLAWB` set it on overflow and leave it unchanged otherwise (upstream clears it).
  - `LDREXD`/`STREXD` register-pair operands (LLVM's `GPRPair`, `R0_R1`) are split into their registers (upstream fails).
  - Remaining: a single `STREX` without a preceding `LDREX` succeeds (no exclusive monitor, as upstream); the interworking bit of a jump target (BX/`LDR pc`/`POP {pc}`/`ALU pc` to an odd address) is kept in the target rather than switching the encoding; `MRS`/`MSR`/`CPS`/`SVC` are not compared. Decoded by LLVM but not lifted (as upstream): `ADR`, `PKHBT`, `REVSH`, `SDIV`/`UDIV`, `SXTB16`/`UXTB16`, `SMUL[BT][BT]`/`SMLA[BT][BT]` except `BB`/`TB`/`LALBT`, `SMULW[BT]`/`SMLAWT`, `SMLSD`/`SMUSD`, `SMMUL`/`SMMLA`, `SMLALD`, the `T` immediate-offset forms and `MOVr_TC`; `UMAAL` is not decoded by the native A32 decoder.
- Thumb (`thumb/` for the 16-bit opcodes, `arm/` for the `t2*` ones, the `thumb.lisp`/`arm-bits.lisp` semantics for the others, marked `port:`; the `unicorn_diff` T32 tables, about 2000 cases over 218 opcodes including IT blocks of one to three instructions, and a 10000-case stress run agree with Unicorn):
  - `thumb/`: `movs rd, #imm8` clears N (upstream tests bit 7 of the immediate); `adcs` computes the carry out of `rn + rm + C`; `cmp` and the branches `b`/`bx`/`blx rm` in IT blocks are conditional (upstream ignores their predicate); `bl`/`blx` link the return address with bit 0 set and `blx rm` returns to `pc + 2`; `pop {..., pc}` also pops the return address off the stack (upstream leaves SP 4 bytes short); `ldr rt, [pc, #-0]`.
  - `arm/` for Thumb-2: the pre/post-indexed halfword, signed and dual accesses and `t2LDREX`/`t2STREX` (whose offset is unscaled) use LLVM's Thumb-2 operand layouts (upstream matches the A32 ones and fails), `#-0` offsets (`INT32_MIN`) are 0, the multiplies never set the flags (upstream reads the predicate register, `CPSR` in IT blocks, as their `S` operand), and the Thumb-2 opcodes without an A32 namesake are lifted as their A32 counterparts (`t2ANDrs` as `ANDrsi`, `t2LDRi8` as `LDRi12`, `t2LDRBs` as `LDRBrs`; upstream has no semantics for them).
  - Lisp: the 16-bit logical operations, `tMVN` and `tTST` are conditional in IT blocks (upstream writes the destination unconditionally); `tCMPhir` computes `rn + ~rm + 1` (upstream's `rn + -rm` gets the carry of `rm = 0` wrong); `tSBC` zero-extends the carry (Primus Lisp sign-extends narrower operands, which subtracted 1 instead of adding it); the register shifts (`tLSLrr`, `tLSRrr`) use the low byte of the register with ARM's carry, and the immediate/shifted-register operands (`i-shift`) decode `lsr`/`asr #32`; the `S` forms of `t2ADDrs`/`t2EORrs`/`t2RSBrs`/`t2LSLri`/`t2LSRri` set the flags; `tADDhirr`/`tMOVr` read `pc` as the address plus 4 and jump when writing it; `t2LDRDi8` reads both words before writing the first register. Added: `tASRrr`, `tROR`, `tCMNz`, `tREVSH`, `tHINT`, `t2ASRri`, `t2RORri`, `t2LSLrr`/`t2LSRrr`/`t2ASRrr`/`t2RORrr`, `t2CLZ`, `t2SDIV`/`t2UDIV`.
  - Remaining: `t2SMLALBT` is not decoded by the native T32 decoder (LLVM decodes it); not lifted (as upstream): the Thumb-2 unprivileged (`T`), halfword/signed 8-bit-offset (`t2LDRHi8`, ...), pre/post-indexed word/byte (`t2LDR_PRE`, `t2STRB_POST`, ...) and halfword register-offset accesses, `t2ORN*`, `t2PKHBT`, `t2RRX`, `t2SUBri12`/`t2SUBspImm`, `t2LDRBpci`, `t2ISB`, `tSTMIA`, `tLDMIA_UPD`.
- AArch64 (the `aarch64*.lisp` Primus Lisp semantics, the only AArch64 lifter, marked `port:`; the `unicorn_diff` A64 tables, about 1900 cases over 276 opcodes with random `NZCV`, all addressing modes, exclusive pairs and LSE atomics, and a 9500-case stress run agree with Unicorn's `max` CPU):
  - Registers: the semantics name registers by their operands and aliases (`W3`, `LR`, `FP`, `WSP` and the `R3` base registers of `setw`), which the port resolves onto `X0`..`X30`/`SP` when lifting (`@mc.resolve_aarch64_registers`: 32-bit reads are low words, 32-bit writes zero-extend), like upstream's `Core.desugar` with the aliasing of `arm_target.ml`; before, the BIL of different instructions named the same register differently and W forms read unbound variables.
  - `setw` writes the zero-extended low word (W results computed at 64 bits from sign-extended operands leaked their upper half); the flag-setting W forms (`SUBS`/`CMP`, `CCMP`/`CCMN` with immediates) compute the flags of the 32-bit operation (upstream: of the 64-bit sign extensions).
  - `STPXi` stores its two registers at `base + 8 * imm` (upstream stores the base register twice at `base + 16 * imm`); `LDPXi` loads both words before writing the first register (which may be the base); `BLR` reads its target before linking (`blr x30`); `ORN` shifts its operand as encoded (upstream shifts left by the whole shift operand); `BFM` with `s < r` (`BFI`) inserts at bit `size - r` (upstream is off by one) and handles full-width moves.
  - Added (about 170 opcodes): `ADDS` (all forms), extended-register `ADD`/`SUB`/`ADDS`/`SUBS`, `ADC`/`SBC`/`ADCS`/`SBCS`, `ADR`, `ANDS`, `BIC`/`BICS`/`EON`, `LSLV`/`LSRV`/`ASRV`/`RORV`, `CLZ`/`CLS`/`RBIT`/`REV`/`REV16`/`REV32`, `EXTR`, `SMADDL`/`UMADDL`/`SMSUBL`/`UMSUBL`/`SMULH`/`UMULH`, the loads and stores of every size with unsigned, pre/post-indexed, register (`roX`/`roW`) and unscaled offsets, `LDP`/`STP` (W/X, all modes) and `LDPSW`, literal loads, `LDXR`/`LDAXR`/`LDAR`/`STXR`/`STLXR`/`STLR` (exclusive stores always succeed, as in the ARM lifter) and the LSE atomic memory operations (`LDADD`/`LDCLR`/`LDEOR`/`LDSET`/`SWP`, all orderings and sizes).
  - Pointer authentication (ARMv8.3 PAuth, no upstream semantics): modeled with authentication disabled (`SCTLR_ELx.EnIA`/`EnIB`/`EnDA`/`EnDB` clear, as Unicorn runs it and as a process without keys sees it): the `PAC*`/`AUT*`/`XPAC*` instructions leave their registers unchanged (`pacibsp`, `paciza x8` lift to empty BIL), `RETAA`/`RETAB` are `RET`, `BRAA`/`BRAB`/`BRAAZ`/`BRABZ` are `BR`, `BLRAA`/`BLRAB`/`BLRAAZ`/`BLRABZ` are `BLR`, `LDRAA`/`LDRAB` are 64-bit loads with offsets scaled by 8 (indexed and pre-indexed); checked against Unicorn by the `a64_pauth` table. `BRK` calls the `software-breakpoint` intrinsic. `PACGA` has no semantics.
- Primus Lisp compiler (`primus_lisp`): `cast-low`/`cast-signed`/`cast-unsigned` to the width of a register operand returned the register symbol, which the primitive call then reified into a constant (the interned register name), so `(cast-low 32 w)` lifted to a number; the result is now the register value. `is_zero_register` memoizes the zero registers of a target (recomputing the target role table on every operand made AArch64 lifting about 30 times slower). As upstream's x86 plugin (which promises it unless `--x86-disable-floating-point-intrinsics`), the semantics context enables `x86-floating-points intrinsic-semantics` (`@primus_lisp.semantics_context`), so the SSE floating-point instructions of `x86-64-sse-intrinsics.lisp` are defined: `addsd %xmm1, %xmm0` (`ADDSDrr_Int`) lifts to a call of the `fadd_rne_ieee754_binary` intrinsic (without the context the definitions are filtered out and the instruction lifted to empty BIL); `set-sse` evaluates its value once (upstream substitutes it twice, calling the intrinsic twice).
- SystemZ (`systemz/`): besides upstream's `LR`, the other general-register moves without condition codes are modeled (`LGR`, `LGFR`, `LLGFR`).
- Symbolic executor (`plugins/primus_symbolic_executor`): BIL `MOD`/`SMOD` are translated to `bvurem`/`bvsrem` (upstream swaps them); shifts by an amount wider than the shifted value are computed in the wider width (upstream fails on them).
- Primus Lisp lifter (`primus_lisp`): hardwired zero registers (registers with the `zero` role: RISC-V `X0`/`ZERO`, AArch64 `XZR`/`WZR`) read as zero and writes to them are discarded (RISC-V `j`/`ret` write `X0`).
- Primus Lisp lifter (`primus_lisp`): hardwired zero registers (registers with the `zero` role: RISC-V `X0`/`ZERO`, AArch64 `XZR`/`WZR`) read as zero and writes to them are discarded (RISC-V `j`/`ret` write `X0`); a missing register operand (LLVM's `NoRegister`, an empty name) reads as zero.
- x86 (`x86/semantics`: ~5000 single-instruction cases assembled with `llvm-mc` and executed in Unicorn 2.1.4, the flags the Intel SDM leaves undefined masked; the Basic lifter, the `x86`/`x86-legacy` providers and the x86 Lisp semantics agree on every case they lift). Where Unicorn (QEMU 5) contradicts the SDM the tables follow the SDM: CMPXCHG does not write the accumulator back when the comparison succeeds (fixed in QEMU 8.1). Fixes:
  - Basic lifter (`project/disassembly_basic_bil.mbt`): shift/rotate/SHLD/SHRD counts are masked to 5 bits (6 for 64-bit operands), not to the operand width; ROL/ROR set CF whenever the masked count is not zero; SAR's CF is the sign for counts beyond the width; the one-operand IMUL sets CF/OF when the product is not the sign extension of its low half; IDIV raises #DE on signed quotient overflow; BTx leave ZF unchanged and the memory forms floor negative bit offsets; CMPXCHG/CMPXCHG8B only write the accumulator when the comparison fails; LAHF stores the constant reserved bits.
  - `x86` providers (`x86/`, marked `port:`, listed in `x86/README.mbt.md`): the same shift/rotate, IMUL, IDIV, BTx and LAHF/PUSHF fixes; BTx zero-extend 32-bit registers in 64-bit mode (per-opcode lifter); the legacy lifter decodes BTS/BTR/BTC (upstream lifts `0f ba /5 /6 /7` as BT) and CMPXCHG16B; CMPXCHG8B loads EDX:EAX in order; XADD stores the sum in r/m (upstream swaps the operands); PAVGB/PAVGW keep the carry; packed shifts by a register/memory count use the low quadword of the source; PSHUFB uses 4 index bits; MOVQ `66 0f d6` zero-extends a register destination.
  - Lisp semantics (`primus_lisp/lisp/semantics/x86`, marked `port:`): memory operands include the scaled index; POP64rmm stores to the full effective address; SHUFPS takes its low words from the destination; ANDNPS/ANDNPD compute `(not src1) & src2`.
  - Sub-registers: the Basic lifter and the x86 Lisp provider resolve their sub-register variables (`EAX`, `AX`, `AL`, `AH`, `R8D`, `XMM0`, ...) onto the full registers like upstream's x86 lifters (`RR.get`/`RR.set` in `x86_tools_reg.ml`): reads are extractions, 32-bit writes in 64-bit mode zero-extend (`RAX := pad:64[...]`), the other writes merge (`@mc.resolve_x86_subregisters`). The Basic decoder tags x86 instructions with the `llvm-x86`/`llvm-x86_64` encodings, which name the mode. `Core::desugar` is unchanged: upstream's (`bap_core_theory_pass.ml` `set`/`assign_sub`) also merges every sub-register write, 32-bit ones included, with the `lo_bits_of main are M32.main` aliases of `x86_target.ml`, and relies on the lifters writing full registers. The Unicorn tables compare the full registers directly.
  - Remaining — not lifted: the Basic lifter's SSE integer instructions (its decoder only recognizes fixture encodings, and none is lifted), RCL/RCR by the legacy lifter; not decoded by the Basic decoder: `TEST m, imm`, `82 /r` (32-bit), `D3 /6`, `LODS`, `LOOP*`, `ENTER`, `POP m`, `CMPXCHG16B`, RIP-relative/absolute/32-bit-address `LEA` and some REX-prefixed `MOV` forms.

- `macho`, `coff`, `image/llvm loader`: Mach-O (thin and universal, segments/sections/symbols/LC_MAIN/LC_UNIXTHREAD/dylibs/LC_FUNCTION_STARTS/relocations/indirect symbols) and PE/COFF (PE32/PE32+/objects, sections, symbols, relocations, imports/exports) readers with loaders emitting upstream `llvm:*` facts and a port of `Bap_llvm_loader.translate`; a content-detecting `llvm` loader picks ELF/Mach-O/COFF, so `bap` opens host macOS binaries (universal slices chosen by `--target` or host architecture).
- `mips`/`riscv` native decoders: LLVM-MC-compatible MIPS32/64 R2/R6 and RV32/RV64 IMAFDC(+Zicsr/Zifencei) decoders verified against `llvm-mc` (all 16-bit RISC-V encodings and large random samples), registered in the `bap` frontend; ARM A32/Thumb-2 (with IT blocks) and AArch64 native decoders likewise.
- `deliberate semantic fixes (MIPS/RISC-V)`: MIPS lifter and `riscv.lisp` semantics corrected to the ISA for LLVM operand conventions (signed branches/comparisons, CLO/CLZ, true multiply high halves, MIPS64 word-op sign extension, zero-register handling, JALR/AUIPC, RV32 load/store widths, M extension); see "Deliberate upstream semantic fixes".
- `driver`: upstream-faithful recursive disassembly driver (incremental scan/merge/debt, data classification, externals, `explore`), KB-backed `Calls.update`, rooter/symbolizer/brancher fact providers, x86 call/ret push/pop semantics, fallthrough decided from lifted semantics (`Insn.derive_props`), synthetic subroutines and `reify_externals`; the `bap` CLI uses it by default.
- `unicorn_diff`: test-only differential semantics suite: ~4,900 generated cases (Unicorn 2 single-step results, with a Python Power ISA 3.0B model for 64-bit-only/ISA 2.06+ PowerPC opcodes) decoded by the native decoders, lifted through the real providers and executed with `@types.exec_stmts`; PowerPC, MIPS, RISC-V and SystemZ agree 100% after fixing PowerPC carries/CR0[SO]/compares/multiplies/rotate masks, MIPS DCLO/DCLZ, RISC-V C.JR/C.JALR and SystemZ LGR/LGFR/LLGFR. ARM (A32 ~1400, Thumb/IT blocks ~2000) and AArch64 (~2100, Lisp semantics) cases were added (the harness runs instruction sequences for IT blocks and exclusive pairs); they agree 100% (and on ~29,000-case stress runs) after the ARM/Thumb/AArch64 fixes listed under "Deliberate upstream semantic fixes" (before: 14% of the A32, 18% of the Thumb and 54% of the AArch64 cases of the opcodes upstream defines differed).
- `x86/semantics`: test-only Unicorn differential suite (~5,000 llvm-mc-assembled cases across ALU, mul/div, shifts, bit ops, moves, control flow, string ops and SSE, SDM-undefined flags masked); the Basic lifter, the upstream `x86` providers, `x86-legacy` and the x86 Lisp semantics agree 100% after fixing shift/rotate count masking and flags, IMUL/IDIV flags and #DE, BTx semantics, CMPXCHG/CMPXCHG8B/CMPXCHG16B/XADD, LAHF/PUSHF reserved bits, SSE averages/shifts/PSHUFB/MOVQ, and Lisp memory-operand indexing.
- `demangle/itanium` + `plugins/cxxfilt`: a native port of LLVM's `ItaniumDemangle.h` (the whole Itanium C++ ABI grammar incl. templates, substitutions, lambdas, abi-tags, modules, requires-clauses) matching `llvm-cxxfilt` 22 on 899,040 real names in `-n`/`-p`/`-t` modes, registered as the `bap:c++filt` (parameters dropped, as upstream's `c++filt -p`) and `bap:itanium` demanglers, replacing upstream's external `c++filt` process.
- `x86 full-register writes`: the Basic lifter and the x86 Lisp provider write full registers in 64-bit mode (32-bit writes zero-extend, 8/16-bit writes merge, sub-register reads are extracts) via `@mc.resolve_x86_subregisters`, as upstream's x86 lifters do.
- `z3` + `plugins/primus_symbolic_executor`: a runtime-loaded (`dlopen`) binding to the Z3 SMT solver (bitvector/boolean terms, solvers with push/pop/timeouts, models → `@types.Word`; unavailable-solver errors on hosts or backends without Z3) and the Primus symbolic executor (symbolic computer, path constraints, SMT-checked path exploration with cutoff and visited-edge pruning, symbolic Lisp primitives and the upstream `symbolic-stdio`/`symbolic-stdlib` Lisp files).

## Performance

Release `bap` on an Apple-silicon Mac (2026-09-27), before and after the
performance pass (outputs byte-identical):

| command | before | after |
| --- | ---: | ---: |
| `bap --help` | 4.2 s | 0.01 s |
| `bap /usr/bin/true -dasm` | 4.4 s | 0.18 s |
| `bap mc --show-bil -- "48 83 ec 08"` | 4.3 s | 0.08 s |
| `bap /usr/bin/true --run --run-entry-points=all` | 4.5 s | 0.19 s |
| `bap /bin/ls -dasm` | 12.0 s | 0.70 s |
| `bap /bin/ls -dbil` | 12.6 s | 0.72 s |
| `bap /bin/ls --target=x86_64 -dbir` | 10.1 s | 0.55 s |
| `bap /bin/bash -dasm` (153k lines) | > 537 s | 21 s |
| `moon test --target native` (run only) | 113 s | 18 s |
| `moon test` (wasm-gc, run only) | 116 s | 26 s |

The fixes: built-in targets (and the table `find_target` searches) are
built once instead of per lookup; target role tables, register roles and
register-name lookups are memoized per target; the disassembly state,
CFG, subroutine partition and symbol table are built with hash/sorted
indices instead of quadratic copy-and-scan updates; `graphlib` traversals
index the edges once, the fixpoint worklist is a heap, and `GraphBuilder`
builds graphs incrementally; memory views share their bytes; the Lisp
semantics of an instruction are compiled once per lifter. The remaining
time is spread over the knowledge base (persistent maps per property
update), the Lisp semantics compiler and library loading (about 120 ms
on the first lifted instruction), and the symbol table, which is
recomputed by the reconstructor, the info pass and the printer.

## Fidelity Gaps (audit, 2026-09-26; several since addressed: knowledge KB evaluator, Core Theory algebra, BIL-to-IR lowering, liveness/SSA, DWARF prefix recovery, typed image memory and raw ELF reader)

- `knowledge` (~40%): no least-fixed-point `collect`/promise evaluation, promise rejection or `with_empty`; facts live in per-slot tables instead of one KB state; no KB `run`, context variables, heterogeneous values, symbol imports or whole-state persistence.
- `core_theory` (~70%): the Core algebra, Empty/Basic/BIL instances, joins, the instance manager, desugaring and the parser are ported; missing are the BIL floating-point emulation (`Bil_semantics.Core_with_fp_emulation`/`Bil_float`), statically typed sorts (sorts are checked at run time), the KB-backed `Label` (labels are values with a `Program` object view) and bin_io persistence of values. Deviations (documented at the definitions): `Core::basic` stores `storew` chunks in the order `loadw` reads them, `Core::desugar` extracts super-register/bit-set parts with inclusive bounds, and the BIL `append` widens/narrows as specified, where upstream is inconsistent.
- `project` disassembly (~70%): the incremental driver (`ProjectDisassemblyDriverState`: scan/merge/debt/data/externals/explore), KB-backed `Calls.update`, rooter/symbolizer/brancher KB providers, the callback-driven `Disasm_expert.Basic` with encoding registration and invalid instructions, and the `@mc` decoder registry are ported; the driver state is not persisted with the project, the knowledge base is per project (not global), the Basic `run` callbacks nest calls (no constant-stack CPS), the legacy port-specific drivers (image-roots, raw-bytes, basic, ...) and the reachability-grouping reconstructor remain for projects not disassembled by the `recursive` driver, and relocation fixups of lifted semantics (upstream `bil-fixup-relocator`) are missing.
- `types` IR/BIL (~65%): BIL-to-IR reconstruction keeps only top-level assignments and selected jumps (no multi-block structured lowering); liveness lacks exit seeding and `keep`.
- `image`/ELF (~80%/~80%): `Image.memory` carries typed segment/symbol/symbol-info/section/code-region values and the raw `elf` reader is lossless, but the project memory is still segment-name strings (`Image::segment_names`), KB loaders run in a per-registration knowledge state rather than the toplevel one, ELF symbol/relocation/dynamic parsing in the loader is still private to `image`, and the ELF spec lacks the upstream `llvm:symbol-entry`/relocation facts. The Mach-O and PE/COFF loaders read no DWARF/PDB debug information, no dyld chained fixups/binding opcodes or PE base relocations (upstream reads none of them either, except PDB), and the unit-bias/user-base options of the upstream `llvm` loader are not ported.
- `dwarf` (~85%): eager function extraction drops the valid prefix when a later unit is malformed.

## Next Packages

- Expand `core_theory` with the full BAP knowledge registry, deeper source/compiler/program-unit/label fact integration, remaining alias provenance, and deeper architecture-specific target metadata.
- Expand `types` with fuller BIL normalization and broader memory-aware optimization passes, richer IR visitors and control-flow semantics, additional SSA/data-flow transforms over the term layer, richer indirect call resolution integrations, and broader parity audits beyond the current translated `.repos/bap/lib_test/bap_types` coverage.
- Expand `traces` with native OCaml bin_io compatibility for BAP-generated `.binprot` files, richer extensible tag/dictionary compatibility, and broader trace event metadata.
- Expand `dwarf` with broader DWARF form coverage beyond indexed strings/range lists, richer nested-DIE attributes and references, richer function-boundary fixtures, and deeper loader integrations beyond project symbol enrichment.
- Expand `image` with additional file-format backends beyond ELF, broader architecture-specific relocation semantics, dynamic-link resolution/orchestration beyond preserved metadata, and deeper loader metadata.
- Expand `project` with concrete disassembly driver implementations and higher-level project orchestration.
- Port Primus Lisp (`primus_lisp`) with Lisp-defined instruction semantics as `mc` providers for RISC-V, AArch64/Thumb, PowerPC and x86 semantics files, then the Lisp-dependent Primus plugins (`primus_test`, `primus_taint` Lisp parts, approximation).
- Port the Lisp-free Primus plugins (schedulers, promiscuous mode, limits, visited tracking, regions, dictionaries, random, loader, printing, systems) and taint analysis (`bap_taint`, taint propagation plugins).
- Port the upstream `plugins/x86` lifter onto the `mc` provider interface (the port currently relies on its own Basic x86 decoder/lifter) and the remaining analysis/output plugins.

## Not Portable

- `bap_llvm`, `bap_ida`, `bap_ghidra`, `radare2`, `objdump`: bindings to native libraries or external tools; decoding is provided by the port's Basic decoder and fixture decoders instead.
- `bap_plugins`, `bap_build`, `bap_bundle`: OCaml dynlink/build tooling; `bap_main` uses a static plugin registry.
- `monads`: relies on OCaml higher-kinded functors; ported code uses direct-style or explicit monad values per use site (e.g. `ogre`, `primus` frame stack).

## Porting Defaults

- Use `Bytes`/`BytesView` for binary payloads and file-format input.
- Use checked `suberror` plus `raise` instead of OCaml exceptions and `Or_error.t`.
- Keep pure packages target-agnostic; isolate native stubs behind native-only packages.
- Prefer behavior-level compatibility over OCaml module-shape compatibility.
