Neutral RTL & Function CFG (archsem-ir)

archsem-ir sits between architecture lifting and downstream consumers (simplifiers, symbolic engines, decompilers, or LLVM/native code generators). It captures IrEmitter streams as validated, backend-neutral SSA RTL (Fragment) and whole-function CFGs (Function).

decode + arch lift ─▶ RtlEmitter ─▶ Fragment (instruction-local RTL + EventGraph + OriginGraph)
                                       │
                                       ▼  lift_reachable_stateless / lift_reachable_stateful
                                    Function (CFG of BasicBlocks + ExceptionalEdges)
                                       │
          ┌────────────────────────────┼────────────────────────────┐
          ▼                            ▼                            ▼
    RegisterSsa / StackMemorySsa   EffectSummary /              replay_cfg /
    ConservativeMemorySsa          CfgEffectSummary             replay_register_ssa

RtlEmitter and Fragment

RtlEmitter implements IrEmitter<Value = ValueId> and produces a Fragment via finish(SemanticControl<ValueId>) (or finish_legacy(ControlEffect<ValueId>)). Unlike an audit-only trace, RtlEmitter:

  • Records every register read at its exact position and access width.
  • Keeps memory, fault, fence, atomic, reservation, and opaque effects strictly ordered.
  • Retains full MemoryAccessRequest, MemoryEventContract, OpaqueIntrinsic, and ChoiceSpec descriptors.
  • Materializes terminal control as a distinct final event (EventId::TERMINAL) inside Fragment::control.

Fragment::validate() independently checks positive non-zero widths (1..=512), canonical constants, operand/result width consistency, conversion directions, 1-bit guards, valid memory/opaque contracts, SSA dominance/use-before-definition, and coherent terminal control.

Fragment::optimize

Fragment::optimize(OptimizeConfig) runs a strict instruction-local pass performing:

  • Width-aware constant folding (1..=512 bits, sharing archsem_core::bitvec exact evaluation, never folding partial-operation UB into constants)
  • Copy/identity propagation and commutative canonicalization
  • Conservative GVN (never commoning Load, ReadReg, Fp*, Opaque*, or distinct Choice identities; pure expressions reusing one stable produced choice are eligible)
  • False-predicate memory simplification (converting a statically false LoadCond to Const(0) and dropping a statically false StoreCond / TrapIf / WriteRegCond)
  • Dead pure-node elimination while retaining all observable effects and stable EventIds

EventGraph, Backward Slicing, and Effect Summaries

Instruction-Local EventGraph

Fragment::event_graph() projects the Node sequence into a validated DAG over stable EventIds plus EventId::TERMINAL. Edges explicitly distinguish:

  • Value(ValueId) — dataflow dependence
  • Address(ValueId) — effective-address dependence
  • ControlPredicate(ValueId) — branch/guard predicate dependence
  • IndirectTarget(ValueId) — computed transfer target
  • RegisterIndex(ValueId) — dynamic indexed-bank selector
  • RegisterSlice(RegisterId) / Flag(RegisterId) — architectural register/flag dependencies
  • MemoryVersion — instruction-local memory ordering
  • EffectOrder / FaultOrder — checkpoint, barrier, and fault precedence
  • ReservationState(ReservationId) — local exclusive monitor state

Policy-Free Backward Slicing

Fragment::backward_slice(&[SliceRoot], SliceEdgeKinds) computes a deterministic BackwardSlice (events, values, and dependency edges) from caller-chosen SliceRoot::Event(EventId) or SliceRoot::Value(ValueId) roots and opt-in SliceEdgeKinds (VALUE, ADDRESS, CONTROL_PREDICATE, INDIRECT_TARGET, REGISTER_SLICE, FLAG, MEMORY_VERSION, EFFECT_ORDER, FAULT_ORDER, REGISTER_INDEX, RESERVATION_STATE). It makes no taint, alias, or recovery assumptions on the caller's behalf.

EffectSummary and CfgEffectSummary

  • EffectSummary::from_fragments composes straight-line fragments (retaining each fragment's optional InstructionExecutionGroup) and summarizes register reads/writes/preserved slices (using the ArchManifest if provided, or conservative raw descriptors otherwise), memory effects, faults, requirements, and uncertainty boundaries.
  • Function::cfg_effect_summary summarizes whole functions per block while retaining the original typed terminator, exceptional edges, multi-predecessor joins (CfgSummaryJoin), and cyclic strongly connected components (CfgSummaryLoop) without flattening mutually exclusive paths.

OriginGraph Provenance & SemanticFidelity

OriginGraph

Every value, effect, and terminal in a Fragment resolves to a stable OriginId inside a bounded, interned OriginGraph DAG:

  • Instruction origin (InstructionOrigin: address, exact bytes, decode context fingerprint, architecture identity, mnemonic, optional consumer-supplied execution/trace/occurrence/epoch supplement via OriginSupplementProvider)
  • Semantic sites (SemanticSite: program identity, revision, nested MicroOpPath, operand role, lane)
  • Ordered bundle membership (OrderedBundleMember for delay slots and compound instructions)
  • Derived values, local transforms, aliases/merges, and explicit truncation markers (OriginTruncationReason)

Optimization passes (Fragment::optimize, archsem-simplify, CFG passes) return explicit transformation mappings (FragmentTransformMappings, FunctionTransformMappings) instead of silently dropping provenance.

SemanticFidelity & FidelityAnalysis

Each Fragment carries a declared SemanticFidelity (coverage, determinism, choice kinds, observable facets, validation evidence, and reason codes). Calling fragment.analyze_fidelity() derives a fresh FidelityAnalysis over the current typed graph—tainting values and observable events only through their actual dependencies and matching observable facets—so rewrites never leave stale side tables.

Function: Reachable CFG Discovery

lift_reachable_stateless and lift_reachable_stateful discover reachable basic blocks starting from an entry address using a Decoder and ImageReader:

  • State-keyed discovery: lift_reachable_stateful keys blocks by (address, CpuMode, DiscoveryState::Key). ContextualDiscoveryState<S, K> lets consumers compose a caller-owned key (such as a code epoch or virtual-PC context) without exposing dispatcher or unpacking heuristics to archsem.
  • Bounds & Incompleteness (Completion): CfgLiftConfig bounds address_range, extra_ranges, additional_entries, max_instruction_bytes, max_instructions, max_blocks, max_total_bytes, max_switch_cases, and decode_limits. If discovery hits a decode failure, unsupported instruction, or resource limit, it attaches a bounded IncompletenessRecord and returns a CfgLiftFailure containing the partial Function (Completion::Incomplete). Destructive transforms and executable replay reject incomplete functions until explicitly valid and marked complete (mark_complete).
  • Ordered Bundles & Repeat Loops: Non-annulled straight-line delay slots and compound instructions remain grouped via OrderedBundle / TransactionRegionId; taken-only annulled slots clone blocks as needed; REP instructions lower into Root, RepeatBody, and RepeatLatch InstructionExecutionGroup fragments.
  • Function Normalization (Function::optimize_function & canonicalize_cfg): Supports fragment simplification, expression forwarding across blocks, register SCCP (RegisterSccpStats), architecture-aware bit-granular register DCE (RegisterDceConfig, ExitLivenessPolicy, ExceptionalStateRoots), constant branch/switch folding, unreachable-block pruning, and optional empty-trampoline threading / linear block coalescing (Function::canonicalize_cfg).

Register SSA & Memory SSA

archsem-ir provides three validated CFG-level SSA products, each independently reconstructible and verifiable via ssa_validation:

  1. RegisterSsa::build(&function, &arch) Promotes architectural parent registers (ParentReg) into SSA values with block-entry RegisterPhis across diamonds and loops. Understands x86 nested GPR slices (AL/AH/AX/EAX/RAX), AArch64 Wn→Xn zero-extension, and vector parent clearing/merging policies.
  2. StackMemorySsa::build(&function, &arch) & optimize_stack_memory Identifies exact, non-overlapping affine SP ± const slots when SP is stable and no call, unwind, atomic, conditional, or opaque memory boundary intervenes. Under StackMemoryConfig::strict(), no loads or stores are eliminated; under assume_private_stack_accesses_non_faulting(), dead private stack stores can be removed.
  3. ConservativeMemorySsa::build(&function) / build_with_partition & MemoryDependencyGraph Assigns whole-memory tokens (MemoryToken) across arbitrary-address loads, stores, atomics, fences, opaque intrinsics, and call clobbers. Callers may supply a labeled MemoryPartitionPolicy to separate disjoint memory classes. MemoryDependencyGraph::build projects constant-address unit ranges (MemoryDependencyRange) and supports function-level memory backward slicing (MemoryDependencyGraph::backward_slice) without claiming general alias recovery.

Retained Artifacts & External Observations

  • Immutable Lineage (RetainedFragmentArtifact, RetainedFunctionArtifact): Keeps the raw lifted artifact immutable while running normalization as a transactional clone-transform-validate-commit query (NormalizationGeneration, NormalizationRecord).
  • External Observation Binding (ObservationSet, TraceSequence): Binds dynamic execution evidence (PC, observed bytes, occurrence IDs, code epochs, register values with known-bit masks, memory transfers, unified control outcomes, and pre-terminal faults) to fragment values/events/origins via typed ObservationBindingRoles. Caller hypotheses live separately in ObservationAssumptionSet (AssumptionHint).

Replay (replay, replay_cfg, replay_register_ssa)

  • Fragment::replay(&mut emitter): Replays an instruction fragment into any IrEmitter, predeclaring persistent choices and installing per-event and terminal SemanticSites.
  • Function::replay_cfg(&mut sink): Replays raw blocks, transaction regions, grouped repeat roles, and prioritized ExceptionalEdges with ExceptionalMemoryState visibility descriptors into a FunctionReplaySink.
  • Function::replay_register_ssa(&mut sink) / replay_register_ssa_with_calls: Lowers sparse live-in block parameters (ParentReg), edge-parallel EdgeAssignment batches, partial-parent reconstruction, and injected CallSummarys into an executable RegisterSsaReplaySink (such as archsem-llvm). Before mutating backend state, replay checks ReplayCapabilities against the function's ReplayRequirements.