The Core Semantic Model (archsem-core)

archsem-core is the standalone foundation of Architectura. It has zero dependencies on any target IR (archsem-ir, LLVM, etc.) and zero dependencies on any instruction decoder (iced-x86, fARM64, etc.). Every architecture definition and consumer communicates exclusively through its neutral vocabulary.

IrEmitter: Required Core vs. Provided Extensions

Every semantic definition—whether a compiled .asem SemProgram or a hand-written Rust provider—is generic over IrEmitter. The trait splits into a required core and provided extension methods whose defaults expand faithfully onto the core:

┌─────────────────────────────────────────────────────────────────────────┐
│ IrEmitter                                                               │
├─────────────────────────────────────────────────────────────────────────┤
│ Required Core                                                           │
│  • type Value                                                           │
│  • begin_instruction()                                                  │
│  • temp(bits), imm(val, bits), reg(RegisterDesc), choice(ChoiceRequest) │
│  • binop(BinOp, a, b, bits), unop(UnOp, a, bits), compare(CmpOp, a, b)  │
│  • zext(v, to_bits), sext(v, to_bits), trunc(v, to_bits)                │
│  • load(addr, req), store(addr, val, req), write_reg(reg, val)          │
│  • select(cond, if_true, if_false), fault(FaultKind)                    │
│  • opaque_intrinsic(OpaqueIntrinsic, args) / intrinsic(name, args, ...) │
├─────────────────────────────────────────────────────────────────────────┤
│ Provided Extensions (default-lowered onto core, override for precision) │
│  • imm_wide(&[u64], bits) — 1..=512-bit literals                        │
│  • load_cond / store_cond / load_try / probe_write                      │
│  • write_reg_with_policy / write_reg_cond_with_policy                   │
│  • atomic_rmw / atomic_cmpxchg / load_exclusive / store_exclusive       │
│  • fence(FenceRequest) / clear_reservation(ReservationId)               │
│  • fp_binop / fp_binop_ex / fp_fma_ex / fp_unary_ex / fp_compare_ex ... │
│  • extract_element / insert_element / lut / shuffle_bytes               │
│  • transaction_model / progress_model / commit_checkpoint / trap_if ... │
│  • flag_demand() -> FlagDemand                                          │
└─────────────────────────────────────────────────────────────────────────┘
  • No control-flow methods: IrEmitter intentionally lacks branch, jump, or basic_block. Every execution returns a ControlEffect<E::Value> or SemanticControl<E::Value>.
  • #[non_exhaustive] operation enums: BinOp, UnOp, CmpOp, FpOp, FpUnOp, FpCmp, and AtomicOp can gain new variants without breaking existing emitters.
  • Lifecycle boundary (begin_instruction): Establishes the boundary for InstructionExecution choices before the first semantic emission, independent of optional mnemonic or source-address metadata.

SemProgram and the Micro-Op VM

Most instruction semantics live as pure data in a SemProgram (SemProgramRef<'_>): a finite list of typed MicroOps operating over a flat Slot (u16) array:

SemProgram (const / OwnedProgram)
   │
   ▼
verify_program[_for_insn]_with_limits()   ◀── mandatory trust boundary
   │
   ▼
run / run_checked / run_with_limits<E: IrEmitter>(program, &mut ctx, insn, entry)
   │
   ▼
Result<SemanticControl<E::Value>, LiftError>

Key micro-op categories include:

  • Emit-time expressions (ImmExpr): Symbolic width and constant expressions resolved per decoded instruction (DstWidth, DstWidthX2, HalfDst, OperandWidth(i), ElemBits, LaneCount, InsnAddr, NextAddr, Lane, OuterLane(k), arithmetic).
  • Emit-time control (StaticIf, Unroll, VLoop): Compile-time/decode-time specialization over static predicates (BuildPred: IsVector, LongMode, HasBroadcast, HasEmbeddedRounding, MaskZeroing, OperandIsMemory(i), DstWidthEq(n), etc.) and bounded unrolling.
  • Dataflow & effects: Const, ReadOp, WriteOp, WriteMasked, ReadReg, WriteReg, WriteRegCond, BinOp, UnOp, Cmp, Zext, Sext, Trunc, Select, Snapshot, Load, LoadCond, Store, StoreCond, ProbeWrite, AtomicEvent, Fence, ClearReservation, TrapIf, TrapIfCode, Fault, Require, Choice, OpaqueIntrinsic, EmitFlags, EvalCond.
  • Compound instruction phases: Non-delay compound instructions (e.g., x86 near CALL) can partition top-level micro-ops via CompoundInstructionSpec (Operation, MemoryAccess, Completion), retaining member order and provenance within a single fragment.

Execution always runs the canonical verifier (vm_verify) before calling the emitter, checking definite slot assignment, widths in 1..=512, lane/index bounds, partial-operation preconditions (NonZeroDivisor, shift counts), choice compatibility, and transaction-region structure.

LiftCtx and DecodeContext

DecodeContext<S>

Every public decoder (Decoder trait) takes &self, input bytes, an address, and a DecodeContext<S>:

  • mode: CpuMode and manifest-selected decoder_mode: DecoderModeId
  • enabled_features: EnabledFeatures: canonical, sorted, duplicate-free DecodeFeature set admitted under ResourceLimits
  • endianness: Endian: decode-dependent byte order
  • state: S: DecodeArchitectureState: bounded, revisioned architecture-specific state (or NoDecodeState)

Decoders return Result<DecodeOutcome<Insn, S>, DecoderFailure>, where DecodeOutcome carries an explicit DecodeContextTransition<S> describing every per-field context change (such as mode switches). Checked entry points (decode_checked, decode_checked_with_limits) validate both input context and transition output before caller state changes.

LiftCtx<'a, E: IrEmitter>

Every semantic provider receives &mut LiftCtx<E>, which bundles:

  • emitter: &'a mut E
  • arch: &'a ArchManifest — declarative register file, flag model (including CarryPolarity), CPU modes, address spaces, segmentation model, and stack direction
  • mode: CpuMode and profile: ModeProfile (address/operand/stack widths, pc_read_bias, SegSemantics)
  • insn_va: u64 and next_va: u64
  • image: Option<&'a dyn ImageReader> and binary_mode: BinaryMode
  • arch_state: &'a mut dyn ArchState — optional lift-time state (plus ArchState::post_instruction for hardware-loop branches)

ControlEffect and SemanticControl

Control flow is never emitted into the IR; it is returned as ControlEffect<V> / SemanticControl<V>:

  • FallThrough — sequential continuation to next_va
  • Jump { target } — direct or indirect jump (with ModeSwitch)
  • Branch { cond, taken, fallthrough, delay_slots, annul } — 1-bit predicate, taken Target, fallthrough VA, and delay-slot/annul policy (AnnulRule)
  • Call { target, return_to } — call transfer with continuation VA and explicit ControlLink timing (before_transfer, before_delay_slots, after_delay_slots)
  • Return { target: Option<V> } — register-based (ARM64 X30) or stack-popped (x86 RET)
  • Trap { kind: FaultKind } — terminal architectural fault/trap (with optional TrapPayload)
  • Switch { value, cases, default } — direct multi-way branch
  • Rep { cond, body, latch, entry } and LoopLatch { cond } — driver-instantiated runtime repeat loops (such as x86 REP/REPE/REPNE)

SemanticControl is the unified, checked terminal record carrying dense ControlSuccessorIds, ControlSuccessorRoles, ControlGuards, ControlSchedule, DecodeTransitionIntent, and SemanticFidelity.

OpaqueIntrinsic: Structured Contracts

When portable micro-ops cannot expand an operation, OpaqueIntrinsic replaces raw string-only intrinsics with a complete, validated contract:

  • identity: OpaqueIntrinsicIdentity — target-independent name + revision (u32)
  • reason: OpaqueReasonCode — why it is opaque (ArchitectureIntrinsic, ExternalEnvironment, ImplementationDefined, PatternOpaque, etc.)
  • inputs: Vec<OpaqueInput> and outputs: Vec<OpaqueOutput> — typed roles (Value, Address, Predicate, MemoryData, RoundingControl, Custom(u16)) and exact widths (OpaqueBitWidth). Multi-output descriptors denote one single execution, never one call per output.
  • registers: Vec<OpaqueRegisterEffect> — exact Slice, Flag, Storage, or explicit aggregate (AllRegisters, AllFlags, AllArchitecturalState) effects (Read, Write, Preserved, Undefined, ConservativeClobber)
  • memory: OpaqueMemoryBehavior, faults: OpaqueFaultBehavior, control: OpaqueControlBehavior, choices: Vec<OpaqueChoice>
  • volatile: bool and fidelity: SemanticFidelity

Optional algorithm families (OpaqueFamily::Crypto and OpaqueFamily::Math) remain compact opaque intrinsics by default unless an emitter opts into expansion via IrEmitter::opaque_expansion().

Choice & ChoiceBindingEnvironment

Architectural nondeterminism is modeled by ChoiceRequest / ChoiceSpec rather than undef or poison:

DimensionVariants
ChoiceKindUnspecified, ConstrainedUnpredictable, ImplementationDefined, Environment, Entropy, Uninitialized
ChoiceScopeFreshPerObservation, ProducedValue, InstructionExecution, ExecutionSession, MachineProfile, ExternallySupplied
ChoiceDomainAny, Masked { known_zero, known_one }, UnsignedRange { min, max }, Finite(alternatives)

Scopes from InstructionExecution upward require a correlation ChoiceKey. For persistent scopes (ExecutionSession, MachineProfile, ExternallySupplied), ChoiceBindingEnvironment provides the backend-neutral bridge:

  • Callers assign deterministic 128-bit ChoiceBindingNamespaces (ExecutionSession, MachineProfile, ExternallySupplied).
  • (scope, namespace, key) maps to a stable ChoiceBindingIdentity, rejecting any incompatible reuse (mismatched width, kind, or domain).
  • Checked entry points (predeclare_persistent_choices) validate and register the complete persistent-choice plan before beginning an instruction or mutating target IR.
  • For multi-fragment instructions (such as REP loops), InstructionExecutionGroup (Root, RepeatBody, RepeatLatch) and predeclare_instruction_execution_choices correlate InstructionExecution choices across fragments.

Register Identity (RegisterId, RegisterDesc, IndexedRegisterBank)

Registers are identified structurally rather than by backend-specific integers:

  • RegisterId: (cid: u32, arch: u8, offset: u16, role: RegisterRole) where role is Physical, Flag, or System.
    • On x86, AL/AX/EAX/RAX share cid = 0, offset = 0, while AH has cid = 0, offset = 8.
    • On AArch64, W0 and X0 share cid = 0, offset = 0, and V0 is the low 128-bit slice of Z0.
  • RegisterDesc: RegisterId paired with exact access width bits: u16.
  • RegisterWritePolicy: Preserve (write slice only, keep upper bits) vs. ZeroExtendParent (zero-extend into parent, e.g. x86 32-bit GPR writes to 64-bit parents, AArch64 Wn→Xn, VEX/EVEX vector writes).
  • IndexedRegisterBank: Runtime-indexed register banks (such as x87 ST(i)) preserve (base, count, index_bits, element_bits) and are bounds-checked (index < count) before emitter mutation.

Guest Memory Contracts & Fault / Transaction Models

Every memory access carries a MemoryAccessRequest:

  • Address space & granularity: AddrSpace (Data, Code, Io, Vendor(u16)), AddressSpaceResolution (with AddressSpaceAliasGroup), address_width_bits, data_width_bits, addressable_unit_bits (AddressableUnitWidth), and MemoryEndian (Little, Big, Unknown).
  • Access & strictness: MemoryVolatility, MemoryOrdering (including AcquirePerLocation for Arm RCpc and *_LimitedRegion for FEAT_LOR), Atomicity (NonAtomic, Atomic, GuestDefined), ReservationAction, MemoryAlignment, MemoryPrivilegePolicy, GuardPolicy, MayFaultPolicy, and TransferMask.
  • Compound events: MemoryEventContract pairs MemoryEventDescriptor (Read, Write, Rmw, CompareExchange, LoadExclusive, StoreExclusive, Fence, CacheMaintenance, OpaqueMemory) with runtime MemoryEventBindings (predicate, dynamic mask, passthrough).
  • Write probes: IrEmitter::probe_write checks store-permission faults over data_bits without writing data or changing memory.

Fault & Transaction Matrix

Each executed SemProgramRef is a transaction-metadata region governed by (TransactionModel, ProgressModel):

TransactionModelProgressModelSemantics on Fault
Restartable (default)Exact (default)Entry state or latest explicit Commit checkpoint is visible
ProgressiveExactEvery preceding effect is visible in exact authored order
ProgressiveCanonicalPrefixEmitted prefix is guaranteed visible; later permitted effects may also have completed
PermittedMemorySubsetExactRegisters/non-memory state roll back to checkpoint; an implementation-selected subset of other memory mutations in the checkpoint segment may be visible (excluding the faulting mutation)

Explicit Commit checkpoints close pending effect sites since region entry or the previous commit (Commit describes exception visibility, never inter-thread memory ordering).