SILICON
Loading...
Searching...
No Matches
gates.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 "gates.hpp"
19
20#include <algorithm>
21#include <functional>
22#include <stdexcept>
23
24#include <core/simulator.hpp>
25
26namespace SILICON::core {
27
28namespace {
29 uint64_t gateDelay(const Gate& gate)
30 {
31 return gate.getPropertyValue<int>("delay").value_or(0);
32 }
33
34 bool gateBitwiseEnabled(const Gate& gate)
35 {
36 return gate.getPropertyValue<bool>("bitwise").value_or(false);
37 }
38
39 int gateWidth(const Gate& gate)
40 {
41 return gate.getPropertyValue<int>("size").value_or(1);
42 }
43
44 State busTruthValue(const Bus& bus)
45 {
46 State result = State::LOW;
47 for (const auto& wire : bus)
48 result = result || Wire::safeGetCurrentState(wire);
49 return result;
50 }
51
52 template <typename Reducer, typename Finalizer = std::identity>
53 void simulateBitwiseGate(Gate& gate, SILICON::simulation::Simulator& sim,
54 State initialState, Reducer&& reducer,
55 Finalizer&& finalizer = {})
56 {
57 const auto delay = gateDelay(gate);
58 const auto inputs = gate.getInputs();
59 const auto outputs = gate.getOutputs();
60
61 if (!gateBitwiseEnabled(gate)) {
62 State result = initialState;
63 for (const auto& input : inputs) {
64 if (gateWidth(gate) > 1) {
65 for (const auto& wire : input)
66 result = reducer(result, Wire::safeGetCurrentState(wire));
67 } else {
68 result = reducer(result, busTruthValue(input));
69 }
70 }
71
72 sim.updateWire(outputs[0][0], finalizer(result), delay, gate.weak_from_this());
73 return;
74 }
75
76 const int width = gateWidth(gate);
77 for (int bit = 0; bit < width; ++bit) {
78 State result = initialState;
79 for (const auto& input : inputs)
80 result = reducer(result, Wire::safeGetCurrentState(input[bit]));
81
82 sim.updateWire(outputs[0][bit], finalizer(result), delay, gate.weak_from_this());
83 }
84 }
85} // namespace
86
87Gate::Gate() : Gate(true) {}
88
89Gate::Gate(const bool enableBitwiseProperties)
90{
91 initializeProperties(enableBitwiseProperties);
92}
93
94Gate::Gate(const std::vector<Wire_ptr>& inputs, Wire_ptr output)
95 : Gate(inputs, std::move(output), true)
96{
97}
98
99Gate::Gate(const std::vector<Wire_ptr>& inputs, Wire_ptr output,
100 const bool enableBitwiseProperties)
101 : Gate(enableBitwiseProperties)
102{
103 if (inputs.empty())
104 throw std::invalid_argument("Gate requires at least one input");
105
106 scalarInputCount = inputs.size();
107 for (const auto& input : inputs)
108 this->inputs.push_back({input});
109 this->outputs = {{output}};
110}
111
112void Gate::initializeProperties(const bool enableBitwiseProperties)
113{
114 defineProperty("delay", 5);
115 setPropertyCallback("delay", [](const PropertyValue& value) {
116 return requireNonNegative("delay", value);
117 });
118
119 if (!enableBitwiseProperties)
120 return;
121
122 defineProperty("bitwise", false);
123 defineProperty("size", 1);
124
125 setPropertyCallback("bitwise", [this](const PropertyValue& value) {
126 const bool bitwise = std::get<bool>(value);
127 if (!inputs.empty() && !outputs.empty()) {
128 const int size = getPropertyValue<int>("size").value_or(1);
129 configureIO(size, bitwise);
130 }
131 return value;
132 });
133
134 setPropertyCallback("size", [this](const PropertyValue& value) {
135 const int size = std::get<int>(requireValidSize("Gate size", value));
136
137 if (!inputs.empty() && !outputs.empty())
138 configureIO(size, getPropertyValue<bool>("bitwise").value_or(false));
139
140 return value;
141 });
142}
143
144void Gate::configureIO(const int size, const bool bitwise)
145{
146 auto newInputs = getInputs();
147 if (newInputs.size() > 1)
148 scalarInputCount = newInputs.size();
149
150 const bool reduction = !bitwise && size > 1;
151 const auto inputCount = reduction ? 1 : scalarInputCount;
152 newInputs.resize(std::min(newInputs.size(), inputCount));
153 while (newInputs.size() < inputCount)
154 newInputs.emplace_back(1);
155 for (auto& input : newInputs)
156 input.setSize(static_cast<unsigned short>(size));
157
158 auto newOutputs = getOutputs();
159 for (auto& output : newOutputs)
160 output.setSize(static_cast<unsigned short>(bitwise ? size : 1));
161
162 setInputs(newInputs);
163 setOutputs(newOutputs);
164}
165
166int Gate::setSize(const int width)
167{
168 if (width < 1)
169 return static_cast<int>(outputs.empty() ? 0 : outputs[0].size());
170
171 auto newInputs = getInputs();
172 for (auto& input : newInputs)
173 input.setSize(static_cast<unsigned short>(width));
174 setInputs(newInputs);
175
176 auto newOutputs = getOutputs();
177 for (auto& output : newOutputs)
178 output.setSize(static_cast<unsigned short>(width));
179 setOutputs(newOutputs);
180
181 return width;
182}
183
184AndGate::AndGate(const std::vector<Wire_ptr>& inputs, Wire_ptr output)
185 : Gate(inputs, std::move(output))
186{
187 if (inputs.size() < 2)
188 throw std::invalid_argument("AndGate requires at least 2 inputs");
189}
190
192{
193 simulateBitwiseGate(*this, sim, State::HIGH,
194 [](const State lhs, const State rhs) { return lhs && rhs; });
195}
196
197OrGate::OrGate(const std::vector<Wire_ptr>& inputs, Wire_ptr output)
198 : Gate(inputs, output)
199{
200 if (inputs.size() < 2)
201 throw std::invalid_argument("OrGate requires at least 2 inputs");
202}
203
205{
206 simulateBitwiseGate(*this, sim, State::LOW,
207 [](const State lhs, const State rhs) { return lhs || rhs; });
208}
209
214
215NotGate::NotGate(Wire_ptr input, Wire_ptr output) : Gate({input}, output, false)
216{
217 initializeNotProperties();
218}
219
221{
222 setProperty("delay", 2);
223 defineProperty("size", 1);
224 setPropertyCallback("size", [this](const PropertyValue& value) {
225 const int size = std::get<int>(requireValidSize("Gate size", value));
226 if (!inputs.empty() && !outputs.empty())
227 setSize(size);
228 return value;
229 });
230}
231
233{
234 const auto delay = getPropertyValue<int>("delay").value_or(0);
235 if (outputs[0].size() == 1) {
236 sim.updateWire(outputs[0][0], !busTruthValue(inputs[0]), delay, weak_from_this());
237 return;
238 }
239
240 if (inputs[0].size() != outputs[0].size())
241 throw std::logic_error("NOT gate input and output widths must match");
242
243 for (std::size_t bit = 0; bit < outputs[0].size(); ++bit) {
244 sim.updateWire(
245 outputs[0][static_cast<unsigned short>(bit)],
246 !Wire::safeGetCurrentState(inputs[0][static_cast<unsigned short>(bit)]), delay,
247 weak_from_this());
248 }
249}
250
251NandGate::NandGate(const std::vector<Wire_ptr>& inputs, Wire_ptr output)
252 : Gate(inputs, output)
253{
254 if (inputs.size() < 2)
255 throw std::invalid_argument("NandGate requires at least 2 inputs");
256 setProperty("delay", 6);
257}
258
260{
261 simulateBitwiseGate(
262 *this, sim, State::HIGH,
263 [](const State lhs, const State rhs) { return lhs && rhs; },
264 [](const State state) { return !state; });
265}
266
267NorGate::NorGate(const std::vector<Wire_ptr>& inputs, Wire_ptr output)
268 : Gate(inputs, output)
269{
270 if (inputs.size() < 2)
271 throw std::invalid_argument("NorGate requires at least 2 inputs");
272 setProperty("delay", 6);
273}
274
276{
277 simulateBitwiseGate(
278 *this, sim, State::LOW, [](const State lhs, const State rhs) { return lhs || rhs; },
279 [](const State state) { return !state; });
280}
281
282XorGate::XorGate(const std::array<Wire_ptr, 2>& inputs, Wire_ptr output)
283 : Gate({inputs[0], inputs[1]}, output)
284{
285 setProperty("delay", 7);
286}
287
289{
290 simulateBitwiseGate(*this, sim, State::LOW,
291 [](const State lhs, const State rhs) { return lhs ^ rhs; });
292}
293
294} // namespace SILICON::core
void simulate(SILICON::simulation::Simulator &sim) override
Executes the component's logic.
Definition gates.cpp:191
void setOutputs(const std::vector< Bus > &newOutputs)
Replaces all output buses.
std::optional< T > getPropertyValue(std::string_view key) const
Gets a property value with type deduction.
std::vector< Bus > outputs
Output buses produced by this component.
void setInputs(const std::vector< Bus > &newInputs)
Replaces all input buses.
void setProperty(std::string_view key, const PropertyValue &value)
Sets a property value.
std::vector< Bus > getOutputs() const
Gets all output buses.
std::vector< Bus > inputs
Input buses connected to this component.
void setPropertyCallback(std::string_view key, PropertyCallback callback)
Sets a callback for property validation/transformation.
void defineProperty(std::string key, T &&defaultValue, PropertyCallback callback=nullptr)
Defines a property with a default value and optional callback.
std::vector< Bus > getInputs() const
Gets all input buses.
Base class for combinational logic gates.
Definition gates.hpp:38
void initializeProperties(bool enableBitwiseProperties)
Definition gates.cpp:112
int setSize(int width)
Resizes every input bus and the output bus to the same width.
Definition gates.cpp:166
Gate(const std::vector< Wire_ptr > &inputs, Wire_ptr output)
Constructs a gate with scalar I/O and bitwise properties enabled.
Definition gates.cpp:94
Gate()
Constructs an empty gate instance for factory/serialization usage.
Definition gates.cpp:87
void configureIO(int size, bool bitwise)
Definition gates.cpp:144
std::size_t scalarInputCount
Definition gates.hpp:42
void simulate(SILICON::simulation::Simulator &sim) override
Executes the component's logic.
Definition gates.cpp:259
void simulate(SILICON::simulation::Simulator &sim) override
Executes the component's logic.
Definition gates.cpp:275
void simulate(SILICON::simulation::Simulator &sim) override
Executes the component's logic.
Definition gates.cpp:232
void initializeNotProperties()
Definition gates.cpp:220
void simulate(SILICON::simulation::Simulator &sim) override
Executes the component's logic.
Definition gates.cpp:204
static State safeGetCurrentState(const std::weak_ptr< Wire > &w)
Definition wire.cpp:245
void simulate(SILICON::simulation::Simulator &sim) override
Executes the component's logic.
Definition gates.cpp:288
Executes event-driven simulation of a Circuit.
Definition simulator.hpp:74
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.
int width(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key)
std::optional< Gate > gate(Cell *cell, SigMap &signals)
std::shared_ptr< Wire > Wire_ptr
Definition wire.hpp:116
std::variant< int, bool, std::string, BusValue > PropertyValue
Variant type for component properties.
PropertyValue requireValidSize(const std::string_view name, const PropertyValue &value)
Validates that an integer property value is a valid bus size.
Definition component.cpp:38
PropertyValue requireNonNegative(const std::string_view name, const PropertyValue &value)
Validates that an integer property value is non-negative.
Definition component.cpp:29