24#include <boost/scope/scope_exit.hpp>
36using namespace SILICON::core;
37using namespace SILICON::waveform;
38using namespace SILICON::waveform::fst;
41 const SILICON::logging::Logger simulationLog(
"simulation");
43 struct StepVectorHash {
44 [[nodiscard]] std::size_t
45 operator()(
const std::vector<std::size_t>& values)
const noexcept
47 std::size_t seed = values.size();
48 for (
const auto value : values) {
49 seed ^= std::hash<std::size_t>{}(
value) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
58 return isCancelled && isCancelled();
61 void capturePreviousWireState(std::unordered_map<uint64_t, State>& previousWireStates,
65 previousWireStates.emplace(wire->getId(), wire->getCurrentState());
68 void capturePreviousBusStates(std::unordered_map<uint64_t, State>& previousWireStates,
71 for (
const auto& wire : bus)
72 capturePreviousWireState(previousWireStates, wire);
83 auto seed = std::hash<uint64_t>{}(key.first);
85 std::hash<std::uintptr_t>{}(key.second) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
116 simulator.stageSequentialOutputs = enabled;
128 if (!previousState || !wire)
131 const State currentState = wire->getCurrentState();
132 if (*previousState == currentState)
145 std::unique_ptr<CircuitWriter>
fstWriter,
150 throw std::invalid_argument(
"Simulator requires a valid Circuit pointer");
155 const Context initialContext{
true, {}};
160 if (initialSimulationTime != 0)
161 static_cast<void>(
run(initialSimulationTime, std::move(isCancelled)));
166 auto compiledBlocks =
circuit->splitCyclic();
169 std::unordered_map<const Component*, std::size_t> componentToStep;
170 for (
const auto& [stepIndex, executionStep] :
172 for (
const auto& comp : executionStep.components)
173 componentToStep[comp.get()] = stepIndex;
176 std::vector<std::vector<std::size_t>> stepGraph(
executionPlan.size());
177 const auto& graph =
circuit->getGraph();
179 for (
const auto edge : boost::make_iterator_range(boost::edges(graph))) {
180 const auto sourceComp = graph[boost::source(edge, graph)].component;
181 const auto targetComp = graph[boost::target(edge, graph)].component;
182 if (!sourceComp || !targetComp)
185 const auto sourceIt = componentToStep.find(sourceComp.get());
186 const auto targetIt = componentToStep.find(targetComp.get());
187 if (sourceIt == componentToStep.end() || targetIt == componentToStep.end()
188 || sourceIt->second == targetIt->second)
191 auto& successors = stepGraph[sourceIt->second];
192 if (!std::ranges::contains(successors, targetIt->second))
193 successors.push_back(targetIt->second);
198 std::unordered_map<uint64_t, std::vector<std::size_t>> seedStepsByWire;
199 for (
const auto vertex : boost::make_iterator_range(boost::vertices(graph))) {
200 const auto comp = graph[vertex].component;
204 const auto stepIt = componentToStep.find(comp.get());
205 if (stepIt == componentToStep.end())
209 comp->inputBuses() | std::views::join
210 | std::views::filter([](
const auto& wire) {
return static_cast<bool>(wire); });
212 for (
const auto& wire : inputWires) {
213 auto& seeds = seedStepsByWire[wire->getId()];
214 if (!std::ranges::contains(seeds, stepIt->second))
215 seeds.push_back(stepIt->second);
219 std::unordered_map<std::vector<std::size_t>,
ExecutionStepSet, StepVectorHash>
220 affectedStepsBySeedSet;
221 affectedStepsBySeedSet.reserve(seedStepsByWire.size());
222 for (
auto& [wireId, seedSteps] : seedStepsByWire) {
223 std::ranges::sort(seedSteps);
225 const auto cachedAffectedSteps = affectedStepsBySeedSet.find(seedSteps);
226 if (cachedAffectedSteps != affectedStepsBySeedSet.end()) {
233 for (
const auto stepIndex : seedSteps) {
234 if (stepIndex >= frontier.size())
235 throw std::logic_error(
236 "Execution-plan seed index exceeds the compiled plan size");
237 frontier.set(stepIndex);
239 while (frontier.any()) {
240 affectedSteps |= frontier;
243 for (
auto stepIndex = frontier.find_first(); stepIndex != ExecutionStepSet::npos;
244 stepIndex = frontier.find_next(stepIndex)) {
245 if (stepIndex >= stepGraph.size())
246 throw std::logic_error(
247 "Forward-cone index exceeds the compiled step graph size");
248 for (
const auto successor : stepGraph[stepIndex]) {
249 if (successor >= successors.size())
250 throw std::logic_error(
251 "Forward-cone successor exceeds the compiled plan size");
252 successors.set(successor);
256 successors &= ~affectedSteps;
257 frontier = std::move(successors);
260 auto [insertedAffectedSteps, _inserted] =
261 affectedStepsBySeedSet.emplace(seedSteps, std::move(affectedSteps));
265 simulationLog.debug(std::format(
"Compiled {} simulation steps",
executionPlan.size()));
273 std::make_unique<CircuitWriter>(fileName,
traceBuses, std::move(options)));
307 std::vector<BusValue> values;
310 values.push_back(bus.getCurrentValue());
318 const auto sourceAddress =
reinterpret_cast<std::uintptr_t
>(source.lock().get());
319 return {target ? target->getId() : 0, sourceAddress};
323 const uint64_t delay,
328 if (target->getCurrentState() == newState) {
336 && pending->second.time == eventTime)
340 eventQueue.push({eventTime, target, newState, source});
345 const auto sourceComponent = source.lock();
347 && sourceComponent->usesStagedSequentialOutputs();
356 if (target->getCurrentState() == newState) {
371 auto it = staging.indices.find(target->getId());
372 if (it == staging.indices.end()) {
375 const auto index = staging.wires.size();
376 staging.wires.push_back(target);
377 staging.writes.emplace_back();
378 it = staging.indices.emplace(target->getId(), index).first;
382 auto& staged = staging.writes[it->second];
383 if (!staged.written) {
384 staged.written =
true;
385 staged.source = source;
386 staged.state = newState;
387 staging.dirtyWires.push_back(it->second);
391 if (staged.source.lock() == source.lock()) {
393 staged.state = newState;
399 if (!staged.conflict) {
400 staged.conflictingSource = source;
401 staged.conflict =
true;
404 const auto before = std::less<const Component*>{};
405 if (before(source.lock().get(), staged.source.lock().get())) {
406 staged.conflictingSource = staged.source;
407 staged.source = source;
411 if (before(source.lock().get(), staged.conflictingSource.lock().get()))
412 staged.conflictingSource = source;
418 auto& staged = staging.
writes[index];
419 staged.source.reset();
420 staged.conflictingSource.reset();
421 staged.written =
false;
422 staged.conflict =
false;
429 bool changed =
false;
431 const auto& target = staging.
wires[index];
432 auto& staged = staging.
writes[index];
434 const auto previous = target->getCurrentState();
436 if (!staged.conflict) {
437 if (previous != staged.state) {
440 target->setCurrentState(staged.state, staged.source);
449 target->setCurrentState(
State::ERROR, staged.conflictingSource);
452 changed |= target->getCurrentState() != previous;
459 std::unordered_map<uint64_t, State>& previousWireStates)
461 std::vector<Bus> changedBuses;
466 for (
const auto& [_key, transition] : transitions) {
467 if (!transition.target || transition.target->getCurrentState() == transition.state)
470 capturePreviousWireState(previousWireStates, transition.target);
471 transition.target->setCurrentState(transition.state, transition.source);
472 changedBuses.push_back(
Bus{transition.target});
486 && it->second.state ==
event.newState;
489std::vector<Simulator::ExecutionStep>
492 std::vector<ExecutionStep> plan;
494 for (
const auto& block : blocks) {
495 if (!block.isCyclic) {
496 for (
const auto& weakComp : block.executionOrder) {
497 if (
auto comp = weakComp.lock())
498 plan.emplace_back(
false, std::vector<Component_ptr>{std::move(comp)});
503 std::vector<Component_ptr> cyclicComps;
504 const auto& blockGraph = block.circuit.getGraph();
505 auto [viBegin, viEnd] = boost::vertices(blockGraph);
506 for (
const auto vertex : std::ranges::subrange(viBegin, viEnd)) {
507 if (
auto comp = blockGraph[vertex].component)
508 cyclicComps.push_back(comp);
511 if (!cyclicComps.empty()) {
517 | std::views::transform([](
const auto& comp) ->
const std::vector<Bus>& {
518 return comp->outputBuses();
520 | std::views::join | std::views::join
521 | std::views::filter([](
const auto& wire) {
return static_cast<bool>(wire); });
522 for (
const auto& wire : outputWires) {
523 const auto index = staging.wires.size();
524 if (staging.indices.emplace(wire->getId(), index).second)
525 staging.wires.push_back(wire);
527 staging.writes.resize(staging.wires.size());
528 staging.dirtyWires.reserve(staging.wires.size());
529 plan.push_back(std::move(step));
539 if (cancellationRequested(isCancelled))
544 if (cancellationRequested(isCancelled))
547 comp->simulate(*
this, context);
555 boost::scope::scope_exit restoreStaging([&] {
561 if (cancellationRequested(isCancelled))
567 if (cancellationRequested(isCancelled))
569 comp->simulate(*
this, context);
576 const std::string errorMsg =
577 "Delta cycle limit exceeded! Unstable zero-delay loop detected.";
578 simulationLog.warning(errorMsg);
579 throw std::runtime_error(errorMsg);
586 for (
const auto& step : steps) {
598 throw std::logic_error(
599 "Execution-step set size does not match the compiled plan size");
601 for (
auto stepIndex = steps.find_first(); stepIndex != ExecutionStepSet::npos;
602 stepIndex = steps.find_next(stepIndex)) {
614 for (
const auto& bus : changedBuses) {
615 for (
const auto& wire : bus) {
624 throw std::logic_error(
625 "Cached forward-cone size does not match the compiled plan size");
656 if (target->getCurrentState() == newState)
662 target->setCurrentState(newState, source);
668 if (value.size() != bus.
size()) {
669 throw std::invalid_argument(
670 std::format(
"Trying to set size {} bus to size {} busValue", bus.
size(),
674 for (
auto i = 0uz; i < bus.
size(); ++i) {
692 std::span<const Bus> changedBuses,
693 std::unordered_map<uint64_t, State> previousWireStates,
696 Context context{
false, changedBuses, std::move(previousWireStates)};
699 enableSequentialStaging);
709 std::unordered_map<uint64_t, State> stagedPreviousWireStates;
710 const auto stagedChangedBuses =
711 enableSequentialStaging
713 : std::vector<Bus>{};
715 if (!stagedChangedBuses.empty()) {
717 Context{
false, stagedChangedBuses, std::move(stagedPreviousWireStates)};
735 simulationLog.info(std::format(
"Running simulation with a duration of {}", duration));
736 const uint64_t minimumEndTime =
currentTime + duration;
738 uint64_t processedSteps = 0;
741 simulationLog.warning(
"Simulation step limit exceeded before the event queue "
742 "stabilized. This might be an unstable circuit.");
757 simulationLog.info(
"Circuit state stabilized (simulation complete)");
763 simulationLog.info(
"Running simulation until pending events are idle");
765 uint64_t processedSteps = 0;
768 simulationLog.warning(
"Simulation step limit exceeded before the event queue "
769 "stabilized. This might be an unstable circuit.");
779 simulationLog.info(
"Circuit state stabilized (simulation complete)");
787 if (cancellationRequested(isCancelled))
791 std::vector<Bus> changedBuses;
792 std::unordered_map<uint64_t, State> previousWireStates;
801 capturePreviousWireState(previousWireStates, ev.targetWire);
804 if (ev.targetWire && ev.targetWire->getCurrentState() != ev.newState) {
805 ev.targetWire->setCurrentState(ev.newState, ev.source);
806 changedBuses.push_back(
Bus{ev.targetWire});
810 if (changedBuses.empty())
818 const uint64_t duration, std::span<const Sample> inputSnapshots,
819 std::span<const WaveformInputDriver> inputDrivers,
CancellationCheck isCancelled)
821 for (std::size_t sampleIndex = 0; sampleIndex < inputSnapshots.size();) {
822 const uint64_t sampleTime = inputSnapshots[sampleIndex].time;
829 std::vector<BusValue> values = inputSnapshots[sampleIndex].values;
831 while (sampleIndex < inputSnapshots.size()
832 && inputSnapshots[sampleIndex].time == sampleTime) {
833 const auto& sameTimeValues = inputSnapshots[sampleIndex].values;
834 if (values.size() < sameTimeValues.size())
835 values.resize(sameTimeValues.size());
836 for (std::size_t i = 0; i < sameTimeValues.size(); ++i)
837 values[i] = sameTimeValues[i];
853 std::span<const WaveformInputDriver> inputDrivers,
856 if (cancellationRequested(isCancelled))
859 bool inputsChanged =
false;
860 const auto inputCount = std::min(values.size(), inputDrivers.size());
861 std::vector<Bus> changedBuses;
862 std::unordered_map<uint64_t, State> previousWireStates;
863 for (std::size_t i = 0; i < inputCount; ++i) {
864 const auto& driver = inputDrivers[i];
865 auto bus = driver.bus;
868 if (bus.getCurrentValue() != normalized) {
869 inputsChanged =
true;
870 changedBuses.push_back(bus);
871 capturePreviousBusStates(previousWireStates, bus);
873 (void)bus.forceSetCurrentValue(normalized, driver.source);
906 return setBus(std::move(bus), value, {}, std::move(isCancelled));
913 if (cancellationRequested(isCancelled))
921 if (currentVal == value)
925 std::vector<Bus> changedBuses{bus};
926 std::unordered_map<uint64_t, State> previousWireStates;
927 capturePreviousBusStates(previousWireStates, bus);
941 const Context context{
true, {}};
bool forceSetCurrentValue(const BusValue &value)
bool isInErrorState() const
BusValue getCurrentValue() const
Represents a digital circuit as a directed graph of components.
std::vector< SimulationBlock > splitCyclic() const
Splits the circuit into simulation blocks separating cyclic from acyclic parts.
std::unordered_map< uint64_t, State > * previousActivePreviousWireStates
bool previousStageSequentialOutputs
EvaluationStateGuard(Simulator &simulator, std::unordered_map< uint64_t, State > *activePreviousWireStates, bool stageSequentialOutputs)
void setStageSequentialOutputs(bool enabled) const
void setActivePreviousWireStates(std::unordered_map< uint64_t, State > *activePreviousWireStates) const
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.
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.
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.
static int maxTransitionsPerDeltaCycle
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.
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.
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.
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.
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={})
std::shared_ptr< Wire > Wire_ptr
std::weak_ptr< Component > Component_weakPtr
std::vector< State > BusValue
QVariant value(const QSettings &settings, const Definition &setting)
Reads a setting value, falling back to its declared default when unset.
BusValue normalizeBusValue(const BusValue &value, const std::size_t width, const State extension)
Resize an LSB-first value to an exact bus width.
Context describing why a component is being evaluated.
std::unordered_map< uint64_t, core::State > previousWireStates
Wire states captured before the reactive mutation that caused this pass.
std::optional< core::State > previousState(const core::Wire_ptr &wire) const
Returns the state a wire had before this reactive evaluation, if captured.
std::vector< std::size_t > dirtyWires
std::vector< Wire_ptr > wires
std::vector< StagedCyclicWire > writes
std::unique_ptr< CyclicStaging > cyclicStaging
std::vector< Component_ptr > components
std::size_t operator()(const PendingTransitionKey &key) const noexcept
Represents a timed event in the simulation.
Component_weakPtr source
The component that is the source of this state change.
Wire_ptr targetWire
The wire to update.