<< lib/cpu/SLCPURuntime.sleela SLeeLa Standard Library Definition. Definition: Defines SLCPURuntime — the runnable base class every specific Sleela-sourced CPU model extends. It supplies the machinery a bare SLCPU skeleton was missing: real register storage (over SLRAM), architectural flags, a word-addressable memory interface, an ALU, a program counter, and a fetch-decode-execute loop with reset/step/run lifecycle. Crucially, SLCPURuntime is the seam that lets a CPU model run ON TOP OF the secondary Sleela VM: it owns an SLSleelaVM substrate and a lowering surface (emitConst/emitBinary/emitStore/...) so a concrete CPU can translate each of its native instructions into the canonical SLeeLa opcodes and execute them on the same engine the native Sleela VM interprets. A per-architecture model therefore only has to (a) declare its registers and (b) implement decode() to map its opcodes onto the ALU and the substrate — everything structural is inherited. Subclassing contract (what a concrete CPU overrides): - configureArch(): set widths and register count, then call bringUp(). - decode(int word): map one fetched instruction word to execute*() / emit*(). - optionally reset()/interrupt() for arch-specific state. Family: cpu. Composes SLRAM, SLALU, SLSleelaVM, SLSleelaOpcode. Extended by SL6502CPU, SLZ80CPU, SLX86CPU, SLARMCPU, SLMIPSCPU, SLRISCVCPU, SLM68000CPU. >> #sleela 2.5 material; class SLCPURuntime { < ---- Descriptive metadata (version 1.11 nested-friendly accessors) ---- > << Eleven catalogued attributes with getter/setter pairs, so a GUI, loader, or catalog can read and (where appropriate) override this record. Values are faithful to the subject's real origin where publicly known. >> String metaVersion = "1.0.0"; int metaId = 10493; String metaAuthor = "Kiro Agent"; String metaDate = "2026-10-16"; String metaCopyright = "SLeeLa project"; String metaTrademark = "none"; String metaCorporation = "none"; < metaOrigin: National | | International | Galactic > String metaOrigin = "International"; String metaBirthDate = "2026-10-09"; < metaScienceRating: maturity/robustness on a 1..10 scale > int metaScienceRating = 9; < metaNationalSchedule: a real, citable instrument or "none" > String metaNationalSchedule = "none"; String getMetaVersion() { return metaVersion; } void setMetaVersion(String v) { metaVersion = v; } int getMetaId() { return metaId; } void setMetaId(int v) { metaId = v; } String getAuthor() { return metaAuthor; } void setAuthor(String v) { metaAuthor = v; } String getDate() { return metaDate; } void setDate(String v) { metaDate = v; } String getCopyright() { return metaCopyright; } void setCopyright(String v) { metaCopyright = v; } String getTrademark() { return metaTrademark; } void setTrademark(String v) { metaTrademark = v; } String getCorporation() { return metaCorporation; } void setCorporation(String v) { metaCorporation = v; } String getOrigin() { return metaOrigin; } void setOrigin(String v) { metaOrigin = v; } String getBirthDate() { return metaBirthDate; } void setBirthDate(String v) { metaBirthDate = v; } int getScienceRating() { return metaScienceRating; } void setScienceRating(int v) { metaScienceRating = v; } String getNationalSchedule() { return metaNationalSchedule; } void setNationalSchedule(String v) { metaNationalSchedule = v; } String archName; < data path width in bits > int width; < address bus width in bits > int addrWidth; < architectural register count > int regCount; < architectural registers (one word each) > SLRAM regs; < word-addressable system memory > SLRAM mem; int memWords; SLALU alu; < program counter (word index) > int pc; int flagZ; int flagN; int flagC; int flagV; int halted; < instructions executed > int retired; < --- clock: run at the model's spec, with overclock support --- > < spec/overclock frequency policy > SLClockPolicy clock; < the model's rated clock (set via setSpecClock) > int specMHz; < --- secondary-VM substrate: the CPU runs its lowered form here --- > SLSleelaVM substrate; SLSleelaOpcode op; < 1 => execute by lowering to canonical opcodes > int lowering; < --- workload execution: run C / C++ / Sleela work on this CPU within a > < resource grant. The register-ISA mapping pipeline is shared across all > < architectures (SLCompilerDriver -> SLProgram -> SLOpcodeMap -> substrate). --- > SLInstructionSet workIsa; SLInstructionDecoder workDecoder; SLSystemCall workSys; < the grant the current workload runs within > SLCPUResource activeGrant; int admittedWorkloads; int completedWorkloads; < --- substrate injection (nesting seam) --- > < When a host (the Secondary Sleela VM, SLVM) wants the CPU to run as a guest > < ON its substrate rather than on a private one, it attaches that substrate > < here. runWorkload()/mapWorkload() then target the attached substrate, so the > < CPU's lowered opcode stream and the host's dispatch loop operate on ONE > < SLSleelaVM — the true "CPU on top of the Secondary VM" nesting the docs > < describe. When null (the default) the CPU owns its substrate as before. > SLSleelaVM attachedSubstrate; < --- optional capabilities: direct DMA and native GPU access --- > < Off by default. A program/executor that needs them turns them on; when on, > < the CPU exposes a direct-memory-access engine and a GPU device it can > < offload to at any point. > < 1 when direct DMA is enabled > int dmaOption; < 1 when native GPU access is enabled > int gpuOption; < the DMA engine (operates over this CPU's memory) > SLDMAController dma; < the GPU device > SLGPUDevice gpu; < Bring the inherited machinery up once a subclass has set its widths. > void bringUp(String name, int dataBits, int addressBits, int registers, int memoryWords) { archName = name; width = dataBits; addrWidth = addressBits; regCount = registers; memWords = memoryWords; regs = new SLRAM(); regs.configure(registers + 1, 32); regs.allocate(); mem = new SLRAM(); mem.configure(memoryWords, 32); mem.allocate(); alu = new SLALU(); alu.configure(dataBits); pc = 0; flagZ = 0; flagN = 0; flagC = 0; flagV = 0; halted = 0; retired = 0; substrate = new SLSleelaVM(); substrate.configure(memoryWords, 4096, registers + 16); op = new SLSleelaOpcode(); op.configure(0, "OP_NOP"); lowering = 0; < Default the clock to a conservative 1 MHz spec; a model/user overrides it > < with setSpecClock(ratedMHz) so the CPU runs at its own specification. > clock = new SLClockPolicy(); specMHz = (specMHz > 0) ? specMHz : 1; clock.configureSpec(specMHz); < Shared multi-language workload pipeline. > workIsa = new SLInstructionSet(); workIsa.configure(); workDecoder = new SLInstructionDecoder(); workDecoder.configure(workIsa); workSys = new SLSystemCall(); workSys.configure(); admittedWorkloads = 0; completedWorkloads = 0; < Optional capabilities default to off. > dmaOption = 0; gpuOption = 0; } < --- optional capability: direct DMA --- > < Enable the direct memory-access engine over this CPU's memory. After this a > < program can call dmaEngine().transfer(...) / memcpy(...) / fill(...) to move > < bulk data without the CPU copying word by word. > void enableDMA() { dmaOption = 1; if (dma == null) { dma = new SLDMAController(); } dma.configure(mem); dma.enable(); } void disableDMA() { dmaOption = 0; if (dma != null) { dma.disable(); } } boolean dmaEnabled() { return dmaOption == 1; } SLDMAController dmaEngine() { return dma; } < Convenience passthrough for the common bulk move (returns words moved or -1). > int dmaCopy(int src, int dst, int length) { if (dmaOption == 0 || dma == null) { return -1; } return dma.memcpy(src, dst, length); } < --- optional capability: native GPU access --- > < Enable a GPU device the CPU can offload parallel/compute kernels to. The > < device uses a real host GPU over the bridge when available, else a modelled > < SIMT engine, so GPU code always runs. > void enableGPU() { enableGPU("SLeeLa Compute GPU", 16, 64, 1000, 256); } void enableGPU(String name, int units, int lanes, int core, int vramMiB) { gpuOption = 1; if (gpu == null) { gpu = new SLGPUDevice(); } gpu.configure(name, units, lanes, core, vramMiB); gpu.enable(); } void disableGPU() { gpuOption = 0; if (gpu != null) { gpu.disable(); } } boolean gpuEnabled() { return gpuOption == 1; } SLGPUDevice gpuDevice() { return gpu; } < The register ISA used by the shared compile/map pipeline (SLWorkload.compile > < needs it to lower any supported language to a language-independent image). > SLInstructionSet workloadIsa() { return workIsa; } < Host hands its substrate to the CPU so the CPU runs nested on it (SLVM). > void attachSubstrate(SLSleelaVM hostSubstrate) { attachedSubstrate = hostSubstrate; } void detachSubstrate() { attachedSubstrate = null; } boolean nested() { return attachedSubstrate != null; } < --- clock / overclocking --- > < Set the model's rated clock (its own specification). A concrete SLCPU > < calls this in configure() so the CPU runs at spec; it may be called before > < or after bringUp(). > void setSpecClock(int ratedMHz) { specMHz = ratedMHz; if (clock == null) { clock = new SLClockPolicy(); } clock.configureSpec(ratedMHz); } < Overclock the CPU to a target effective frequency (returns false if the > < target exceeds the model's stability ceiling — the OC is applied but the > < policy reports it unstable). > boolean overclock(int targetMHz) { if (clock == null) { return false; } clock.overclockTo(targetMHz); return clock.isStable(); } void setClockMultiplier(int m) { if (clock != null) { clock.setMultiplier(m); } } void setBaseClock(int mhz) { if (clock != null) { clock.setBaseClock(mhz); } } void setStabilityCeiling(int mhz){ if (clock != null) { clock.setStabilityCeiling(mhz); } } void resetClock() { if (clock != null) { clock.resetToSpec(); } } SLClockPolicy clockPolicy() { return clock; } int specClockMHz() { return specMHz; } int effectiveMHz() { return (clock != null) ? clock.effectiveMHz() : specMHz; } boolean overclocked(){ return clock != null && clock.isOverclocked(); } boolean clockStable(){ return clock == null || clock.isStable(); } < How many model cycles the clock delivers in a given number of microseconds > < (lets a workload budget be expressed in time rather than raw instructions). > int cyclesInMicroseconds(int us) { return effectiveMHz() * us; } < Compile + map a workload onto a target substrate WITHOUT running it, so a > < host (SLVM) can drive the resulting opcode stream itself. Returns the > < substrate that now carries the workload, or null if the workload was > < rejected. Used by SLVM.runGuestWorkload for the Creator -> SLVM -> CPU -> > < program stack. > SLSleelaVM mapWorkload(SLWorkload work, SLSleelaVM target) { if (!admit(work)) { return null; } activeGrant = work.grant(); if (!work.compiled()) { work.compile(workIsa); } if (!activeGrant.ioEnabled()) { target.setHosted(); } SLOpcodeMap map = new SLOpcodeMap(); map.configure(workIsa, workSys, target); map.mapProgram(work.image(), workDecoder); work.markRunning(); return target; } < --- resource assignment + workload execution --- > < Admission control: can this CPU satisfy the workload's resource grant? > < A workload is admitted only when its memory request fits the CPU's address > < space and (if it needs I/O/privileged services) the model provides them. > boolean admit(SLWorkload work) { SLCPUResource g = work.grant(); if (g == null) { work.markRejected(); return false; } if (g.words() > memWords) { work.markRejected(); return false; } if (g.budget() <= 0) { work.markRejected(); return false; } work.markAdmitted(); admittedWorkloads = admittedWorkloads + 1; return true; } < Run a workload on this CPU within its grant. The source (C/C++/Sleela/Java) > < is compiled to the register ISA, mapped onto THIS CPU's canonical-opcode > < substrate, and executed up to the grant's instruction budget. Returns the > < observable output (the printed value), or -1 if the workload was rejected. > int runWorkload(SLWorkload work) { if (!admit(work)) { return -1; } activeGrant = work.grant(); < Compile the source to a language-independent register-ISA image. > if (!work.compiled()) { work.compile(workIsa); } < Target substrate: the host's injected one when nested (CPU runs as a guest > < of the Secondary VM), otherwise a fresh private one sized to the grant so > < one workload cannot see another's memory. > if (attachedSubstrate != null) { substrate = attachedSubstrate; } else { substrate = new SLSleelaVM(); substrate.configure(activeGrant.words(), 4096, regCount + 16); } if (!activeGrant.ioEnabled()) { substrate.setHosted(); } < Map the register-ISA image onto this CPU's substrate. > SLOpcodeMap map = new SLOpcodeMap(); map.configure(workIsa, workSys, substrate); map.mapProgram(work.image(), workDecoder); < Execute within the instruction budget (the resource time-slice). > work.markRunning(); int ran = substrate.run(activeGrant.budget()); int i = 0; while (i < ran) { activeGrant.chargeInstruction(); i = i + 1; } int observable = substrate.printed(); work.markDone(observable); completedWorkloads = completedWorkloads + 1; return observable; } int grantsAdmitted() { return admittedWorkloads; } int workloadsRun() { return completedWorkloads; } SLCPUResource currentGrant() { return activeGrant; } < --- register / memory access (what decode() uses) --- > int readReg(int i) { if (i < 0 || i > regCount) { return 0; } return regs.readWord(i); } void writeReg(int i, int v) { if (i < 0 || i > regCount) { return; } regs.writeWord(i, maskWord(v)); } int readMem(int addr) { if (addr < 0 || addr >= memWords) { return 0; } return mem.readWord(addr); } void writeMem(int addr, int v) { if (addr < 0 || addr >= memWords) { return; } mem.writeWord(addr, maskWord(v)); } int maskWord(int v) { int m = 1; int i = 0; while (i < width) { m = m * 2; i = i + 1; } int r = v % m; if (r < 0) { r = r + m; } return r; } < --- ALU surface (decode() routes arithmetic through here so flags are set) --- > int aluOp(int a, int b, int op) { int r = alu.execute(a, b, op); flagZ = alu.zero(); flagN = alu.negative(); flagC = alu.carry(); flagV = alu.overflow(); return r; } < --- lowering surface: emit canonical opcodes onto the secondary VM --- > void enableLowering() { lowering = 1; substrate.setHosted(); } int emitConst(int v) { return substrate.emit(op.OP_CONST, v); } int emitLoadGlobal(int slot){ return substrate.emit(op.OP_LOADG, slot); } int emitStoreGlobal(int slot){ return substrate.emit(op.OP_STOREG, slot); } int emitAdd() { return substrate.emit(op.OP_ADD, 0); } int emitSub() { return substrate.emit(op.OP_SUB, 0); } int emitMul() { return substrate.emit(op.OP_MUL, 0); } int emitPrint(){ return substrate.emit(op.OP_PRINT, 0); } int emitHalt() { return substrate.emit(op.OP_HALT, 0); } int emitJump(int target) { return substrate.emit(op.OP_JMP, target); } int emitJumpIfFalse(int target){ return substrate.emit(op.OP_JMPF, target); } < Execute the lowered program on the substrate (the "run on top of the > < secondary VM" path). Returns opcodes retired on the substrate. > int runLowered(int budget) { return substrate.run(budget); } int loweredOutput() { return substrate.printed(); } SLSleelaVM engine() { return substrate; } < --- fetch-decode-execute lifecycle (overridable) --- > < Default fetch: read the instruction word at pc and advance. > int fetch() { if (pc < 0 || pc >= memWords) { halted = 1; return 0; } int word = mem.readWord(pc); pc = pc + 1; return word; } < Subclasses override decode() to interpret one instruction word. The base > < treats a zero word as NOP and anything else as HALT so the loop terminates > < safely if a model forgets to override. > void decode(int word) { if (word == 0) { return; } halted = 1; } < Per-instruction hook a subclass overrides for M1-cycle side effects (e.g. > < the Z80 memory refresh). Default does nothing. > void preFetch() { } < One instruction: pre-fetch hook, fetch, decode/execute, count. > int step() { if (halted == 1) { return -1; } preFetch(); int word = fetch(); if (halted == 1) { return -1; } decode(word); retired = retired + 1; return word; } int run(int budget) { int ran = 0; while (halted == 0 && ran < budget) { step(); ran = ran + 1; } return ran; } void reset() { pc = 0; flagZ = 0; flagN = 0; flagC = 0; flagV = 0; halted = 0; retired = 0; int i = 0; while (i <= regCount) { regs.writeWord(i, 0); i = i + 1; } } void loadProgramWord(int addr, int word) { writeMem(addr, word); } void setEntryPoint(int addr) { pc = addr; } < arch-specific; default no-op > void interrupt(int vector) { } < --- introspection --- > boolean validate() { return width > 0 && regCount > 0 && memWords > 0; } String architecture() { return archName; } int programCounter() { return pc; } int instructionsRetired(){ return retired; } boolean isHalted() { return halted == 1; } int dataWidth() { return width; } int registerCount() { return regCount; } int zero() { return flagZ; } int negative() { return flagN; } int carry() { return flagC; } int overflow() { return flagV; } < ================================================================== > < RUNS BY BOTH -- the basis of function every CPU model inherits > < ================================================================== > < A CPU model is defined partly by the fact that it can run code two ways, > < and that the two ways AGREE: > < (1) by OPCODES -- its own instruction set driven through the native > < fetch-decode-execute loop (fetch/decode/step/run); and > < (2) by FUNCTION-CALL EQUIVALENCE -- the code of an assumed other process > < (any supported language/ISA workload) reduced through the shared > < SLOpcodeMap to the equivalent canonical-opcode / service-call stream > < on this CPU's substrate (runWorkload). > < Both mechanisms already funnel to the one canonical SLSleelaVM engine, so > < "runs by both" is not two behaviours but one basis observed two ways. These > < named entry points make that expectation first-class and inherited, and > < basisHolds() asserts the two observables coincide -- the opcode-vs- > < equivalence analogue of SLTuringBridge.proveEquivalence, on a single CPU. > < (1) Run a native instruction-word program through the opcode loop. The > < program is an int[] of packed instruction words (as a model's assembler > < helper produces); it is loaded from `at`, the entry point is set, and the > < fetch-decode-execute loop runs within `budget`. Returns opcodes retired. > int runByOpcodes(int[] program, int at, int budget) { reset(); int n = arrayLength(program); int i = 0; while (i < n) { loadProgramWord(at + i, program[i]); i = i + 1; } setEntryPoint(at); return run(budget); } int runByOpcodes(int[] program, int budget) { return runByOpcodes(program, 0, budget); } < (2) Run the code of an assumed other process by function-call equivalence: > < the workload is compiled and mapped (SLOpcodeMap) to the equivalent opcode / > < service-call stream on this CPU, then executed within its grant. This is a > < first-class, honestly-named view of the shared workload path (runWorkload). > < Returns the observable output, or -1 if the workload was not admitted. > int runByEquivalence(SLWorkload work) { return runWorkload(work); } < The observable result left by the OPCODE path. A native instruction loop > < leaves its result in architecture-defined state (a register or a memory > < cell), NOT on the lowering substrate -- so the base reads register 0 as the > < conventional result slot. A model whose result lands elsewhere (e.g. the > < 6502's accumulator) overrides this to name its own result location, so the > < basis comparison stays honest rather than assuming a fixed convention. > int opcodeObservable() { return readReg(0); } < Does this CPU run by both? The basis holds when the SAME computation, run > < by opcodes and by function-call equivalence, yields the SAME observable. > < `opcodeProgram` is the native-opcode form left in opcodeObservable(); > < `equivalentWork` is the assumed-other-process form whose observable is its > < printed output. `expected` is the agreed result both must produce (callers > < supply it because the two paths observe different surfaces -- a register vs. > < a printed value -- so equivalence means "both equal the intended result", > < not "both read the same physical slot"). Returns true iff both agree with it. > boolean basisHolds(int[] opcodeProgram, int opcodeBudget, SLWorkload equivalentWork, int expected) { runByOpcodes(opcodeProgram, 0, opcodeBudget); int viaOpcodes = opcodeObservable(); int viaEquivalence = runByEquivalence(equivalentWork); return viaOpcodes == expected && viaEquivalence == expected; } < A model advertises that running by both mechanisms is part of its basis. > < Always true for an SLCPURuntime-derived model: both the opcode loop and the > < equivalence pipeline are inherited here. Subclasses do not re-implement it; > < they inherit the capability by extending this runtime. > boolean runsByBoth() { return true; } }