SILICON
Loading...
Searching...
No Matches
simulator.hpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#pragma once
19#include <boost/dynamic_bitset.hpp>
20#include <core/circuit.hpp>
21#include <core/component.hpp>
22#include <core/siliconFst.hpp>
24#include <cstdint>
25#include <functional>
26#include <memory>
27#include <queue>
28#include <span>
29#include <stdexcept>
30#include <string>
31#include <string_view>
32#include <unordered_map>
33#include <utility>
34#include <vector>
35
36namespace SILICON::simulation {
37
38using namespace SILICON::core;
39using namespace SILICON::waveform;
40using namespace SILICON::waveform::fst;
41
45struct TimedEvent {
47 uint64_t time;
48
51
54
57
59 bool operator>(const TimedEvent& other) const { return time > other.time; }
60};
61
74class Simulator {
75public:
77 using TraceSink = std::function<void(uint64_t, const std::vector<BusValue>&)>;
78
84
89 using CancellationCheck = std::function<bool()>;
90
97
105
113 [[nodiscard]] static EdgeType edgeType(const Context& context, const Wire_ptr& wire);
114
124 explicit Simulator(std::shared_ptr<const Circuit> c, uint64_t initialSimulationTime = 0,
125 std::unique_ptr<CircuitWriter> fstWriter = nullptr,
126 CancellationCheck isCancelled = {});
138 RunResult run(uint64_t duration, CancellationCheck isCancelled = {});
139
151 RunResult runUntilIdle(CancellationCheck isCancelled = {});
152
165 RunResult simulateWaveform(uint64_t duration, std::span<const Sample> inputSnapshots,
166 std::span<const WaveformInputDriver> inputDrivers,
167 CancellationCheck isCancelled = {});
168
175 void enableFstTracing(std::string_view fileName, CircuitWriter::Options options = {});
176
182 void setFstWriter(std::unique_ptr<CircuitWriter> writer);
183
190 void setTraceBuses(std::vector<CircuitWriter::NamedBus> buses);
191 void setTraceSink(TraceSink sink);
192
205 RunResult setBus(Bus bus, BusValue value, CancellationCheck isCancelled = {});
206
221 RunResult setBus(Bus bus, BusValue value, const Component_weakPtr& source,
222 CancellationCheck isCancelled = {});
223
234 RunResult simulateBus(const Bus& bus, CancellationCheck isCancelled = {});
235
244 void updateWire(const Wire_ptr& target, State newState, uint64_t delay,
245 const Component_weakPtr& source);
246
258 void updateBus(const Bus& bus, const BusValue& value, uint64_t delay,
259 const Component_weakPtr& source);
260
265 [[nodiscard]] uint64_t getCurrentTime() const { return currentTime; }
266
267 static void setMaxSimulationSteps(uint64_t value);
268 static void setMaxTransitionsPerDeltaCycle(int value);
269
270 [[nodiscard]] static uint64_t getMaxSimulationSteps();
271 [[nodiscard]] static int getMaxTransitionsPerDeltaCycle();
272
273private:
274 using ExecutionStepSet = boost::dynamic_bitset<>;
275
276 using PendingTransitionKey = std::pair<uint64_t, std::uintptr_t>;
277
279 [[nodiscard]] std::size_t operator()(const PendingTransitionKey& key) const noexcept;
280 };
281
283 uint64_t time = 0;
285 };
286
292
293 using StagedTransitions = std::unordered_map<PendingTransitionKey,
296
304
306 // Compiled output-wire slots are reused; only dirty slots are visited at commit.
307 std::vector<Wire_ptr> wires;
308 std::unordered_map<uint64_t, std::size_t> indices;
309 std::vector<StagedCyclicWire> writes;
310 std::vector<std::size_t> dirtyWires;
311 };
312
314 ExecutionStep(bool cyclic, std::vector<Component_ptr> orderedComponents)
315 : isCyclic(cyclic), components(std::move(orderedComponents))
316 {
317 if (isCyclic)
318 cyclicStaging = std::make_unique<CyclicStaging>();
319 }
320
321 bool isCyclic = false;
322 std::vector<Component_ptr> components;
323 std::unique_ptr<CyclicStaging> cyclicStaging;
324 };
325
327
329 std::shared_ptr<const Circuit> circuit;
330
333
335 std::vector<ExecutionStep> executionPlan;
336
338 std::unordered_map<uint64_t, ExecutionStepSet> forwardExecutionStepsByWire;
339
341 std::priority_queue<TimedEvent, std::vector<TimedEvent>, std::greater<>> eventQueue;
342
344 std::unordered_map<PendingTransitionKey, PendingTransition, PendingTransitionKeyHash>
346
349
352
354 uint64_t currentTime = 0;
355
357 std::unique_ptr<CircuitWriter> fstWriter;
358
360 std::vector<CircuitWriter::NamedBus> traceBuses;
361
364
366 std::unordered_map<uint64_t, State>* activePreviousWireStates = nullptr;
367
370
371 static uint64_t maxSimulationSteps;
373
377 void emitTraceSnapshot();
378
379 [[nodiscard]] static PendingTransitionKey
380 pendingTransitionKey(const Wire_ptr& target, const Component_weakPtr& source);
381
382 void scheduleDelayedWireUpdate(const Wire_ptr& target, State newState, uint64_t delay,
383 const Component_weakPtr& source);
384
385 [[nodiscard]] bool shouldStageSequentialOutput(const Component_weakPtr& source) const;
386
387 void stageSequentialWireUpdate(const Wire_ptr& target, State newState,
388 const Component_weakPtr& source);
389
390 void stageCyclicWireUpdate(const Wire_ptr& target, State newState,
391 const Component_weakPtr& source);
392
393 [[nodiscard]] bool commitStagedCyclicTransitions(CyclicStaging& staging);
395
396 [[nodiscard]] std::vector<Bus> commitStagedSequentialTransitions(
397 std::unordered_map<uint64_t, State>& previousWireStates);
398
399 [[nodiscard]] RunResult
400 evaluateForwardConeAndTrace(std::span<const Bus> changedBuses,
401 std::unordered_map<uint64_t, State> previousWireStates,
402 const CancellationCheck& isCancelled = {},
403 bool enableSequentialStaging = true);
404
405 [[nodiscard]] bool isDelayedEventPending(const TimedEvent& event) const;
406
407 [[nodiscard]] static std::vector<ExecutionStep>
408 compileExecutionPlan(std::span<const Circuit::SimulationBlock> blocks);
409
410 [[nodiscard]] bool evaluateExecutionStep(const ExecutionStep& step,
411 const Context& context,
412 const CancellationCheck& isCancelled = {});
413
414 [[nodiscard]] bool evaluateExecutionPlan(std::span<const ExecutionStep> steps,
415 const Context& context,
416 const CancellationCheck& isCancelled = {});
417
418 [[nodiscard]] bool evaluateExecutionSteps(const ExecutionStepSet& steps,
419 const Context& context,
420 const CancellationCheck& isCancelled = {});
421
422 [[nodiscard]] ExecutionStepSet
423 getForwardExecutionSteps(std::span<const Bus> changedBuses) const;
424
425 [[nodiscard]] RunResult
426 applyWaveformInputSample(std::span<const BusValue> values,
427 std::span<const WaveformInputDriver> inputDrivers,
428 const CancellationCheck& isCancelled);
429
430 [[nodiscard]] RunResult processNextEventBatch(const CancellationCheck& isCancelled);
431
435 [[nodiscard]] RunResult
436 evaluateExecutionPlanAndTrace(std::span<const ExecutionStep> steps,
437 const Context& context,
438 const CancellationCheck& isCancelled = {});
439};
440
441} // namespace SILICON::simulation
std::pair< uint64_t, std::uintptr_t > PendingTransitionKey
std::vector< ExecutionStep > executionPlan
Compiled component/SCC execution plan in topological order.
StagedTransitions stagedSequentialTransitions
Zero-delay sequential writes waiting for the active pass to finish.
std::unordered_map< uint64_t, ExecutionStepSet > forwardExecutionStepsByWire
Cached downstream execution-step membership for each input wire ID.
bool shouldStageSequentialOutput(const Component_weakPtr &source) const
RunResult processNextEventBatch(const CancellationCheck &isCancelled)
boost::dynamic_bitset<> ExecutionStepSet
void emitTraceSnapshot()
Emits a waveform snapshot when tracing is enabled.
std::priority_queue< TimedEvent, std::vector< TimedEvent >, std::greater<> > eventQueue
Priority queue of timed events sorted by time.
static uint64_t getMaxSimulationSteps()
void setFstWriter(std::unique_ptr< CircuitWriter > writer)
Installs a caller-created FST writer.
static EdgeType edgeType(const Context &context, const Wire_ptr &wire)
Classifies one wire's transition in a simulation context.
bool commitStagedCyclicTransitions(CyclicStaging &staging)
void discardStagedCyclicTransitions(CyclicStaging &staging)
EdgeType
Logical edge observed for one wire during a reactive evaluation.
Definition simulator.hpp:99
RunResult evaluateForwardConeAndTrace(std::span< const Bus > changedBuses, std::unordered_map< uint64_t, State > previousWireStates, const CancellationCheck &isCancelled={}, bool enableSequentialStaging=true)
static std::vector< ExecutionStep > compileExecutionPlan(std::span< const Circuit::SimulationBlock > blocks)
std::unordered_map< uint64_t, State > * activePreviousWireStates
Previous-state index being populated during the active reactive pass.
uint64_t getCurrentTime() const
Gets the current simulation time.
void scheduleDelayedWireUpdate(const Wire_ptr &target, State newState, uint64_t delay, const Component_weakPtr &source)
void stageCyclicWireUpdate(const Wire_ptr &target, State newState, const Component_weakPtr &source)
RunResult applyWaveformInputSample(std::span< const BusValue > values, std::span< const WaveformInputDriver > inputDrivers, const CancellationCheck &isCancelled)
RunResult evaluateExecutionPlanAndTrace(std::span< const ExecutionStep > steps, const Context &context, const CancellationCheck &isCancelled={})
Evaluates a plan and emits a trace snapshot on success.
std::unordered_map< PendingTransitionKey, PendingTransition, PendingTransitionKeyHash > pendingTransitions
Latest valid delayed transition for each component-output wire.
RunResult setBus(Bus bus, BusValue value, CancellationCheck isCancelled={})
Forces a bus to a specific value and propagates the change through the circuit.
std::vector< Bus > commitStagedSequentialTransitions(std::unordered_map< uint64_t, State > &previousWireStates)
RunResult run(uint64_t duration, CancellationCheck isCancelled={})
Executes the simulation for a specified duration.
Simulator(std::shared_ptr< const Circuit > c, uint64_t initialSimulationTime=0, std::unique_ptr< CircuitWriter > fstWriter=nullptr, CancellationCheck isCancelled={})
Constructs a Simulator for the given circuit.
TraceSink traceSink
Optional callback for live waveform viewers.
void stageSequentialWireUpdate(const Wire_ptr &target, State newState, const Component_weakPtr &source)
RunResult runUntilIdle(CancellationCheck isCancelled={})
Runs pending timed events until no further propagation is scheduled.
std::function< bool()> CancellationCheck
Framework-independent cooperative cancellation callback.
Definition simulator.hpp:89
static void setMaxSimulationSteps(uint64_t value)
RunResult simulateBus(const Bus &bus, CancellationCheck isCancelled={})
Propagates changes from a bus through the circuit in reverse direction.
static void setMaxTransitionsPerDeltaCycle(int value)
void enableFstTracing(std::string_view fileName, CircuitWriter::Options options={})
Enables FST tracing for this simulator.
std::unique_ptr< CircuitWriter > fstWriter
Optional waveform writer for simulation tracing.
std::unordered_map< PendingTransitionKey, StagedWireTransition, PendingTransitionKeyHash > StagedTransitions
void setTraceBuses(std::vector< CircuitWriter::NamedBus > buses)
Configures bus-level waveform snapshots emitted by the simulator.
bool evaluateExecutionSteps(const ExecutionStepSet &steps, const Context &context, const CancellationCheck &isCancelled={})
std::vector< CircuitWriter::NamedBus > traceBuses
Bus list observed by waveform tracing.
ExecutionStepSet getForwardExecutionSteps(std::span< const Bus > changedBuses) const
RunResult simulateWaveform(uint64_t duration, std::span< const Sample > inputSnapshots, std::span< const WaveformInputDriver > inputDrivers, CancellationCheck isCancelled={})
Drives input buses from a sampled internal waveform and runs to duration.
CyclicStaging * activeCyclicStaging
Active SCC's reusable staging buffer; null outside a cyclic step.
void setTraceSink(TraceSink sink)
bool evaluateExecutionPlan(std::span< const ExecutionStep > steps, const Context &context, const CancellationCheck &isCancelled={})
void updateBus(const Bus &bus, const BusValue &value, uint64_t delay, const Component_weakPtr &source)
Updates a bus to a new value through the normal wire-update path.
static uint64_t maxSimulationSteps
std::function< void(uint64_t, const std::vector< BusValue > &)> TraceSink
Receives encoded waveform values for a simulation timestamp.
Definition simulator.hpp:77
bool isDelayedEventPending(const TimedEvent &event) const
void initializeExecutionPlan()
Builds execution and reachability caches once, during construction.
bool stageSequentialOutputs
True while reactive evaluation should stage opted-in zero-delay writes.
static int getMaxTransitionsPerDeltaCycle()
RunResult
Outcome of a cancellable simulator operation.
Definition simulator.hpp:92
uint64_t currentTime
Current simulation time.
std::shared_ptr< const Circuit > circuit
The circuit being simulated.
static PendingTransitionKey pendingTransitionKey(const Wire_ptr &target, const Component_weakPtr &source)
void updateWire(const Wire_ptr &target, State newState, uint64_t delay, const Component_weakPtr &source)
Updates a wire with a new state and optional delay.
bool evaluateExecutionStep(const ExecutionStep &step, const Context &context, const CancellationCheck &isCancelled={})
TraceWriter::Options Options
FST file metadata and hierarchy options shared with TraceWriter.
std::shared_ptr< Wire > Wire_ptr
Definition wire.hpp:116
std::weak_ptr< Component > Component_weakPtr
Definition wire.hpp:52
std::vector< State > BusValue
Definition wire.hpp:120
Context describing why a component is being evaluated.
Definition component.hpp:90
std::vector< StagedCyclicWire > writes
std::unordered_map< uint64_t, std::size_t > indices
std::unique_ptr< CyclicStaging > cyclicStaging
ExecutionStep(bool cyclic, std::vector< Component_ptr > orderedComponents)
std::vector< Component_ptr > components
std::size_t operator()(const PendingTransitionKey &key) const noexcept
Definition simulator.cpp:80
Bus driven by one column of an input waveform.
Definition simulator.hpp:80
Represents a timed event in the simulation.
Definition simulator.hpp:45
Component_weakPtr source
The component that is the source of this state change.
Definition simulator.hpp:56
uint64_t time
Simulation time at which the event occurs.
Definition simulator.hpp:47
bool operator>(const TimedEvent &other) const
Comparison operator for priority queue ordering.
Definition simulator.hpp:59
State newState
The new state to set on the wire.
Definition simulator.hpp:53
Wire_ptr targetWire
The wire to update.
Definition simulator.hpp:50