The Asem Language
Asem (Architectura Semantics, dialect asem 1.0) is the source language for authoring instruction semantics and machine-code form catalogs in Architectura. Every .asem file under semantics/ is compiled by archsem-lang (archsemc) into the exact same archsem_core::SemProgram representation and validated by the canonical archsem-core verifier before any code or package is emitted.
source.asem ─▶ lex ─▶ parse ─▶ lower (resolve · typecheck · instantiate)
─▶ SemProgramBuilder ─▶ canonical verifier ─▶ Rust / .asemc
Asem adds no runtime control flow or hidden semantics of its own: everything lowers to archsem-core micro-ops, and any verifier rejection is a compile-time error.
File Structure & Imports
Every .asem file opens with a dialect header, a dotted module path, optional relative imports, and top-level items:
language asem 1.0;
module x86.bmi2_shift;
import "common_helpers.asem";
import "PATH";imports declarations (fragment,template,register,fault,table,opaque intrinsic,atomic event) transitively under a shared namespace with no shadowing. An imported file'sprogram,pattern,subprogram,form, andwrite_hookitems are not emitted by the importer.- Comments support
//line and/* ... */block syntax. Keywords are contextual.
Top-Level Items
| Item | Syntax | Purpose |
|---|---|---|
template | template NAME<TypeParams>(ValueParams) [stack evm ...] { ... } | Parameterized program body instantiated by program items |
program | program SYM [annots] [atomic] route "ROUTE" [compound(...)] = TEMPLATE<...>(...); | Instantiates a template for a decoder route (program_for or atomic_program_for) |
pattern | pattern NAME [@revision(n)] [@slots(n)] { ... } | Non-parameterized, self-routed program (often entry-parameterized via entry) |
subprogram | subprogram NAME [@slots(n)] { ... } | Non-routed helper program (used by finish rep ... body ... latch ...) |
fragment | fragment NAME [(params) -> (outs)] { ... } | Reusable statement block expanded via expand (hygienic when parameterized; splice when parameterless) |
form | form NAME for SEMANTIC { ... } | Declares one legal machine-code encoding/operand/decorator realization |
register | register NAME = physical|flag|system CID [arch N] [offset B] [count N]; | Declares an architectural register or contiguous register bank |
fault | fault NAME = "MNEMONIC" trigger TRIGGER class CLASS; | Declares an architectural fault/trap identity |
table | table NAME : bits<W> = { v0, v1, ... }; | Declares a compile-time / lut byte table |
opaque intrinsic | opaque intrinsic NAME { ... } | Declares a typed OpaqueIntrinsic descriptor |
write_hook | write_hook NAME on register BANK max_bits N { ... } | Dispatch-time transformer bracketing writes to a register bank (e.g. ARM64 AdvSIMD V→Z overlap) |
Types, Widths & Meta-Expressions
Every value has a positive bit width : bits<M>, where M is an ImmExpr meta-expression:
- Literals & parameters:
bits<8>,bits<64>, templatewidthparameters (bits<w>), numericstatic forloop indices (ImmExpr::Lane,ImmExpr::OuterLane(k)). - Symbolic width leaves:
dst_width,dst_width_x2,half_dst,addr_width,stack_width,elem_bits,lane_count,entry_narrow_bits,insn_addr,next_addr,lane,operand_width,embedded_rounding,insn_word,guest_addr_width,x86_fpu_opcode. - Operand builtins:
operand_width(n),imm_of_operand(n),operand_reg_num(n),mem_scale(n),mem_disp(n),mem_segment(n),operand_lane(n),operand_lane_bits(n),operand_shift(n), etc. - Meta arithmetic & folding:
add,sub,mul,div,shl,shr,and,xor,eq,ne,lt,le,gt,ge,mask,lit(...).
Statements, Expressions & Templates
language asem 1.0;
module x86.bmi2_shift;
template shift_to_dest<Op: binop>() {
let src = read operand 1 : bits<dst_width>;
let count = read operand 2 : bits<dst_width>;
let mask = const sub(dst_width, 1) : bits<dst_width>;
let masked = binop and(count, mask) : bits<dst_width>;
let result = binop Op(src, masked) : bits<dst_width>;
write operand 0 <- result;
finish fallthrough;
}
program RORX route "RORX" = shift_to_dest<ror>();
program SARX route "SARX" = shift_to_dest<ashr>();
program SHRX route "SHRX" = shift_to_dest<lshr>();
program SHLX route "SHLX" = shift_to_dest<shl>();
- Slot allocation: Each fresh
let x = ...;claims the nextSlotin source order (@slot(n)pins an exact slot;@slots(n)sets minimum capacity). Re-binding an existing name (let x = ...;) reuses its slot in place. - Compile-time specialization:
static if PRED { ... } else { ... }selects at instantiation or emitsStaticIf(is_vector,long_mode,has_broadcast,has_embedded_rounding,mask_zeroing,operand_is_memory(i),predicate_is(COND), etc.).static for I in 0 .. Nlowers toUnroll;static for X in { ... }unrolls at compile time. - Value & vector ops:
binop,unop,cmp,zext,sext,trunc,resize,snapshot,select,funnel_shift,vec_binop,vec_unop,vec_compare,vec_reduce,vec_broadcast,vec_extract,vec_insert,vec_resize,vec_shift_var,lut, plus explicit-rounding scalar/packed floating point (fp_binop,fp_binop_ex,fp_fma_ex,fp_unop_ex,fp_compare,fp_convert_ex,fp_to_int_ex,int_to_fp_ex,vec_fp_*). - Status flags (
emit_flags&flagsblocks):emit_flagsinvokes the manifest-driven flag engine (entry,logic,add,sub,adc,sbb).flags over(...) [when C] [covers status|nzcv] { ... }declares per-flag symbolic expressions (withzf,sf,pf,carry_add,carry_sub,borrow_sub,overflow_add,overflow_sub,aux_*,undefined,preserve, or recipe arms). Canonicalflagsblocks lower to the exact shared flag-engine micro-op. - Memory & atomics:
load,load_cond,store,store_cond,probe_write,load linear,store linear,segment_address,atomic_rmw,atomic_cmpxchg,load_excl,store_excl,clear_reservation, andfence. Qualified memory accesses supportunprivileged,volatile,ordered <ORDERING>,space data|code|io, andguest_atomicity(...). - Predicated writes (
when):when COND { write reg ...; }lowers toWriteRegCond/ApplyWritebackCond(pure expressions execute unconditionally; only architectural register writes and writebacks are predicated). - Compound phases & terminals: Non-delay compound instructions partition top-level ops via
phase operation 0 { ... } phase memory 0 { ... } phase completion { ... }. Terminals includefinish fallthrough;,jump,branch,switch,call ... link ... timing ...;,stop halt|wait|unreachable;,trap ...;,fault NAME [when COND];,require C "reason";, andfinish rep ... body ... latch ...;.
choose & opaque intrinsic
Nondeterminism (choose)
let undef_cf = choose unspecified : bits<1>;
let z_choice = choose constrained_unpredictable scope instruction_execution key 0x5356455a4552_4f55 values(0, 1) : bits<1>;
- Kinds:
unspecified,constrained_unpredictable,implementation_defined,environment,entropy,uninitialized. - Scopes:
fresh_per_observation,produced_value(default),instruction_execution,execution_session,machine_profile,externally_supplied(correlation scopes requirekey N). - Domains: Unrestricted by default, or
values(v0, v1, ...)for finite domains.
Structured Opaques (opaque intrinsic)
opaque intrinsic CPUID_LEAF {
identity: "x86.cpuid";
revision: 0;
reason: architecture_intrinsic;
inputs: (value : bits<32>, value : bits<32>);
outputs: (value unknown : bits<32>, value unknown : bits<32>,
value unknown : bits<32>, value unknown : bits<32>);
registers: (
reg EAX read, reg ECX read,
reg EAX write output(0), reg EBX write output(1),
reg ECX write output(2), reg EDX write output(3)
);
memory: none;
faults: none;
control: fall_through;
choices: ();
volatile: false;
fidelity: opaque_dataflow;
}
@preserve_form programs wrap a single zero-input/zero-output opaque intrinsic for RecompilationDisposition::PreserveForm rows (such as PAUSE).
form Declarations
form declarations describe legal machine-code realizations independently of semantic behavior:
form LOCK_ADD for atomic_add {
decoder "Add_rm64_r64";
family legacy;
modes(64);
operand 0 read_write mem any : bits<64>;
operand 1 read reg gpr : bits<64>;
prefix lock required;
}
Forms support value extensions (sign_extend/zero_extend/truncate to bits<W>), destination parent write policies (preserve/zero_extend/sign_extend), EVEX mask/zeroing/sae/rounding/evex_b, vsib, fixed, implicit, immediate, upper_lanes, alternative, memory legality contracts, address overrides, and Knights Corner mvex conversions/swizzles/eviction hints.
Canonical Verification & Static Lints
Every program runs archsem-core's canonical verifier during compilation, rejecting slot errors, width mismatches, and unproved partial operations (NonZeroDivisor obligations can be discharged in-program via explicit guards/selects or deferred to per-instruction verification).
Additionally, passing --lint (or annotating @lint / @allow(...)) enables four cross-cutting static lints in archsem-lang:
form_mismatch: Cross-checks everyformcontract against the inferredProgramEffectSummaryacross syntheticInsnViewrealizations (operand read/write directions, memory access contracts, and implicit flags).fault_after_commit: Flags uncommitted architectural register, flag, or operand writes that precede a potentially faulting memory access or trap/fault check without an interveningcommit;ortransaction progressive;.unhygienic_fragment: Flags legacy parameterless splice fragments in favor of hygienic parameterized fragments.duplicate_register: Flags distinctregisterdeclarations in the same unit that alias an identical(role, cid, arch, offset)identity.