SILICON
Loading...
Searching...
No Matches
simulator.cpp
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#include "simulator.hpp"
19
20#include <algorithm>
21#include <ranges>
22#include <utility>
23
24#include <boost/scope/scope_exit.hpp>
25
26#include <core/component.hpp>
27#include <core/wireUtils.hpp>
28
31
32#include <logging/logger.hpp>
33
34namespace SILICON::simulation {
35
36using namespace SILICON::core;
37using namespace SILICON::waveform;
38using namespace SILICON::waveform::fst;
39
40namespace {
41 const SILICON::logging::Logger simulationLog("simulation");
42
43 struct StepVectorHash {
44 [[nodiscard]] std::size_t
45 operator()(const std::vector<std::size_t>& values) const noexcept
46 {
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);
50 }
51 return seed;
52 }
53 };
54
55 bool cancellationRequested(const Simulator::CancellationCheck& isCancelled)
56 {
57 // An empty callback keeps existing synchronous callers on the zero-overhead path.
58 return isCancelled && isCancelled();
59 }
60
61 void capturePreviousWireState(std::unordered_map<uint64_t, State>& previousWireStates,
62 const Wire_ptr& wire)
63 {
64 if (wire)
65 previousWireStates.emplace(wire->getId(), wire->getCurrentState());
66 }
67
68 void capturePreviousBusStates(std::unordered_map<uint64_t, State>& previousWireStates,
69 const Bus& bus)
70 {
71 for (const auto& wire : bus)
72 capturePreviousWireState(previousWireStates, wire);
73 }
74
75} // namespace
76
77uint64_t Simulator::maxSimulationSteps = 100000;
79
81 const PendingTransitionKey& key) const noexcept
82{
83 auto seed = std::hash<uint64_t>{}(key.first);
84 seed ^=
85 std::hash<std::uintptr_t>{}(key.second) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
86 return seed;
87}
88
90public:
101
103 {
104 simulator.activePreviousWireStates = previousActivePreviousWireStates;
105 simulator.stageSequentialOutputs = previousStageSequentialOutputs;
106 }
107
109 std::unordered_map<uint64_t, State>* activePreviousWireStates) const
110 {
111 simulator.activePreviousWireStates = activePreviousWireStates;
112 }
113
114 void setStageSequentialOutputs(bool enabled) const
115 {
116 simulator.stageSequentialOutputs = enabled;
117 }
118
119private:
121 std::unordered_map<uint64_t, State>* previousActivePreviousWireStates = nullptr;
123};
124
126{
127 const auto previousState = context.previousState(wire);
128 if (!previousState || !wire)
129 return EdgeType::NO_CHANGE;
130
131 const State currentState = wire->getCurrentState();
132 if (*previousState == currentState)
133 return EdgeType::NO_CHANGE;
134
135 if (*previousState == State::LOW && currentState == State::HIGH)
136 return EdgeType::RISE;
137
138 if (*previousState == State::HIGH && currentState == State::LOW)
139 return EdgeType::FALL;
140
141 return EdgeType::UNKNOWN;
142}
143
144Simulator::Simulator(std::shared_ptr<const Circuit> c, uint64_t initialSimulationTime,
145 std::unique_ptr<CircuitWriter> fstWriter,
146 CancellationCheck isCancelled)
147 : circuit(std::move(c)), fstWriter(std::move(fstWriter))
148{
149 if (!circuit)
150 throw std::invalid_argument("Simulator requires a valid Circuit pointer");
151
153
154 // Initial evaluation participates in the same cancellation contract as later runs.
155 const Context initialContext{true, {}};
156 if (!evaluateExecutionPlan(executionPlan, initialContext, isCancelled))
157 return;
159
160 if (initialSimulationTime != 0)
161 static_cast<void>(run(initialSimulationTime, std::move(isCancelled)));
162}
163
165{
166 auto compiledBlocks = circuit->splitCyclic();
167 executionPlan = compileExecutionPlan(compiledBlocks);
168
169 std::unordered_map<const Component*, std::size_t> componentToStep;
170 for (const auto& [stepIndex, executionStep] :
171 executionPlan | SILICON::views::enumerate) {
172 for (const auto& comp : executionStep.components)
173 componentToStep[comp.get()] = stepIndex;
174 }
175
176 std::vector<std::vector<std::size_t>> stepGraph(executionPlan.size());
177 const auto& graph = circuit->getGraph();
178
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)
183 continue;
184
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)
189 continue;
190
191 auto& successors = stepGraph[sourceIt->second];
192 if (!std::ranges::contains(successors, targetIt->second))
193 successors.push_back(targetIt->second);
194 }
195
196 // Direct listeners are normally a sparse subset of the plan, so retain a compact
197 // vector here. The transitive cones below are dense enough to benefit from bitsets.
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;
201 if (!comp)
202 continue;
203
204 const auto stepIt = componentToStep.find(comp.get());
205 if (stepIt == componentToStep.end())
206 continue;
207
208 auto inputWires =
209 comp->inputBuses() | std::views::join
210 | std::views::filter([](const auto& wire) { return static_cast<bool>(wire); });
211
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);
216 }
217 }
218
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);
224
225 const auto cachedAffectedSteps = affectedStepsBySeedSet.find(seedSteps);
226 if (cachedAffectedSteps != affectedStepsBySeedSet.end()) {
227 forwardExecutionStepsByWire.emplace(wireId, cachedAffectedSteps->second);
228 continue;
229 }
230
231 ExecutionStepSet affectedSteps(executionPlan.size());
232 ExecutionStepSet frontier(executionPlan.size());
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);
238 }
239 while (frontier.any()) {
240 affectedSteps |= frontier;
241
242 ExecutionStepSet successors(executionPlan.size());
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);
253 }
254 }
255
256 successors &= ~affectedSteps;
257 frontier = std::move(successors);
258 }
259
260 auto [insertedAffectedSteps, _inserted] =
261 affectedStepsBySeedSet.emplace(seedSteps, std::move(affectedSteps));
262 forwardExecutionStepsByWire.emplace(wireId, insertedAffectedSteps->second);
263 }
264
265 simulationLog.debug(std::format("Compiled {} simulation steps", executionPlan.size()));
266}
267
268void Simulator::enableFstTracing(std::string_view fileName,
270{
271 if (!traceBuses.empty()) {
273 std::make_unique<CircuitWriter>(fileName, traceBuses, std::move(options)));
274 } else {
275 setFstWriter(std::make_unique<CircuitWriter>(fileName, *circuit, std::move(options)));
276 }
277}
278
279void Simulator::setFstWriter(std::unique_ptr<CircuitWriter> writer)
280{
281 fstWriter = std::move(writer);
283}
284
285void Simulator::setTraceBuses(std::vector<CircuitWriter::NamedBus> buses)
286{
287 traceBuses = std::move(buses);
289}
290
292{
293 traceSink = std::move(sink);
295}
296
298{
299 if (fstWriter) {
300 fstWriter->emitSnapshot(currentTime);
301 fstWriter->flush();
302 }
303
304 if (!traceSink || traceBuses.empty())
305 return;
306
307 std::vector<BusValue> values;
308 values.reserve(traceBuses.size());
309 for (const auto& [name, bus] : traceBuses)
310 values.push_back(bus.getCurrentValue());
311
312 traceSink(currentTime, values);
313}
314
317{
318 const auto sourceAddress = reinterpret_cast<std::uintptr_t>(source.lock().get());
319 return {target ? target->getId() : 0, sourceAddress};
320}
321
322void Simulator::scheduleDelayedWireUpdate(const Wire_ptr& target, const State newState,
323 const uint64_t delay,
324 const Component_weakPtr& source)
325{
326 const auto key = pendingTransitionKey(target, source);
327
328 if (target->getCurrentState() == newState) {
329 pendingTransitions.erase(key);
330 return;
331 }
332
333 const uint64_t eventTime = currentTime + delay;
334 const auto pending = pendingTransitions.find(key);
335 if (pending != pendingTransitions.end() && pending->second.state == newState
336 && pending->second.time == eventTime)
337 return;
338
339 pendingTransitions[key] = {eventTime, newState};
340 eventQueue.push({eventTime, target, newState, source});
341}
342
344{
345 const auto sourceComponent = source.lock();
346 return stageSequentialOutputs && sourceComponent
347 && sourceComponent->usesStagedSequentialOutputs();
348}
349
350void Simulator::stageSequentialWireUpdate(const Wire_ptr& target, const State newState,
351 const Component_weakPtr& source)
352{
353 const auto key = pendingTransitionKey(target, source);
354 pendingTransitions.erase(key);
355
356 if (target->getCurrentState() == newState) {
358 return;
359 }
360
361 stagedSequentialTransitions[key] = {target, newState, source};
362}
363
364void Simulator::stageCyclicWireUpdate(const Wire_ptr& target, const State newState,
365 const Component_weakPtr& source)
366{
367 if (!pendingTransitions.empty())
368 pendingTransitions.erase(pendingTransitionKey(target, source));
369
370 auto& staging = *activeCyclicStaging;
371 auto it = staging.indices.find(target->getId());
372 if (it == staging.indices.end()) {
373 // Components normally write their declared outputs. Preserve staging for an
374 // undeclared target as well, extending this step's reusable buffer once.
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;
379 }
380
381 // Even a write equal to s_k remains marked, so another source cannot hide it.
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);
388 return;
389 }
390
391 if (staged.source.lock() == source.lock()) {
392 // Repeated writes by one source retain its last value, as the keyed map did.
393 staged.state = newState;
394 return;
395 }
396
397 // Keep the two lowest source addresses so even three or more drivers give
398 // an unowned wire the same owner regardless of evaluation order.
399 if (!staged.conflict) {
400 staged.conflictingSource = source;
401 staged.conflict = true;
402 }
403
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;
408 return;
409 }
410
411 if (before(source.lock().get(), staged.conflictingSource.lock().get()))
412 staged.conflictingSource = source;
413}
414
416{
417 for (const auto index : staging.dirtyWires) {
418 auto& staged = staging.writes[index];
419 staged.source.reset();
420 staged.conflictingSource.reset();
421 staged.written = false;
422 staged.conflict = false;
423 }
424 staging.dirtyWires.clear();
425}
426
428{
429 bool changed = false;
430 for (const auto index : staging.dirtyWires) {
431 const auto& target = staging.wires[index];
432 auto& staged = staging.writes[index];
433 // All writes were staged, so this is still the wire's state at cycle start.
434 const auto previous = target->getCurrentState();
435
436 if (!staged.conflict) {
437 if (previous != staged.state) {
439 capturePreviousWireState(*activePreviousWireStates, target);
440 target->setCurrentState(staged.state, staged.source);
441 }
442 } else {
443 // Distinct sources claimed the same output in this delta-cycle. Both writes
444 // pass through Wire's ownership check. A fixed source order also makes the
445 // initial owner independent of the SCC's component evaluation order.
447 capturePreviousWireState(*activePreviousWireStates, target);
448 target->setCurrentState(State::ERROR, staged.source);
449 target->setCurrentState(State::ERROR, staged.conflictingSource);
450 }
451
452 changed |= target->getCurrentState() != previous;
453 }
455 return changed;
456}
457
459 std::unordered_map<uint64_t, State>& previousWireStates)
460{
461 std::vector<Bus> changedBuses;
462
463 auto transitions = std::move(stagedSequentialTransitions);
465
466 for (const auto& [_key, transition] : transitions) {
467 if (!transition.target || transition.target->getCurrentState() == transition.state)
468 continue;
469
470 capturePreviousWireState(previousWireStates, transition.target);
471 transition.target->setCurrentState(transition.state, transition.source);
472 changedBuses.push_back(Bus{transition.target});
473 }
474
475 return changedBuses;
476}
477
479{
480 if (!event.targetWire)
481 return false;
482
483 const auto key = pendingTransitionKey(event.targetWire, event.source);
484 const auto it = pendingTransitions.find(key);
485 return it != pendingTransitions.end() && it->second.time == event.time
486 && it->second.state == event.newState;
487}
488
489std::vector<Simulator::ExecutionStep>
490Simulator::compileExecutionPlan(std::span<const Circuit::SimulationBlock> blocks)
491{
492 std::vector<ExecutionStep> plan;
493
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)});
499 }
500 continue;
501 }
502
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);
509 }
510
511 if (!cyclicComps.empty()) {
512 ExecutionStep step(true, std::move(cyclicComps));
513 auto& staging = *step.cyclicStaging;
514
515 auto outputWires =
516 step.components
517 | std::views::transform([](const auto& comp) -> const std::vector<Bus>& {
518 return comp->outputBuses();
519 })
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);
526 }
527 staging.writes.resize(staging.wires.size());
528 staging.dirtyWires.reserve(staging.wires.size());
529 plan.push_back(std::move(step));
530 }
531 }
532
533 return plan;
534}
535
537 const CancellationCheck& isCancelled)
538{
539 if (cancellationRequested(isCancelled))
540 return false;
541
542 if (!step.isCyclic) {
543 for (const auto& comp : step.components) {
544 if (cancellationRequested(isCancelled))
545 return false;
546
547 comp->simulate(*this, context);
548 }
549 return true;
550 }
551
552 auto& staging = *step.cyclicStaging;
553 auto* const previousCyclicStaging = activeCyclicStaging;
554 activeCyclicStaging = &staging;
555 boost::scope::scope_exit restoreStaging([&] {
557 activeCyclicStaging = previousCyclicStaging;
558 });
559
560 for (int i = 0; i < maxTransitionsPerDeltaCycle; ++i) {
561 if (cancellationRequested(isCancelled))
562 return false;
563
564 // No wire changes during evaluation, so every component reads the same s_k.
565 // Applying the collected writes afterward produces s_(k+1) in one commit.
566 for (const auto& comp : step.components) {
567 if (cancellationRequested(isCancelled))
568 return false;
569 comp->simulate(*this, context);
570 }
571
572 if (!commitStagedCyclicTransitions(staging))
573 return true;
574 }
575
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);
580}
581
582bool Simulator::evaluateExecutionPlan(std::span<const ExecutionStep> steps,
583 const Context& context,
584 const CancellationCheck& isCancelled)
585{
586 for (const auto& step : steps) {
587 if (!evaluateExecutionStep(step, context, isCancelled))
588 return false;
589 }
590 return true;
591}
592
594 const Context& context,
595 const CancellationCheck& isCancelled)
596{
597 if (steps.size() != executionPlan.size())
598 throw std::logic_error(
599 "Execution-step set size does not match the compiled plan size");
600
601 for (auto stepIndex = steps.find_first(); stepIndex != ExecutionStepSet::npos;
602 stepIndex = steps.find_next(stepIndex)) {
603 if (!evaluateExecutionStep(executionPlan[stepIndex], context, isCancelled))
604 return false;
605 }
606 return true;
607}
608
610Simulator::getForwardExecutionSteps(std::span<const Bus> changedBuses) const
611{
612 ExecutionStepSet steps(executionPlan.size());
613
614 for (const auto& bus : changedBuses) {
615 for (const auto& wire : bus) {
616 if (!wire)
617 continue;
618
619 const auto it = forwardExecutionStepsByWire.find(wire->getId());
620 if (it == forwardExecutionStepsByWire.end())
621 continue;
622
623 if (it->second.size() != executionPlan.size())
624 throw std::logic_error(
625 "Cached forward-cone size does not match the compiled plan size");
626 steps |= it->second;
627 }
628 }
629
630 return steps;
631}
632
633void Simulator::updateWire(const Wire_ptr& target, const State newState,
634 const uint64_t delay, const Component_weakPtr& source)
635{
636 if (!target)
637 return;
638
639 if (delay != 0) {
640 scheduleDelayedWireUpdate(target, newState, delay, source);
641 return;
642 }
643
644 if (shouldStageSequentialOutput(source)) {
645 stageSequentialWireUpdate(target, newState, source);
646 return;
647 }
648
650 stageCyclicWireUpdate(target, newState, source);
651 return;
652 }
653
654 pendingTransitions.erase(pendingTransitionKey(target, source));
655
656 if (target->getCurrentState() == newState)
657 return;
658
660 capturePreviousWireState(*activePreviousWireStates, target);
661
662 target->setCurrentState(newState, source);
663}
664
665void Simulator::updateBus(const Bus& bus, const BusValue& value, const uint64_t delay,
666 const Component_weakPtr& source)
667{
668 if (value.size() != bus.size()) {
669 throw std::invalid_argument(
670 std::format("Trying to set size {} bus to size {} busValue", bus.size(),
671 value.size()));
672 }
673
674 for (auto i = 0uz; i < bus.size(); ++i) {
675 updateWire(bus[i], value[i], delay, source);
676 }
677}
678
680Simulator::evaluateExecutionPlanAndTrace(std::span<const ExecutionStep> steps,
681 const Context& context,
682 const CancellationCheck& isCancelled)
683{
684 if (!evaluateExecutionPlan(steps, context, isCancelled))
686
689}
690
692 std::span<const Bus> changedBuses,
693 std::unordered_map<uint64_t, State> previousWireStates,
694 const CancellationCheck& isCancelled, const bool enableSequentialStaging)
695{
696 Context context{false, changedBuses, std::move(previousWireStates)};
697 const auto steps = getForwardExecutionSteps(changedBuses);
698 const EvaluationStateGuard evaluationState(*this, &context.previousWireStates,
699 enableSequentialStaging);
700
701 try {
702 const auto completed = evaluateExecutionSteps(steps, context, isCancelled);
703 if (!completed) {
706 }
707
708 evaluationState.setStageSequentialOutputs(false);
709 std::unordered_map<uint64_t, State> stagedPreviousWireStates;
710 const auto stagedChangedBuses =
711 enableSequentialStaging
712 ? commitStagedSequentialTransitions(stagedPreviousWireStates)
713 : std::vector<Bus>{};
714
715 if (!stagedChangedBuses.empty()) {
716 auto stagedContext =
717 Context{false, stagedChangedBuses, std::move(stagedPreviousWireStates)};
718 const auto stagedSteps = getForwardExecutionSteps(stagedChangedBuses);
719 evaluationState.setActivePreviousWireStates(&stagedContext.previousWireStates);
720 if (!evaluateExecutionSteps(stagedSteps, stagedContext, isCancelled)) {
722 }
723 }
724
727 } catch (...) {
729 throw;
730 }
731}
732
734{
735 simulationLog.info(std::format("Running simulation with a duration of {}", duration));
736 const uint64_t minimumEndTime = currentTime + duration;
737
738 uint64_t processedSteps = 0;
739 while (!eventQueue.empty() && eventQueue.top().time <= minimumEndTime) {
740 if (processedSteps >= maxSimulationSteps) {
741 simulationLog.warning("Simulation step limit exceeded before the event queue "
742 "stabilized. This might be an unstable circuit.");
744 }
745 ++processedSteps;
746
747 const auto result = processNextEventBatch(isCancelled);
748 if (result != RunResult::Completed)
749 return result;
750 }
751
752 if (currentTime < minimumEndTime) {
753 currentTime = minimumEndTime;
755 }
756
757 simulationLog.info("Circuit state stabilized (simulation complete)");
759}
760
762{
763 simulationLog.info("Running simulation until pending events are idle");
764
765 uint64_t processedSteps = 0;
766 while (!eventQueue.empty()) {
767 if (processedSteps >= maxSimulationSteps) {
768 simulationLog.warning("Simulation step limit exceeded before the event queue "
769 "stabilized. This might be an unstable circuit.");
771 }
772 ++processedSteps;
773
774 const auto result = processNextEventBatch(isCancelled);
775 if (result != RunResult::Completed)
776 return result;
777 }
778
779 simulationLog.info("Circuit state stabilized (simulation complete)");
781}
782
785{
786 // Stop only between event batches so a timestamp is never left half-applied.
787 if (cancellationRequested(isCancelled))
789
790 currentTime = eventQueue.top().time;
791 std::vector<Bus> changedBuses;
792 std::unordered_map<uint64_t, State> previousWireStates;
793
794 while (!eventQueue.empty() && eventQueue.top().time == currentTime) {
795 auto ev = eventQueue.top();
796 eventQueue.pop();
797
798 if (!isDelayedEventPending(ev))
799 continue;
800
801 capturePreviousWireState(previousWireStates, ev.targetWire);
802 pendingTransitions.erase(pendingTransitionKey(ev.targetWire, ev.source));
803
804 if (ev.targetWire && ev.targetWire->getCurrentState() != ev.newState) {
805 ev.targetWire->setCurrentState(ev.newState, ev.source);
806 changedBuses.push_back(Bus{ev.targetWire});
807 }
808 }
809
810 if (changedBuses.empty())
812
813 return evaluateForwardConeAndTrace(changedBuses, std::move(previousWireStates),
814 isCancelled);
815}
816
818 const uint64_t duration, std::span<const Sample> inputSnapshots,
819 std::span<const WaveformInputDriver> inputDrivers, CancellationCheck isCancelled)
820{
821 for (std::size_t sampleIndex = 0; sampleIndex < inputSnapshots.size();) {
822 const uint64_t sampleTime = inputSnapshots[sampleIndex].time;
823 if (sampleTime > currentTime) {
824 const auto result = run(sampleTime - currentTime, isCancelled);
825 if (result != RunResult::Completed)
826 return result;
827 }
828
829 std::vector<BusValue> values = inputSnapshots[sampleIndex].values;
830 ++sampleIndex;
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];
838 ++sampleIndex;
839 }
840
841 const auto result = applyWaveformInputSample(values, inputDrivers, isCancelled);
842 if (result != RunResult::Completed)
843 return result;
844 }
845
846 if (duration > currentTime)
847 return run(duration - currentTime, isCancelled);
849}
850
852Simulator::applyWaveformInputSample(std::span<const BusValue> values,
853 std::span<const WaveformInputDriver> inputDrivers,
854 const CancellationCheck& isCancelled)
855{
856 if (cancellationRequested(isCancelled))
858
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;
866 const auto normalized = SILICON::wireUtils::normalizeBusValue(values[i], bus.size());
867
868 if (bus.getCurrentValue() != normalized) {
869 inputsChanged = true;
870 changedBuses.push_back(bus);
871 capturePreviousBusStates(previousWireStates, bus);
872 }
873 (void)bus.forceSetCurrentValue(normalized, driver.source);
874 }
875
876 if (!inputsChanged)
878
879 return evaluateForwardConeAndTrace(changedBuses, std::move(previousWireStates),
880 isCancelled);
881}
882
884{
885 maxSimulationSteps = std::max<uint64_t>(1, value);
886}
887
889{
890 maxTransitionsPerDeltaCycle = std::max(1, value);
891}
892
897
902
904 CancellationCheck isCancelled)
905{
906 return setBus(std::move(bus), value, {}, std::move(isCancelled));
907}
908
910 const Component_weakPtr& source,
911 CancellationCheck isCancelled)
912{
913 if (cancellationRequested(isCancelled))
915
916 value = SILICON::wireUtils::normalizeBusValue(value, bus.size());
917
918 // Early return if bus current value == new value (only if the prev value is valid)
919 if (!bus.isInErrorState() && !bus.hasUnknowns()) {
920 BusValue currentVal = bus.getCurrentValue();
921 if (currentVal == value)
923 }
924
925 std::vector<Bus> changedBuses{bus};
926 std::unordered_map<uint64_t, State> previousWireStates;
927 capturePreviousBusStates(previousWireStates, bus);
928
929 (void)bus.forceSetCurrentValue(value, source);
930
931 return evaluateForwardConeAndTrace(changedBuses, std::move(previousWireStates),
932 isCancelled);
933}
934
936{
937 Circuit subCircuit = circuit->getBackwardsSubgraph(bus);
938 auto blocks = subCircuit.splitCyclic();
939 auto plan = compileExecutionPlan(blocks);
940
941 const Context context{true, {}};
942 return evaluateExecutionPlanAndTrace(plan, context, isCancelled);
943}
944
945} // namespace SILICON::simulation
bool hasUnknowns() const
Definition wire.cpp:545
bool forceSetCurrentValue(const BusValue &value)
Definition wire.cpp:487
bool isInErrorState() const
Definition wire.cpp:538
BusValue getCurrentValue() const
Definition wire.cpp:530
Represents a digital circuit as a directed graph of components.
Definition circuit.hpp:125
std::vector< SimulationBlock > splitCyclic() const
Splits the circuit into simulation blocks separating cyclic from acyclic parts.
Definition circuit.cpp:557
std::unordered_map< uint64_t, State > * previousActivePreviousWireStates
EvaluationStateGuard(Simulator &simulator, std::unordered_map< uint64_t, State > *activePreviousWireStates, bool stageSequentialOutputs)
Definition simulator.cpp:91
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.
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.
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.
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
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.
Definition wire.cpp:121
Context describing why a component is being evaluated.
Definition component.hpp:90
std::unordered_map< uint64_t, core::State > previousWireStates
Wire states captured before the reactive mutation that caused this pass.
Definition component.hpp:98
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< StagedCyclicWire > writes
std::unique_ptr< CyclicStaging > cyclicStaging
std::vector< Component_ptr > components
std::size_t operator()(const PendingTransitionKey &key) const noexcept
Definition simulator.cpp: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
Wire_ptr targetWire
The wire to update.
Definition simulator.hpp:50