Coverage Report

Created: 2026-11-02 16:55

/home/runner/work/LabNeura/LabNeura/src/labneura/eda/mapping/generic/generic_mapping.cpp
Line
Count
Source (jump to first uncovered line)
1
#include "labneura/eda/netlist.h"
2
3
#include "behavioral_synthesis.h"
4
5
#include <algorithm>
6
#include <cctype>
7
#include <cstdint>
8
#include <iterator>
9
#include <optional>
10
#include <regex>
11
#include <map>
12
#include <set>
13
#include <stdexcept>
14
#include <string>
15
#include <unordered_map>
16
#include <unordered_set>
17
#include <utility>
18
#include <vector>
19
20
namespace labneura::eda {
21
namespace {
22
23
2.09k
bool is_identifier(const Expression& expression) {
24
2.09k
    return expression.get_kind() == ExpressionKind::Identifier;
25
2.09k
}
26
27
349
std::optional<bool> literal_value(const Expression& expression) {
28
349
    if (expression.get_kind() != ExpressionKind::Literal &&
29
349
        expression.get_kind() != ExpressionKind::Opaque) {
30
329
        return std::nullopt;
31
329
    }
32
20
    const auto source = expression.get_source();
33
20
    static const std::regex based_literal(
34
20
        R"(^\s*[0-9]+\s*'\s*[sS]?[bBoOdDhH]\s*[0-9a-fA-F_xXzZ?]+\s*$)");
35
20
    static const std::regex decimal(R"(^\s*([0-9]+)\s*$)");
36
20
    std::smatch decimal_match;
37
20
    const bool is_based = std::regex_match(source, based_literal);
38
20
    const bool is_decimal = std::regex_match(source, decimal_match, decimal);
39
20
    if (!is_based && !is_decimal) return std::nullopt;
40
20
    if (source.find_first_of("xXzZ?") != std::string::npos) {
41
1
        throw std::runtime_error(
42
1
            "scalar X/Z constants cannot be mapped to generic tie cells");
43
1
    }
44
19
    if (is_decimal) {
45
3
        return (std::stoull(decimal_match[1].str()) & 1U) != 0;
46
3
    }
47
16
    const auto apostrophe = source.find('\'');
48
16
    const auto base_position = source.find_first_of("bBoOdDhH", apostrophe);
49
16
    const auto digit_position = source.find_first_not_of(" \t", base_position + 1);
50
16
    const auto digits = source.substr(digit_position);
51
16
    const char base = static_cast<char>(
52
16
        std::tolower(static_cast<unsigned char>(source[base_position])));
53
16
    if (digits.empty()) return std::nullopt;
54
16
    if (base == 'd') return (std::stoull(digits) & 1U) != 0;
55
16
    const char last_digit = digits.back();
56
16
    return (std::isdigit(static_cast<unsigned char>(last_digit))
57
16
                ? (last_digit - '0') & 1
58
16
                : (std::tolower(static_cast<unsigned char>(last_digit)) - 'a' + 10) &
59
0
                      1) != 0;
60
16
}
61
62
781
std::string pin_name(std::size_t index) {
63
781
    if (index >= 26) {
64
0
        throw std::runtime_error(
65
0
            "generic Boolean operator has more than 26 operands");
66
0
    }
67
781
    return std::string(1, static_cast<char>('A' + index));
68
781
}
69
70
std::string generic_type_for_operator(const std::string& op,
71
277
                                      std::size_t operand_count) {
72
277
    if (op == "&" || op == "&&") return "AND" + std::to_string(operand_count);
73
135
    if (op == "|" || op == "||") return "OR" + std::to_string(operand_count);
74
71
    if (op == "^") return "XOR" + std::to_string(operand_count);
75
0
    throw std::runtime_error("unsupported Boolean operator in generic mapping: " +
76
0
                             op);
77
71
}
78
79
std::optional<std::string> generic_type_for_primitive(
80
52
    const std::string& cell_type, std::size_t input_count) {
81
52
    if (cell_type == "pullup" || cell_type == "pulldown") {
82
2
        if (input_count != 0) {
83
0
            throw std::runtime_error(
84
0
                "primitive gate '" + cell_type + "' must not have inputs");
85
0
        }
86
2
        return cell_type == "pullup" ? "TIEHI" : "TIELO";
87
2
    }
88
50
    if (cell_type == "buf" || cell_type == "not") {
89
2
        if (input_count != 1) {
90
0
            throw std::runtime_error(
91
0
                "primitive gate '" + cell_type +
92
0
                "' must have exactly one input");
93
0
        }
94
2
        return cell_type == "buf" ? "BUF" : "INV";
95
2
    }
96
97
48
    std::string generic_family;
98
48
    if (cell_type == "and") generic_family = "AND";
99
31
    else if (cell_type == "nand") generic_family = "NAND";
100
29
    else if (cell_type == "or") generic_family = "OR";
101
17
    else if (cell_type == "nor") generic_family = "NOR";
102
16
    else if (cell_type == "xor") generic_family = "XOR";
103
12
    else if (cell_type == "xnor") generic_family = "XNOR";
104
11
    else return std::nullopt;
105
106
37
    if (input_count < 2) {
107
0
        throw std::runtime_error(
108
0
            "primitive gate '" + cell_type +
109
0
            "' must have at least two inputs");
110
0
    }
111
37
    return generic_family + std::to_string(input_count);
112
37
}
113
114
67
bool is_switch_level_primitive(const std::string& cell_type) {
115
67
    return cell_type == "cmos" || cell_type == "nmos" ||
116
67
           cell_type == "pmos" || cell_type == "rnmos" ||
117
67
           cell_type == "rpmos" || cell_type == "tran" ||
118
67
           cell_type == "rtran" || cell_type == "tranif0" ||
119
67
           cell_type == "tranif1" || cell_type == "rtranif0" ||
120
67
           cell_type == "rtranif1";
121
67
}
122
123
struct GenericMapper {
124
    std::vector<Net> nets;
125
    std::vector<Instance> instances;
126
    std::unordered_set<std::string> used_names;
127
    std::size_t next_index = 0;
128
129
110
    explicit GenericMapper(const Module& module) {
130
587
        for (const auto& net : module.get_nets()) used_names.insert(net.get_name());
131
110
        for (const auto& instance : module.get_instances()) {
132
64
            used_names.insert(instance.get_name());
133
64
        }
134
110
    }
135
136
1.23k
    std::string unique_name(const std::string& prefix) {
137
1.23k
        std::string name;
138
1.23k
        do {
139
1.23k
            name = prefix + std::to_string(next_index++);
140
1.23k
        } while (!used_names.insert(name).second);
141
1.23k
        return name;
142
1.23k
    }
143
144
    void add_cell(std::string type, std::vector<PinConnection> connections,
145
368
                  const std::string& output) {
146
368
        connections.emplace_back("Y", output);
147
368
        instances.emplace_back(unique_name("__generic_inst"), std::move(type),
148
368
                               std::move(connections));
149
368
    }
150
151
    void lower_user_defined_primitive(const Instance& instance,
152
1
                                      std::vector<Net>& output_nets) {
153
1
        if (instance.is_sequential_primitive()) {
154
0
            throw std::runtime_error(
155
0
                "generic mapping does not support sequential user-defined "
156
0
                "primitive '" +
157
0
                instance.get_cell_type() + "'");
158
0
        }
159
160
1
        const auto& connections = instance.get_connections();
161
1
        const auto output_connection = std::find_if(
162
1
            connections.begin(), connections.end(),
163
1
            [](const PinConnection& connection) {
164
1
                return connection.get_pin() == "Y";
165
1
            });
166
1
        std::vector<std::string> input_nets;
167
1
        input_nets.reserve(connections.size());
168
3
        for (const auto& connection : connections) {
169
3
            if (connection.get_pin() != "Y") {
170
2
                input_nets.push_back(connection.get_net());
171
2
            }
172
3
        }
173
1
        if (output_connection == connections.end() || input_nets.empty() ||
174
1
            input_nets.size() > 16 || instance.get_primitive_table().empty()) {
175
0
            throw std::runtime_error(
176
0
                "user-defined primitive '" + instance.get_cell_type() +
177
0
                "' has an unsupported port count or empty truth table");
178
0
        }
179
180
1
        const std::size_t combinations =
181
1
            std::size_t{1} << input_nets.size();
182
1
        std::vector<bool> covered(combinations, false);
183
1
        std::vector<bool> values(combinations, false);
184
1
        std::set<std::string> product_terms;
185
4
        for (const auto& row : instance.get_primitive_table()) {
186
4
            if (row.inputs.size() != input_nets.size() ||
187
4
                (row.output != '0' && row.output != '1')) {
188
0
                throw std::runtime_error(
189
0
                    "user-defined primitive '" + instance.get_cell_type() +
190
0
                    "' uses an unsupported UDP table symbol");
191
0
            }
192
20
            for (std::size_t combination = 0; combination < combinations;
193
16
                 ++combination) {
194
16
                bool matches = true;
195
28
                for (std::size_t index = 0; index < input_nets.size(); ++index) {
196
24
                    const char symbol = static_cast<char>(std::tolower(
197
24
                        static_cast<unsigned char>(row.inputs[index])));
198
24
                    const bool input =
199
24
                        (combination & (std::size_t{1} << index)) != 0;
200
24
                    if ((symbol == '0' && input) ||
201
24
                        (symbol == '1' && !input)) {
202
12
                        matches = false;
203
12
                        break;
204
12
                    }
205
12
                    if (symbol != '0' && symbol != '1' && symbol != '?' &&
206
12
                        symbol != 'b') {
207
0
                        throw std::runtime_error(
208
0
                            "user-defined primitive '" +
209
0
                            instance.get_cell_type() +
210
0
                            "' uses an unsupported UDP input symbol");
211
0
                    }
212
12
                }
213
16
                if (!matches) continue;
214
4
                const bool output = row.output == '1';
215
4
                if (covered[combination] && values[combination] != output) {
216
0
                    throw std::runtime_error(
217
0
                        "user-defined primitive '" +
218
0
                        instance.get_cell_type() +
219
0
                        "' has conflicting UDP table rows");
220
0
                }
221
4
                covered[combination] = true;
222
4
                values[combination] = output;
223
4
            }
224
4
            if (row.output == '1') product_terms.insert(row.inputs);
225
4
        }
226
1
        if (std::find(covered.begin(), covered.end(), false) != covered.end()) {
227
0
            throw std::runtime_error(
228
0
                "user-defined primitive '" + instance.get_cell_type() +
229
0
                "' has unspecified UDP outputs that cannot be mapped");
230
0
        }
231
1
        const auto output = output_connection->get_net();
232
1
        if (std::find(values.begin(), values.end(), false) == values.end()) {
233
0
            add_cell("TIEHI", {}, output);
234
0
            return;
235
0
        }
236
1
        if (product_terms.empty()) {
237
0
            add_cell("TIELO", {}, output);
238
0
            return;
239
0
        }
240
241
1
        std::vector<std::string> inverted_inputs(input_nets.size());
242
1
        std::vector<std::string> terms;
243
1
        terms.reserve(product_terms.size());
244
2
        for (const auto& pattern : product_terms) {
245
2
            std::vector<std::string> literals;
246
6
            for (std::size_t index = 0; index < input_nets.size(); ++index) {
247
4
                const auto symbol = static_cast<char>(std::tolower(
248
4
                    static_cast<unsigned char>(pattern[index])));
249
4
                if (symbol == '?' || symbol == 'b') continue;
250
4
                if (symbol == '1') {
251
2
                    literals.push_back(input_nets[index]);
252
2
                    continue;
253
2
                }
254
2
                if (inverted_inputs[index].empty()) {
255
2
                    inverted_inputs[index] = unique_name("__generic_net");
256
2
                    output_nets.emplace_back(inverted_inputs[index],
257
2
                                             NetType::Internal);
258
2
                    add_cell("INV", {{"A", input_nets[index]}},
259
2
                             inverted_inputs[index]);
260
2
                }
261
2
                literals.push_back(inverted_inputs[index]);
262
2
            }
263
264
2
            if (literals.empty()) {
265
0
                const auto constant = unique_name("__generic_net");
266
0
                output_nets.emplace_back(constant, NetType::Internal);
267
0
                add_cell("TIEHI", {}, constant);
268
0
                terms.push_back(constant);
269
2
            } else if (literals.size() == 1) {
270
0
                terms.push_back(literals.front());
271
2
            } else {
272
2
                const auto term = unique_name("__generic_net");
273
2
                output_nets.emplace_back(term, NetType::Internal);
274
2
                std::vector<PinConnection> term_inputs;
275
6
                for (std::size_t index = 0; index < literals.size(); ++index) {
276
4
                    term_inputs.emplace_back(pin_name(index), literals[index]);
277
4
                }
278
2
                add_cell("AND" + std::to_string(literals.size()),
279
2
                         std::move(term_inputs), term);
280
2
                terms.push_back(term);
281
2
            }
282
2
        }
283
284
1
        if (terms.size() == 1) {
285
0
            add_cell("BUF", {{"A", terms.front()}}, output);
286
0
            return;
287
0
        }
288
1
        std::vector<PinConnection> sum_inputs;
289
3
        for (std::size_t index = 0; index < terms.size(); ++index) {
290
2
            sum_inputs.emplace_back(pin_name(index), terms[index]);
291
2
        }
292
1
        add_cell("OR" + std::to_string(terms.size()), std::move(sum_inputs),
293
1
                 output);
294
1
    }
295
296
    bool collect_associative(const Expression& expression,
297
                             const std::string& op,
298
1.27k
                             std::vector<const Expression*>& operands) {
299
1.27k
        if (expression.get_kind() == ExpressionKind::Binary &&
300
1.27k
            expression.get_value() == op &&
301
1.27k
            expression.get_operands().size() == 2) {
302
498
            return collect_associative(expression.get_operands()[0], op,
303
498
                                        operands) &&
304
498
                   collect_associative(expression.get_operands()[1], op,
305
498
                                        operands);
306
498
        }
307
775
        operands.push_back(&expression);
308
775
        return true;
309
1.27k
    }
310
311
278
    bool is_supported_operator(const std::string& op) const {
312
278
        return op == "&" || op == "&&" || op == "|" || op == "||" ||
313
278
               op == "^";
314
278
    }
315
316
    std::optional<std::string> lower(const Expression& expression,
317
1.02k
                                     const std::string& destination) {
318
1.02k
        if (is_identifier(expression)) return expression.get_source();
319
350
        if (expression.get_kind() == ExpressionKind::BitSelect &&
320
350
            expression.get_operands().size() == 2) {
321
1
            const auto& base = expression.get_operands()[0];
322
1
            const auto& selector = expression.get_operands()[1];
323
1
            if (selector.get_kind() == ExpressionKind::Literal) {
324
0
                return expression.get_source();
325
0
            }
326
1
            const auto data_width = base.get_width();
327
1
            const auto selector_width = selector.get_width();
328
1
            if (!is_identifier(base) || !is_identifier(selector) ||
329
1
                data_width < 2 || selector_width == 0 ||
330
1
                selector_width >= sizeof(std::size_t) * 8 ||
331
1
                data_width != (std::size_t{1} << selector_width)) {
332
0
                return std::nullopt;
333
0
            }
334
335
1
            std::vector<std::string> values;
336
1
            values.reserve(data_width);
337
5
            for (std::size_t i = 0; i < data_width; ++i) {
338
4
                values.push_back(base.get_source() + "[" +
339
4
                                 std::to_string(i) + "]");
340
4
            }
341
3
            for (std::size_t level = 0; level < selector_width; ++level) {
342
2
                std::vector<std::string> next_values;
343
2
                next_values.reserve(values.size() / 2);
344
5
                for (std::size_t i = 0; i < values.size(); i += 2) {
345
3
                    const bool final_cell = values.size() == 2;
346
3
                    const auto output =
347
3
                        final_cell ? destination : unique_name("__generic_net");
348
3
                    if (!final_cell) nets.emplace_back(output, NetType::Internal);
349
3
                    add_cell(
350
3
                        "MUX2",
351
3
                        {{"A0", values[i]},
352
3
                         {"A1", values[i + 1]},
353
3
                         {"S", selector.get_source() + "[" +
354
3
                                   std::to_string(level) + "]"}},
355
3
                        output);
356
3
                    next_values.push_back(output);
357
3
                }
358
2
                values = std::move(next_values);
359
2
            }
360
1
            return destination;
361
1
        }
362
349
        if (const auto value = literal_value(expression)) {
363
19
            add_cell(*value ? "TIEHI" : "TIELO", {}, destination);
364
19
            return destination;
365
19
        }
366
330
        if (expression.get_kind() == ExpressionKind::Binary &&
367
330
            is_supported_operator(expression.get_value())) {
368
277
            std::vector<const Expression*> operands;
369
277
            if (!collect_associative(expression, expression.get_value(),
370
277
                                     operands)) {
371
0
                return std::nullopt;
372
0
            }
373
277
            if (operands.size() < 2) return std::nullopt;
374
277
            std::vector<PinConnection> connections;
375
1.05k
            for (std::size_t i = 0; i < operands.size(); ++i) {
376
775
                const auto signal = lower(*operands[i], unique_name("__generic_net"));
377
775
                if (!signal) return std::nullopt;
378
775
                if (*signal != operands[i]->get_source() ||
379
775
                    !is_identifier(*operands[i])) {
380
136
                    nets.emplace_back(*signal, NetType::Internal);
381
136
                }
382
775
                connections.emplace_back(pin_name(i), *signal);
383
775
            }
384
277
            add_cell(generic_type_for_operator(expression.get_value(),
385
277
                                               operands.size()),
386
277
                     std::move(connections), destination);
387
277
            return destination;
388
277
        }
389
53
        if (expression.get_kind() == ExpressionKind::Unary &&
390
53
            (expression.get_value() == "~" || expression.get_value() == "!") &&
391
53
            expression.get_operands().size() == 1) {
392
38
            const auto& operand = expression.get_operands().front();
393
38
            const auto signal = lower(operand, unique_name("__generic_net"));
394
38
            if (!signal) return std::nullopt;
395
38
            if (!is_identifier(operand)) nets.emplace_back(*signal, NetType::Internal);
396
38
            add_cell("INV", {{"A", *signal}}, destination);
397
38
            return destination;
398
38
        }
399
15
        if (expression.get_kind() == ExpressionKind::Conditional &&
400
15
            expression.get_operands().size() == 3) {
401
13
            const auto& operands = expression.get_operands();
402
13
            std::vector<std::string> signals;
403
39
            for (const auto& operand : operands) {
404
39
                const auto signal = lower(operand, unique_name("__generic_net"));
405
39
                if (!signal) return std::nullopt;
406
39
                if (!is_identifier(operand)) nets.emplace_back(*signal, NetType::Internal);
407
39
                signals.push_back(*signal);
408
39
            }
409
13
            add_cell("MUX2",
410
13
                     {{"S", signals[0]}, {"A1", signals[1]},
411
13
                      {"A0", signals[2]}},
412
13
                     destination);
413
13
            return destination;
414
13
        }
415
2
        return std::nullopt;
416
15
    }
417
};
418
419
}  // namespace
420
421
154
Module generic_map(const Module& rtl_module) {
422
154
    const auto map_module =
423
192
        [&](const auto& self, const Module& source) -> Module {
424
192
        std::vector<Module> child_modules;
425
192
        child_modules.reserve(source.get_child_modules().size());
426
192
        for (const auto& child : source.get_child_modules()) {
427
38
            child_modules.push_back(self(self, child));
428
38
        }
429
430
192
        Module mapped;
431
192
        const bool requires_behavioral_lowering =
432
192
            source.is_behavioral() ||
433
192
            std::any_of(source.get_assignments().begin(),
434
111
                        source.get_assignments().end(),
435
175
                        [](const ContinuousAssignment& assignment) {
436
175
                            return !is_identifier(
437
175
                                assignment.get_lhs_expression());
438
175
                        });
439
192
        if (requires_behavioral_lowering) {
440
82
            mapped = detail::lower_behavioral_rtl(
441
82
                source.parsed_context_, source.get_name(), {}, true);
442
82
            mapped = Module(mapped.get_name(), mapped.get_ports(),
443
82
                            mapped.get_nets(), mapped.get_instances(),
444
82
                            mapped.get_assignments(), mapped.is_behavioral(),
445
82
                            source.get_hierarchy_instance_name(),
446
82
                            mapped.get_child_modules());
447
110
        } else {
448
110
            GenericMapper mapper(source);
449
110
            std::vector<ContinuousAssignment> remaining_assignments;
450
451
174
            for (const auto& assignment : source.get_assignments()) {
452
174
                const auto& lhs = assignment.get_lhs_expression();
453
174
                if (!is_identifier(lhs)) {
454
0
                    throw std::runtime_error(
455
0
                        "generic mapping currently requires scalar identifier assignment targets: " +
456
0
                        assignment.get_lhs());
457
0
                }
458
174
                const auto result =
459
174
                    mapper.lower(assignment.get_rhs_expression(), lhs.get_source());
460
174
                if (!result) {
461
1
                    throw std::runtime_error("continuous assignment '" +
462
1
                                             assignment.get_lhs() + " = " +
463
1
                                             assignment.get_rhs() +
464
1
                                             "' has no supported generic mapping");
465
1
                }
466
173
                if (*result != lhs.get_source()) {
467
9
                    mapper.add_cell("BUF", {{"A", *result}}, lhs.get_source());
468
9
                }
469
173
            }
470
471
109
            auto nets = source.get_nets();
472
109
            nets.insert(nets.end(),
473
109
                        std::make_move_iterator(mapper.nets.begin()),
474
109
                        std::make_move_iterator(mapper.nets.end()));
475
109
            auto instances = source.get_instances();
476
166
            for (std::size_t index = 0; index < instances.size();) {
477
68
                auto& instance = instances[index];
478
68
                const auto& cell_type = instance.get_cell_type();
479
68
                if (instance.is_user_defined_primitive()) {
480
1
                    mapper.lower_user_defined_primitive(instance, nets);
481
1
                    instances.erase(instances.begin() +
482
1
                                    static_cast<std::ptrdiff_t>(index));
483
1
                    continue;
484
1
                }
485
67
                if (is_switch_level_primitive(cell_type)) {
486
11
                    throw std::runtime_error(
487
11
                        "generic mapping does not support switch-level "
488
11
                        "primitive '" +
489
11
                        cell_type +
490
11
                        "'; use a synthesis flow with switch-level support");
491
11
                }
492
56
                const auto input_count = static_cast<std::size_t>(
493
56
                    std::count_if(
494
56
                        instance.get_connections().begin(),
495
56
                        instance.get_connections().end(),
496
170
                        [](const PinConnection& connection) {
497
170
                            return connection.get_pin() != "Y";
498
170
                        }));
499
56
                if (cell_type == "bufif0" || cell_type == "bufif1" ||
500
56
                    cell_type == "notif0" || cell_type == "notif1") {
501
4
                    if (input_count != 2) {
502
0
                        throw std::runtime_error(
503
0
                            "primitive gate '" + cell_type +
504
0
                            "' must have exactly two inputs");
505
0
                    }
506
4
                    const auto& connections = instance.get_connections();
507
4
                    const auto output = std::find_if(
508
4
                        connections.begin(), connections.end(),
509
4
                        [](const PinConnection& connection) {
510
4
                            return connection.get_pin() == "Y";
511
4
                        });
512
4
                    const auto data = std::find_if(
513
4
                        connections.begin(), connections.end(),
514
8
                        [](const PinConnection& connection) {
515
8
                            return connection.get_pin() == "A";
516
8
                        });
517
4
                    const auto enable = std::find_if(
518
4
                        connections.begin(), connections.end(),
519
12
                        [](const PinConnection& connection) {
520
12
                            return connection.get_pin() == "B";
521
12
                        });
522
4
                    if (output == connections.end() ||
523
4
                        data == connections.end() ||
524
4
                        enable == connections.end()) {
525
0
                        throw std::runtime_error(
526
0
                            "primitive gate '" + cell_type +
527
0
                            "' has invalid connections");
528
0
                    }
529
530
4
                    std::string data_net = data->get_net();
531
4
                    std::string enable_net = enable->get_net();
532
4
                    if (cell_type == "notif0" || cell_type == "notif1") {
533
2
                        const auto inverted =
534
2
                            mapper.unique_name("__generic_net");
535
2
                        nets.emplace_back(inverted, NetType::Internal);
536
2
                        mapper.add_cell("INV", {{"A", data_net}}, inverted);
537
2
                        data_net = inverted;
538
2
                    }
539
4
                    if (cell_type == "bufif1" || cell_type == "notif1") {
540
2
                        const auto inverted =
541
2
                            mapper.unique_name("__generic_net");
542
2
                        nets.emplace_back(inverted, NetType::Internal);
543
2
                        mapper.add_cell("INV", {{"A", enable_net}}, inverted);
544
2
                        enable_net = inverted;
545
2
                    }
546
4
                    instance = Instance(
547
4
                        instance.get_name(), "TRIBUF",
548
4
                        {{"A", std::move(data_net)},
549
4
                         {"TE_B", std::move(enable_net)},
550
4
                         {"Y", output->get_net()}});
551
4
                    continue;
552
4
                }
553
52
                const auto generic_type = generic_type_for_primitive(
554
52
                    cell_type, input_count);
555
52
                if (generic_type) {
556
41
                    instance = Instance(instance.get_name(),
557
41
                                        *generic_type,
558
41
                                        instance.get_connections());
559
41
                }
560
52
                ++index;
561
52
            }
562
98
            instances.insert(
563
98
                instances.end(),
564
98
                std::make_move_iterator(mapper.instances.begin()),
565
98
                std::make_move_iterator(mapper.instances.end()));
566
98
            mapped = Module(source.get_name(), source.get_ports(),
567
98
                            std::move(nets), std::move(instances),
568
98
                            std::move(remaining_assignments),
569
98
                            source.is_behavioral(),
570
98
                            source.get_hierarchy_instance_name(),
571
98
                            std::move(child_modules));
572
98
        }
573
574
180
        return mapped;
575
192
    };
576
577
154
    return map_module(map_module, rtl_module);
578
154
}
579
580
Module generic_map(const Project& project, const std::string& top,
581
10
                   const std::map<std::string, std::string>& parameters) {
582
10
    std::unordered_map<std::string, const Module*> by_name;
583
10
    std::unordered_set<std::string> instantiated;
584
94
    for (const auto& module : project.get_modules()) by_name[module.get_name()] = &module;
585
94
    for (const auto& module : project.get_modules()) {
586
159
        for (const auto& instance : module.get_instances()) {
587
159
            if (by_name.count(instance.get_cell_type())) {
588
159
                instantiated.insert(instance.get_cell_type());
589
159
            }
590
159
        }
591
94
    }
592
593
10
    std::string top_name = top;
594
10
    if (top_name.empty()) {
595
0
        for (const auto& module : project.get_modules()) {
596
0
            if (instantiated.count(module.get_name())) continue;
597
0
            if (!top_name.empty()) {
598
0
                throw std::runtime_error(
599
0
                    "project has several top-level modules; pass top=<module>");
600
0
            }
601
0
            top_name = module.get_name();
602
0
        }
603
0
        if (top_name.empty()) throw std::runtime_error("project has no top-level module");
604
0
    }
605
10
    const auto top_module = by_name.find(top_name);
606
10
    if (top_module == by_name.end()) {
607
1
        throw std::runtime_error("top module '" + top_name + "' not found in project");
608
1
    }
609
610
9
    if (parameters.empty()) {
611
6
        std::unordered_set<std::string> active_modules;
612
6
        const auto build_hierarchy =
613
6
            [&](const auto& self, const Module& source,
614
38
                const std::string& instance_name) -> Module {
615
38
            if (!active_modules.insert(source.get_name()).second) {
616
0
                throw std::runtime_error(
617
0
                    "recursive module hierarchy detected at '" +
618
0
                    source.get_name() + "'");
619
0
            }
620
621
38
            std::vector<Module> children;
622
38
            for (const auto& instance : source.get_instances()) {
623
32
                const auto child = by_name.find(instance.get_cell_type());
624
32
                if (child != by_name.end()) {
625
32
                    children.push_back(
626
32
                        self(self, *child->second, instance.get_name()));
627
32
                }
628
32
            }
629
630
38
            active_modules.erase(source.get_name());
631
38
            Module hierarchy_node(
632
38
                source.get_name(), source.get_ports(), source.get_nets(),
633
38
                source.get_instances(), source.get_assignments(),
634
38
                source.is_behavioral(), instance_name, std::move(children));
635
38
            hierarchy_node.parsed_context_ = source.parsed_context_;
636
38
            return hierarchy_node;
637
38
        };
638
6
        auto hierarchy =
639
6
            build_hierarchy(build_hierarchy, *top_module->second, {});
640
6
        hierarchy.parsed_context_ = project.parsed_context_;
641
6
        return generic_map(hierarchy);
642
6
    }
643
644
    // Parameter overrides use project-wide elaboration so the specialized
645
    // design reflects the selected top-level values.
646
3
    bool needs_lowering = !parameters.empty();
647
3
    std::vector<const Module*> pending{top_module->second};
648
3
    std::unordered_set<std::string> visited;
649
8
    while (!pending.empty()) {
650
5
        const Module* module = pending.back();
651
5
        pending.pop_back();
652
5
        if (!visited.insert(module->get_name()).second) continue;
653
5
        if (module->is_behavioral()) needs_lowering = true;
654
5
        for (const auto& instance : module->get_instances()) {
655
2
            const auto child = by_name.find(instance.get_cell_type());
656
2
            if (child == by_name.end()) continue;
657
2
            needs_lowering = true;
658
2
            pending.push_back(child->second);
659
2
        }
660
5
    }
661
3
    if (!needs_lowering) return generic_map(*top_module->second);
662
3
    return detail::lower_behavioral_rtl(project.parsed_context_, top_name,
663
3
                                        parameters, true);
664
3
}
665
666
}  // namespace labneura::eda