Add fileinfo to firrtl backend for instances
[yosys.git] / backends / firrtl / firrtl.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 */
19
20 #include "kernel/rtlil.h"
21 #include "kernel/register.h"
22 #include "kernel/sigtools.h"
23 #include "kernel/celltypes.h"
24 #include "kernel/cellaigs.h"
25 #include "kernel/log.h"
26 #include <algorithm>
27 #include <string>
28 #include <vector>
29 #include <cmath>
30
31 USING_YOSYS_NAMESPACE
32 PRIVATE_NAMESPACE_BEGIN
33
34 pool<string> used_names;
35 dict<IdString, string> namecache;
36 int autoid_counter;
37
38 typedef unsigned FDirection;
39 static const FDirection FD_NODIRECTION = 0x0;
40 static const FDirection FD_IN = 0x1;
41 static const FDirection FD_OUT = 0x2;
42 static const FDirection FD_INOUT = 0x3;
43 static const int FIRRTL_MAX_DSH_WIDTH_ERROR = 20; // For historic reasons, this is actually one greater than the maximum allowed shift width
44
45 // Shamelessly copied from ilang_backend.cc. Something better is surely possible here.
46 void dump_const(std::ostream &f, const RTLIL::Const &data, int width = -1, int offset = 0, bool autoint = true)
47 {
48 if (width < 0)
49 width = data.bits.size() - offset;
50 if ((data.flags & RTLIL::CONST_FLAG_STRING) == 0 || width != (int)data.bits.size()) {
51 if (width == 32 && autoint) {
52 int32_t val = 0;
53 for (int i = 0; i < width; i++) {
54 log_assert(offset+i < (int)data.bits.size());
55 switch (data.bits[offset+i]) {
56 case RTLIL::S0: break;
57 case RTLIL::S1: val |= 1 << i; break;
58 default: val = -1; break;
59 }
60 }
61 if (val >= 0) {
62 f << stringf("%d", val);
63 return;
64 }
65 }
66 f << stringf("%d'", width);
67 for (int i = offset+width-1; i >= offset; i--) {
68 log_assert(i < (int)data.bits.size());
69 switch (data.bits[i]) {
70 case RTLIL::S0: f << stringf("0"); break;
71 case RTLIL::S1: f << stringf("1"); break;
72 case RTLIL::Sx: f << stringf("x"); break;
73 case RTLIL::Sz: f << stringf("z"); break;
74 case RTLIL::Sa: f << stringf("-"); break;
75 case RTLIL::Sm: f << stringf("m"); break;
76 }
77 }
78 } else {
79 f << stringf("\"");
80 std::string str = data.decode_string();
81 for (size_t i = 0; i < str.size(); i++) {
82 if (str[i] == '\n')
83 f << stringf("\\n");
84 else if (str[i] == '\t')
85 f << stringf("\\t");
86 else if (str[i] < 32)
87 f << stringf("\\%03o", str[i]);
88 else if (str[i] == '"')
89 f << stringf("\\\"");
90 else if (str[i] == '\\')
91 f << stringf("\\\\");
92 else
93 f << str[i];
94 }
95 f << stringf("\"");
96 }
97 }
98
99 std::string getFileinfo(dict<RTLIL::IdString, RTLIL::Const> attributes)
100 {
101 std::ostringstream fileinfo;
102 for (auto &it : attributes) {
103 if (it.first == "\\src") {
104 dump_const(fileinfo, it.second);
105 }
106 }
107 return fileinfo.str();
108 }
109
110 // Get a port direction with respect to a specific module.
111 FDirection getPortFDirection(IdString id, Module *module)
112 {
113 Wire *wire = module->wires_.at(id);
114 FDirection direction = FD_NODIRECTION;
115 if (wire && wire->port_id)
116 {
117 if (wire->port_input)
118 direction |= FD_IN;
119 if (wire->port_output)
120 direction |= FD_OUT;
121 }
122 return direction;
123 }
124
125 string next_id()
126 {
127 string new_id;
128
129 while (1) {
130 new_id = stringf("_%d", autoid_counter++);
131 if (used_names.count(new_id) == 0) break;
132 }
133
134 used_names.insert(new_id);
135 return new_id;
136 }
137
138 const char *make_id(IdString id)
139 {
140 if (namecache.count(id) != 0)
141 return namecache.at(id).c_str();
142
143 string new_id = log_id(id);
144
145 for (int i = 0; i < GetSize(new_id); i++)
146 {
147 char &ch = new_id[i];
148 if ('a' <= ch && ch <= 'z') continue;
149 if ('A' <= ch && ch <= 'Z') continue;
150 if ('0' <= ch && ch <= '9' && i != 0) continue;
151 if ('_' == ch) continue;
152 ch = '_';
153 }
154
155 while (used_names.count(new_id) != 0)
156 new_id += '_';
157
158 namecache[id] = new_id;
159 used_names.insert(new_id);
160 return namecache.at(id).c_str();
161 }
162
163 struct FirrtlWorker
164 {
165 Module *module;
166 std::ostream &f;
167
168 dict<SigBit, pair<string, int>> reverse_wire_map;
169 string unconn_id;
170 RTLIL::Design *design;
171 std::string indent;
172
173 // Define read/write ports and memories.
174 // We'll collect their definitions and emit the corresponding FIRRTL definitions at the appropriate point in module construction.
175 // For the moment, we don't handle $readmemh or $readmemb.
176 // These will be part of a subsequent PR.
177 struct read_port {
178 string name;
179 bool clk_enable;
180 bool clk_parity;
181 bool transparent;
182 RTLIL::SigSpec clk;
183 RTLIL::SigSpec ena;
184 RTLIL::SigSpec addr;
185 read_port(string name, bool clk_enable, bool clk_parity, bool transparent, RTLIL::SigSpec clk, RTLIL::SigSpec ena, RTLIL::SigSpec addr) : name(name), clk_enable(clk_enable), clk_parity(clk_parity), transparent(transparent), clk(clk), ena(ena), addr(addr) {
186 // Current (3/13/2019) conventions:
187 // generate a constant 0 for clock and a constant 1 for enable if they are undefined.
188 if (!clk.is_fully_def())
189 this->clk = SigSpec(State::S0);
190 if (!ena.is_fully_def())
191 this->ena = SigSpec(State::S1);
192 }
193 string gen_read(const char * indent) {
194 string addr_expr = make_expr(addr);
195 string ena_expr = make_expr(ena);
196 string clk_expr = make_expr(clk);
197 string addr_str = stringf("%s%s.addr <= %s\n", indent, name.c_str(), addr_expr.c_str());
198 string ena_str = stringf("%s%s.en <= %s\n", indent, name.c_str(), ena_expr.c_str());
199 string clk_str = stringf("%s%s.clk <= asClock(%s)\n", indent, name.c_str(), clk_expr.c_str());
200 return addr_str + ena_str + clk_str;
201 }
202 };
203 struct write_port : read_port {
204 RTLIL::SigSpec mask;
205 write_port(string name, bool clk_enable, bool clk_parity, bool transparent, RTLIL::SigSpec clk, RTLIL::SigSpec ena, RTLIL::SigSpec addr, RTLIL::SigSpec mask) : read_port(name, clk_enable, clk_parity, transparent, clk, ena, addr), mask(mask) {
206 if (!clk.is_fully_def())
207 this->clk = SigSpec(RTLIL::Const(0));
208 if (!ena.is_fully_def())
209 this->ena = SigSpec(RTLIL::Const(0));
210 if (!mask.is_fully_def())
211 this->ena = SigSpec(RTLIL::Const(1));
212 }
213 string gen_read(const char * /* indent */) {
214 log_error("gen_read called on write_port: %s\n", name.c_str());
215 return stringf("gen_read called on write_port: %s\n", name.c_str());
216 }
217 string gen_write(const char * indent) {
218 string addr_expr = make_expr(addr);
219 string ena_expr = make_expr(ena);
220 string clk_expr = make_expr(clk);
221 string mask_expr = make_expr(mask);
222 string mask_str = stringf("%s%s.mask <= %s\n", indent, name.c_str(), mask_expr.c_str());
223 string addr_str = stringf("%s%s.addr <= %s\n", indent, name.c_str(), addr_expr.c_str());
224 string ena_str = stringf("%s%s.en <= %s\n", indent, name.c_str(), ena_expr.c_str());
225 string clk_str = stringf("%s%s.clk <= asClock(%s)\n", indent, name.c_str(), clk_expr.c_str());
226 return addr_str + ena_str + clk_str + mask_str;
227 }
228 };
229 /* Memories defined within this module. */
230 struct memory {
231 Cell *pCell; // for error reporting
232 string name; // memory name
233 int abits; // number of address bits
234 int size; // size (in units) of the memory
235 int width; // size (in bits) of each element
236 int read_latency;
237 int write_latency;
238 vector<read_port> read_ports;
239 vector<write_port> write_ports;
240 std::string init_file;
241 std::string init_file_srcFileSpec;
242 string srcLine;
243 memory(Cell *pCell, string name, int abits, int size, int width) : pCell(pCell), name(name), abits(abits), size(size), width(width), read_latency(0), write_latency(1), init_file(""), init_file_srcFileSpec("") {
244 // Provide defaults for abits or size if one (but not the other) is specified.
245 if (this->abits == 0 && this->size != 0) {
246 this->abits = ceil_log2(this->size);
247 } else if (this->abits != 0 && this->size == 0) {
248 this->size = 1 << this->abits;
249 }
250 // Sanity-check this construction.
251 if (this->name == "") {
252 log_error("Nameless memory%s\n", this->atLine());
253 }
254 if (this->abits == 0 && this->size == 0) {
255 log_error("Memory %s has zero address bits and size%s\n", this->name.c_str(), this->atLine());
256 }
257 if (this->width == 0) {
258 log_error("Memory %s has zero width%s\n", this->name.c_str(), this->atLine());
259 }
260 }
261 // We need a default constructor for the dict insert.
262 memory() : pCell(0), read_latency(0), write_latency(1), init_file(""), init_file_srcFileSpec(""){}
263
264 const char *atLine() {
265 if (srcLine == "") {
266 if (pCell) {
267 auto p = pCell->attributes.find("\\src");
268 srcLine = " at " + p->second.decode_string();
269 }
270 }
271 return srcLine.c_str();
272 }
273 void add_memory_read_port(read_port &rp) {
274 read_ports.push_back(rp);
275 }
276 void add_memory_write_port(write_port &wp) {
277 write_ports.push_back(wp);
278 }
279 void add_memory_file(std::string init_file, std::string init_file_srcFileSpec) {
280 this->init_file = init_file;
281 this->init_file_srcFileSpec = init_file_srcFileSpec;
282 }
283
284 };
285 dict<string, memory> memories;
286
287 void register_memory(memory &m)
288 {
289 memories[m.name] = m;
290 }
291
292 void register_reverse_wire_map(string id, SigSpec sig)
293 {
294 for (int i = 0; i < GetSize(sig); i++)
295 reverse_wire_map[sig[i]] = make_pair(id, i);
296 }
297
298 FirrtlWorker(Module *module, std::ostream &f, RTLIL::Design *theDesign) : module(module), f(f), design(theDesign), indent(" ")
299 {
300 }
301
302 static string make_expr(const SigSpec &sig)
303 {
304 string expr;
305
306 for (auto chunk : sig.chunks())
307 {
308 string new_expr;
309
310 if (chunk.wire == nullptr)
311 {
312 std::vector<RTLIL::State> bits = chunk.data;
313 new_expr = stringf("UInt<%d>(\"h", GetSize(bits));
314
315 while (GetSize(bits) % 4 != 0)
316 bits.push_back(State::S0);
317
318 for (int i = GetSize(bits)-4; i >= 0; i -= 4)
319 {
320 int val = 0;
321 if (bits[i+0] == State::S1) val += 1;
322 if (bits[i+1] == State::S1) val += 2;
323 if (bits[i+2] == State::S1) val += 4;
324 if (bits[i+3] == State::S1) val += 8;
325 new_expr.push_back(val < 10 ? '0' + val : 'a' + val - 10);
326 }
327
328 new_expr += "\")";
329 }
330 else if (chunk.offset == 0 && chunk.width == chunk.wire->width)
331 {
332 new_expr = make_id(chunk.wire->name);
333 }
334 else
335 {
336 string wire_id = make_id(chunk.wire->name);
337 new_expr = stringf("bits(%s, %d, %d)", wire_id.c_str(), chunk.offset + chunk.width - 1, chunk.offset);
338 }
339
340 if (expr.empty())
341 expr = new_expr;
342 else
343 expr = "cat(" + new_expr + ", " + expr + ")";
344 }
345
346 return expr;
347 }
348
349 std::string fid(RTLIL::IdString internal_id)
350 {
351 return make_id(internal_id);
352 }
353
354 std::string cellname(RTLIL::Cell *cell)
355 {
356 return fid(cell->name).c_str();
357 }
358
359 void process_instance(RTLIL::Cell *cell, vector<string> &wire_exprs)
360 {
361 std::string cell_type = fid(cell->type);
362 std::string instanceOf;
363 // If this is a parameterized module, its parent module is encoded in the cell type
364 if (cell->type.begins_with("$paramod"))
365 {
366 std::string::iterator it;
367 for (it = cell_type.begin(); it < cell_type.end(); it++)
368 {
369 switch (*it) {
370 case '\\': /* FALL_THROUGH */
371 case '=': /* FALL_THROUGH */
372 case '\'': /* FALL_THROUGH */
373 case '$': instanceOf.append("_"); break;
374 default: instanceOf.append(1, *it); break;
375 }
376 }
377 }
378 else
379 {
380 instanceOf = cell_type;
381 }
382
383 std::string cell_name = cellname(cell);
384 std::string cell_name_comment;
385 if (cell_name != fid(cell->name))
386 cell_name_comment = " /* " + fid(cell->name) + " */ ";
387 else
388 cell_name_comment = "";
389 // Find the module corresponding to this instance.
390 auto instModule = design->module(cell->type);
391 // If there is no instance for this, just return.
392 if (instModule == NULL)
393 {
394 log_warning("No instance for %s.%s\n", cell_type.c_str(), cell_name.c_str());
395 return;
396 }
397 auto cellFileinfo = getFileinfo(cell->attributes);
398 wire_exprs.push_back(stringf("%s" "inst %s%s of %s @[%s]", indent.c_str(), cell_name.c_str(), cell_name_comment.c_str(), instanceOf.c_str(), cellFileinfo.c_str()));
399
400 for (auto it = cell->connections().begin(); it != cell->connections().end(); ++it) {
401 if (it->second.size() > 0) {
402 const SigSpec &secondSig = it->second;
403 const std::string firstName = cell_name + "." + make_id(it->first);
404 const std::string secondExpr = make_expr(secondSig);
405 // Find the direction for this port.
406 FDirection dir = getPortFDirection(it->first, instModule);
407 std::string sourceExpr, sinkExpr;
408 const SigSpec *sinkSig = nullptr;
409 switch (dir) {
410 case FD_INOUT:
411 log_warning("Instance port connection %s.%s is INOUT; treating as OUT\n", cell_type.c_str(), log_signal(it->second));
412 /* FALLTHRU */
413 case FD_OUT:
414 sourceExpr = firstName;
415 sinkExpr = secondExpr;
416 sinkSig = &secondSig;
417 break;
418 case FD_NODIRECTION:
419 log_warning("Instance port connection %s.%s is NODIRECTION; treating as IN\n", cell_type.c_str(), log_signal(it->second));
420 /* FALLTHRU */
421 case FD_IN:
422 sourceExpr = secondExpr;
423 sinkExpr = firstName;
424 break;
425 default:
426 log_error("Instance port %s.%s unrecognized connection direction 0x%x !\n", cell_type.c_str(), log_signal(it->second), dir);
427 break;
428 }
429 // Check for subfield assignment.
430 std::string bitsString = "bits(";
431 if (sinkExpr.compare(0, bitsString.length(), bitsString) == 0) {
432 if (sinkSig == nullptr)
433 log_error("Unknown subfield %s.%s\n", cell_type.c_str(), sinkExpr.c_str());
434 // Don't generate the assignment here.
435 // Add the source and sink to the "reverse_wire_map" and we'll output the assignment
436 // as part of the coalesced subfield assignments for this wire.
437 register_reverse_wire_map(sourceExpr, *sinkSig);
438 } else {
439 wire_exprs.push_back(stringf("\n%s%s <= %s @[%s]", indent.c_str(), sinkExpr.c_str(), sourceExpr.c_str(), cellFileinfo.c_str()));
440 }
441 }
442 }
443 wire_exprs.push_back(stringf("\n"));
444
445 }
446
447 // Given an expression for a shift amount, and a maximum width,
448 // generate the FIRRTL expression for equivalent dynamic shift taking into account FIRRTL shift semantics.
449 std::string gen_dshl(const string b_expr, const int b_width)
450 {
451 string result = b_expr;
452 if (b_width >= FIRRTL_MAX_DSH_WIDTH_ERROR) {
453 int max_shift_width_bits = FIRRTL_MAX_DSH_WIDTH_ERROR - 1;
454 string max_shift_string = stringf("UInt<%d>(%d)", max_shift_width_bits, (1<<max_shift_width_bits) - 1);
455 // Deal with the difference in semantics between FIRRTL and verilog
456 result = stringf("mux(gt(%s, %s), %s, bits(%s, %d, 0))", b_expr.c_str(), max_shift_string.c_str(), max_shift_string.c_str(), b_expr.c_str(), max_shift_width_bits - 1);
457 }
458 return result;
459 }
460
461 void run()
462 {
463 auto moduleFileinfo = getFileinfo(module->attributes);
464 f << stringf(" module %s: @[%s]\n", make_id(module->name), moduleFileinfo.c_str());
465 vector<string> port_decls, wire_decls, cell_exprs, wire_exprs;
466
467 for (auto wire : module->wires())
468 {
469 const auto wireName = make_id(wire->name);
470 auto wireFileinfo = getFileinfo(wire->attributes);
471
472 // If a wire has initial data, issue a warning since FIRRTL doesn't currently support it.
473 if (wire->attributes.count("\\init")) {
474 log_warning("Initial value (%s) for (%s.%s) not supported\n",
475 wire->attributes.at("\\init").as_string().c_str(),
476 log_id(module), log_id(wire));
477 }
478 if (wire->port_id)
479 {
480 if (wire->port_input && wire->port_output)
481 log_error("Module port %s.%s is inout!\n", log_id(module), log_id(wire));
482 port_decls.push_back(stringf(" %s %s: UInt<%d> @[%s]\n", wire->port_input ? "input" : "output",
483 wireName, wire->width, wireFileinfo.c_str()));
484 }
485 else
486 {
487 wire_decls.push_back(stringf(" wire %s: UInt<%d> @[%s]\n", wireName, wire->width, wireFileinfo.c_str()));
488 }
489 }
490
491 for (auto cell : module->cells())
492 {
493 static Const ndef(0, 0);
494
495 // Is this cell is a module instance?
496 if (cell->type[0] != '$')
497 {
498 process_instance(cell, wire_exprs);
499 continue;
500 }
501 // Not a module instance. Set up cell properties
502 bool extract_y_bits = false; // Assume no extraction of final bits will be required.
503 int a_width = cell->parameters.at("\\A_WIDTH", ndef).as_int(); // The width of "A"
504 int b_width = cell->parameters.at("\\B_WIDTH", ndef).as_int(); // The width of "A"
505 const int y_width = cell->parameters.at("\\Y_WIDTH", ndef).as_int(); // The width of the result
506 const bool a_signed = cell->parameters.at("\\A_SIGNED", ndef).as_bool();
507 const bool b_signed = cell->parameters.at("\\B_SIGNED", ndef).as_bool();
508 bool firrtl_is_signed = a_signed; // The result is signed (subsequent code may change this).
509 int firrtl_width = 0;
510 string primop;
511 bool always_uint = false;
512 string y_id = make_id(cell->name);
513
514 if (cell->type.in("$not", "$logic_not", "$neg", "$reduce_and", "$reduce_or", "$reduce_xor", "$reduce_bool", "$reduce_xnor"))
515 {
516 string a_expr = make_expr(cell->getPort("\\A"));
517 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
518
519 if (a_signed) {
520 a_expr = "asSInt(" + a_expr + ")";
521 }
522
523 // Don't use the results of logical operations (a single bit) to control padding
524 if (!(cell->type.in("$eq", "$eqx", "$gt", "$ge", "$lt", "$le", "$ne", "$nex", "$reduce_bool", "$logic_not") && y_width == 1) ) {
525 a_expr = stringf("pad(%s, %d)", a_expr.c_str(), y_width);
526 }
527
528 // Assume the FIRRTL width is a single bit.
529 firrtl_width = 1;
530 if (cell->type == "$not") primop = "not";
531 else if (cell->type == "$neg") {
532 primop = "neg";
533 firrtl_is_signed = true; // Result of "neg" is signed (an SInt).
534 firrtl_width = a_width;
535 } else if (cell->type == "$logic_not") {
536 primop = "eq";
537 a_expr = stringf("%s, UInt(0)", a_expr.c_str());
538 }
539 else if (cell->type == "$reduce_and") primop = "andr";
540 else if (cell->type == "$reduce_or") primop = "orr";
541 else if (cell->type == "$reduce_xor") primop = "xorr";
542 else if (cell->type == "$reduce_xnor") {
543 primop = "not";
544 a_expr = stringf("xorr(%s)", a_expr.c_str());
545 }
546 else if (cell->type == "$reduce_bool") {
547 primop = "neq";
548 // Use the sign of the a_expr and its width as the type (UInt/SInt) and width of the comparand.
549 a_expr = stringf("%s, %cInt<%d>(0)", a_expr.c_str(), a_signed ? 'S' : 'U', a_width);
550 }
551
552 string expr = stringf("%s(%s)", primop.c_str(), a_expr.c_str());
553
554 if ((firrtl_is_signed && !always_uint))
555 expr = stringf("asUInt(%s)", expr.c_str());
556
557 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
558 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
559
560 continue;
561 }
562 if (cell->type.in("$add", "$sub", "$mul", "$div", "$mod", "$xor", "$xnor", "$and", "$or", "$eq", "$eqx",
563 "$gt", "$ge", "$lt", "$le", "$ne", "$nex", "$shr", "$sshr", "$sshl", "$shl",
564 "$logic_and", "$logic_or", "$pow"))
565 {
566 string a_expr = make_expr(cell->getPort("\\A"));
567 string b_expr = make_expr(cell->getPort("\\B"));
568 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
569
570 if (a_signed) {
571 a_expr = "asSInt(" + a_expr + ")";
572 // Expand the "A" operand to the result width
573 if (a_width < y_width) {
574 a_expr = stringf("pad(%s, %d)", a_expr.c_str(), y_width);
575 a_width = y_width;
576 }
577 }
578 // Shift amount is always unsigned, and needn't be padded to result width,
579 // otherwise, we need to cast the b_expr appropriately
580 if (b_signed && !cell->type.in("$shr", "$sshr", "$shl", "$sshl", "$pow")) {
581 b_expr = "asSInt(" + b_expr + ")";
582 // Expand the "B" operand to the result width
583 if (b_width < y_width) {
584 b_expr = stringf("pad(%s, %d)", b_expr.c_str(), y_width);
585 b_width = y_width;
586 }
587 }
588
589 // For the arithmetic ops, expand operand widths to result widths befor performing the operation.
590 // This corresponds (according to iverilog) to what verilog compilers implement.
591 if (cell->type.in("$add", "$sub", "$mul", "$div", "$mod", "$xor", "$xnor", "$and", "$or"))
592 {
593 if (a_width < y_width) {
594 a_expr = stringf("pad(%s, %d)", a_expr.c_str(), y_width);
595 a_width = y_width;
596 }
597 if (b_width < y_width) {
598 b_expr = stringf("pad(%s, %d)", b_expr.c_str(), y_width);
599 b_width = y_width;
600 }
601 }
602 // Assume the FIRRTL width is the width of "A"
603 firrtl_width = a_width;
604 auto a_sig = cell->getPort("\\A");
605
606 if (cell->type == "$add") {
607 primop = "add";
608 firrtl_is_signed = a_signed | b_signed;
609 firrtl_width = max(a_width, b_width);
610 } else if (cell->type == "$sub") {
611 primop = "sub";
612 firrtl_is_signed = true;
613 int a_widthInc = (!a_signed && b_signed) ? 2 : (a_signed && !b_signed) ? 1 : 0;
614 int b_widthInc = (a_signed && !b_signed) ? 2 : (!a_signed && b_signed) ? 1 : 0;
615 firrtl_width = max(a_width + a_widthInc, b_width + b_widthInc);
616 } else if (cell->type == "$mul") {
617 primop = "mul";
618 firrtl_is_signed = a_signed | b_signed;
619 firrtl_width = a_width + b_width;
620 } else if (cell->type == "$div") {
621 primop = "div";
622 firrtl_is_signed = a_signed | b_signed;
623 firrtl_width = a_width;
624 } else if (cell->type == "$mod") {
625 primop = "rem";
626 firrtl_width = min(a_width, b_width);
627 } else if (cell->type == "$and") {
628 primop = "and";
629 always_uint = true;
630 firrtl_width = max(a_width, b_width);
631 }
632 else if (cell->type == "$or" ) {
633 primop = "or";
634 always_uint = true;
635 firrtl_width = max(a_width, b_width);
636 }
637 else if (cell->type == "$xor") {
638 primop = "xor";
639 always_uint = true;
640 firrtl_width = max(a_width, b_width);
641 }
642 else if (cell->type == "$xnor") {
643 primop = "xnor";
644 always_uint = true;
645 firrtl_width = max(a_width, b_width);
646 }
647 else if ((cell->type == "$eq") | (cell->type == "$eqx")) {
648 primop = "eq";
649 always_uint = true;
650 firrtl_width = 1;
651 }
652 else if ((cell->type == "$ne") | (cell->type == "$nex")) {
653 primop = "neq";
654 always_uint = true;
655 firrtl_width = 1;
656 }
657 else if (cell->type == "$gt") {
658 primop = "gt";
659 always_uint = true;
660 firrtl_width = 1;
661 }
662 else if (cell->type == "$ge") {
663 primop = "geq";
664 always_uint = true;
665 firrtl_width = 1;
666 }
667 else if (cell->type == "$lt") {
668 primop = "lt";
669 always_uint = true;
670 firrtl_width = 1;
671 }
672 else if (cell->type == "$le") {
673 primop = "leq";
674 always_uint = true;
675 firrtl_width = 1;
676 }
677 else if ((cell->type == "$shl") | (cell->type == "$sshl")) {
678 // FIRRTL will widen the result (y) by the amount of the shift.
679 // We'll need to offset this by extracting the un-widened portion as Verilog would do.
680 extract_y_bits = true;
681 // Is the shift amount constant?
682 auto b_sig = cell->getPort("\\B");
683 if (b_sig.is_fully_const()) {
684 primop = "shl";
685 int shift_amount = b_sig.as_int();
686 b_expr = std::to_string(shift_amount);
687 firrtl_width = a_width + shift_amount;
688 } else {
689 primop = "dshl";
690 // Convert from FIRRTL left shift semantics.
691 b_expr = gen_dshl(b_expr, b_width);
692 firrtl_width = a_width + (1 << b_width) - 1;
693 }
694 }
695 else if ((cell->type == "$shr") | (cell->type == "$sshr")) {
696 // We don't need to extract a specific range of bits.
697 extract_y_bits = false;
698 // Is the shift amount constant?
699 auto b_sig = cell->getPort("\\B");
700 if (b_sig.is_fully_const()) {
701 primop = "shr";
702 int shift_amount = b_sig.as_int();
703 b_expr = std::to_string(shift_amount);
704 firrtl_width = max(1, a_width - shift_amount);
705 } else {
706 primop = "dshr";
707 firrtl_width = a_width;
708 }
709 // We'll need to do some special fixups if the source (and thus result) is signed.
710 if (firrtl_is_signed) {
711 // If this is a "logical" shift right, pretend the source is unsigned.
712 if (cell->type == "$shr") {
713 a_expr = "asUInt(" + a_expr + ")";
714 }
715 }
716 }
717 else if ((cell->type == "$logic_and")) {
718 primop = "and";
719 a_expr = "neq(" + a_expr + ", UInt(0))";
720 b_expr = "neq(" + b_expr + ", UInt(0))";
721 always_uint = true;
722 firrtl_width = 1;
723 }
724 else if ((cell->type == "$logic_or")) {
725 primop = "or";
726 a_expr = "neq(" + a_expr + ", UInt(0))";
727 b_expr = "neq(" + b_expr + ", UInt(0))";
728 always_uint = true;
729 firrtl_width = 1;
730 }
731 else if ((cell->type == "$pow")) {
732 if (a_sig.is_fully_const() && a_sig.as_int() == 2) {
733 // We'll convert this to a shift. To simplify things, change the a_expr to "1"
734 // so we can use b_expr directly as a shift amount.
735 // Only support 2 ** N (i.e., shift left)
736 // FIRRTL will widen the result (y) by the amount of the shift.
737 // We'll need to offset this by extracting the un-widened portion as Verilog would do.
738 a_expr = firrtl_is_signed ? "SInt(1)" : "UInt(1)";
739 extract_y_bits = true;
740 // Is the shift amount constant?
741 auto b_sig = cell->getPort("\\B");
742 if (b_sig.is_fully_const()) {
743 primop = "shl";
744 int shiftAmount = b_sig.as_int();
745 if (shiftAmount < 0) {
746 log_error("Negative power exponent - %d: %s.%s\n", shiftAmount, log_id(module), log_id(cell));
747 }
748 b_expr = std::to_string(shiftAmount);
749 firrtl_width = a_width + shiftAmount;
750 } else {
751 primop = "dshl";
752 // Convert from FIRRTL left shift semantics.
753 b_expr = gen_dshl(b_expr, b_width);
754 firrtl_width = a_width + (1 << b_width) - 1;
755 }
756 } else {
757 log_error("Non power 2: %s.%s\n", log_id(module), log_id(cell));
758 }
759 }
760
761 if (!cell->parameters.at("\\B_SIGNED").as_bool()) {
762 b_expr = "asUInt(" + b_expr + ")";
763 }
764
765 string expr;
766 // Deal with $xnor == ~^ (not xor)
767 if (primop == "xnor") {
768 expr = stringf("not(xor(%s, %s))", a_expr.c_str(), b_expr.c_str());
769 } else {
770 expr = stringf("%s(%s, %s)", primop.c_str(), a_expr.c_str(), b_expr.c_str());
771 }
772
773 // Deal with FIRRTL's "shift widens" semantics, or the need to widen the FIRRTL result.
774 // If the operation is signed, the FIRRTL width will be 1 one bit larger.
775 if (extract_y_bits) {
776 expr = stringf("bits(%s, %d, 0)", expr.c_str(), y_width - 1);
777 } else if (firrtl_is_signed && (firrtl_width + 1) < y_width) {
778 expr = stringf("pad(%s, %d)", expr.c_str(), y_width);
779 }
780
781 if ((firrtl_is_signed && !always_uint))
782 expr = stringf("asUInt(%s)", expr.c_str());
783
784 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
785 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
786
787 continue;
788 }
789
790 if (cell->type.in("$mux"))
791 {
792 int width = cell->parameters.at("\\WIDTH").as_int();
793 string a_expr = make_expr(cell->getPort("\\A"));
794 string b_expr = make_expr(cell->getPort("\\B"));
795 string s_expr = make_expr(cell->getPort("\\S"));
796 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), width));
797
798 string expr = stringf("mux(%s, %s, %s)", s_expr.c_str(), b_expr.c_str(), a_expr.c_str());
799
800 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
801 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
802
803 continue;
804 }
805
806 if (cell->type.in("$mem"))
807 {
808 string mem_id = make_id(cell->name);
809 int abits = cell->parameters.at("\\ABITS").as_int();
810 int width = cell->parameters.at("\\WIDTH").as_int();
811 int size = cell->parameters.at("\\SIZE").as_int();
812 memory m(cell, mem_id, abits, size, width);
813 int rd_ports = cell->parameters.at("\\RD_PORTS").as_int();
814 int wr_ports = cell->parameters.at("\\WR_PORTS").as_int();
815
816 Const initdata = cell->parameters.at("\\INIT");
817 for (State bit : initdata.bits)
818 if (bit != State::Sx)
819 log_error("Memory with initialization data: %s.%s\n", log_id(module), log_id(cell));
820
821 Const rd_clk_enable = cell->parameters.at("\\RD_CLK_ENABLE");
822 Const wr_clk_enable = cell->parameters.at("\\WR_CLK_ENABLE");
823 Const wr_clk_polarity = cell->parameters.at("\\WR_CLK_POLARITY");
824
825 int offset = cell->parameters.at("\\OFFSET").as_int();
826 if (offset != 0)
827 log_error("Memory with nonzero offset: %s.%s\n", log_id(module), log_id(cell));
828
829 for (int i = 0; i < rd_ports; i++)
830 {
831 if (rd_clk_enable[i] != State::S0)
832 log_error("Clocked read port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
833
834 SigSpec addr_sig = cell->getPort("\\RD_ADDR").extract(i*abits, abits);
835 SigSpec data_sig = cell->getPort("\\RD_DATA").extract(i*width, width);
836 string addr_expr = make_expr(addr_sig);
837 string name(stringf("%s.r%d", m.name.c_str(), i));
838 bool clk_enable = false;
839 bool clk_parity = true;
840 bool transparency = false;
841 SigSpec ena_sig = RTLIL::SigSpec(RTLIL::State::S1, 1);
842 SigSpec clk_sig = RTLIL::SigSpec(RTLIL::State::S0, 1);
843 read_port rp(name, clk_enable, clk_parity, transparency, clk_sig, ena_sig, addr_sig);
844 m.add_memory_read_port(rp);
845 cell_exprs.push_back(rp.gen_read(indent.c_str()));
846 register_reverse_wire_map(stringf("%s.data", name.c_str()), data_sig);
847 }
848
849 for (int i = 0; i < wr_ports; i++)
850 {
851 if (wr_clk_enable[i] != State::S1)
852 log_error("Unclocked write port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
853
854 if (wr_clk_polarity[i] != State::S1)
855 log_error("Negedge write port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
856
857 string name(stringf("%s.w%d", m.name.c_str(), i));
858 bool clk_enable = true;
859 bool clk_parity = true;
860 bool transparency = false;
861 SigSpec addr_sig =cell->getPort("\\WR_ADDR").extract(i*abits, abits);
862 string addr_expr = make_expr(addr_sig);
863 SigSpec data_sig =cell->getPort("\\WR_DATA").extract(i*width, width);
864 string data_expr = make_expr(data_sig);
865 SigSpec clk_sig = cell->getPort("\\WR_CLK").extract(i);
866 string clk_expr = make_expr(clk_sig);
867
868 SigSpec wen_sig = cell->getPort("\\WR_EN").extract(i*width, width);
869 string wen_expr = make_expr(wen_sig[0]);
870
871 for (int i = 1; i < GetSize(wen_sig); i++)
872 if (wen_sig[0] != wen_sig[i])
873 log_error("Complex write enable on port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
874
875 SigSpec mask_sig = RTLIL::SigSpec(RTLIL::State::S1, 1);
876 write_port wp(name, clk_enable, clk_parity, transparency, clk_sig, wen_sig[0], addr_sig, mask_sig);
877 m.add_memory_write_port(wp);
878 cell_exprs.push_back(stringf("%s%s.data <= %s\n", indent.c_str(), name.c_str(), data_expr.c_str()));
879 cell_exprs.push_back(wp.gen_write(indent.c_str()));
880 }
881 register_memory(m);
882 continue;
883 }
884
885 if (cell->type.in("$memwr", "$memrd", "$meminit"))
886 {
887 std::string cell_type = fid(cell->type);
888 std::string mem_id = make_id(cell->parameters["\\MEMID"].decode_string());
889 int abits = cell->parameters.at("\\ABITS").as_int();
890 int width = cell->parameters.at("\\WIDTH").as_int();
891 memory *mp = nullptr;
892 if (cell->type == "$meminit" ) {
893 log_error("$meminit (%s.%s.%s) currently unsupported\n", log_id(module), log_id(cell), mem_id.c_str());
894 } else {
895 // It's a $memwr or $memrd. Remember the read/write port parameters for the eventual FIRRTL memory definition.
896 auto addrSig = cell->getPort("\\ADDR");
897 auto dataSig = cell->getPort("\\DATA");
898 auto enableSig = cell->getPort("\\EN");
899 auto clockSig = cell->getPort("\\CLK");
900 Const clk_enable = cell->parameters.at("\\CLK_ENABLE");
901 Const clk_polarity = cell->parameters.at("\\CLK_POLARITY");
902
903 // Do we already have an entry for this memory?
904 if (memories.count(mem_id) == 0) {
905 memory m(cell, mem_id, abits, 0, width);
906 register_memory(m);
907 }
908 mp = &memories.at(mem_id);
909 int portNum = 0;
910 bool transparency = false;
911 string data_expr = make_expr(dataSig);
912 if (cell->type.in("$memwr")) {
913 portNum = (int) mp->write_ports.size();
914 write_port wp(stringf("%s.w%d", mem_id.c_str(), portNum), clk_enable.as_bool(), clk_polarity.as_bool(), transparency, clockSig, enableSig, addrSig, dataSig);
915 mp->add_memory_write_port(wp);
916 cell_exprs.push_back(stringf("%s%s.data <= %s\n", indent.c_str(), wp.name.c_str(), data_expr.c_str()));
917 cell_exprs.push_back(wp.gen_write(indent.c_str()));
918 } else if (cell->type.in("$memrd")) {
919 portNum = (int) mp->read_ports.size();
920 read_port rp(stringf("%s.r%d", mem_id.c_str(), portNum), clk_enable.as_bool(), clk_polarity.as_bool(), transparency, clockSig, enableSig, addrSig);
921 mp->add_memory_read_port(rp);
922 cell_exprs.push_back(rp.gen_read(indent.c_str()));
923 register_reverse_wire_map(stringf("%s.data", rp.name.c_str()), dataSig);
924 }
925 }
926 continue;
927 }
928
929 if (cell->type.in("$dff"))
930 {
931 bool clkpol = cell->parameters.at("\\CLK_POLARITY").as_bool();
932 if (clkpol == false)
933 log_error("Negative edge clock on FF %s.%s.\n", log_id(module), log_id(cell));
934
935 int width = cell->parameters.at("\\WIDTH").as_int();
936 string expr = make_expr(cell->getPort("\\D"));
937 string clk_expr = "asClock(" + make_expr(cell->getPort("\\CLK")) + ")";
938
939 wire_decls.push_back(stringf(" reg %s: UInt<%d>, %s\n", y_id.c_str(), width, clk_expr.c_str()));
940
941 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
942 register_reverse_wire_map(y_id, cell->getPort("\\Q"));
943
944 continue;
945 }
946
947 // This may be a parameterized module - paramod.
948 if (cell->type.begins_with("$paramod"))
949 {
950 process_instance(cell, wire_exprs);
951 continue;
952 }
953 if (cell->type == "$shiftx") {
954 // assign y = a[b +: y_width];
955 // We'll extract the correct bits as part of the primop.
956
957 string a_expr = make_expr(cell->getPort("\\A"));
958 // Get the initial bit selector
959 string b_expr = make_expr(cell->getPort("\\B"));
960 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
961
962 if (cell->getParam("\\B_SIGNED").as_bool()) {
963 // Use validif to constrain the selection (test the sign bit)
964 auto b_string = b_expr.c_str();
965 int b_sign = cell->parameters.at("\\B_WIDTH").as_int() - 1;
966 b_expr = stringf("validif(not(bits(%s, %d, %d)), %s)", b_string, b_sign, b_sign, b_string);
967 }
968 string expr = stringf("dshr(%s, %s)", a_expr.c_str(), b_expr.c_str());
969
970 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
971 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
972 continue;
973 }
974 if (cell->type == "$shift") {
975 // assign y = a >> b;
976 // where b may be negative
977
978 string a_expr = make_expr(cell->getPort("\\A"));
979 string b_expr = make_expr(cell->getPort("\\B"));
980 auto b_string = b_expr.c_str();
981 string expr;
982 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
983
984 if (cell->getParam("\\B_SIGNED").as_bool()) {
985 // We generate a left or right shift based on the sign of b.
986 std::string dshl = stringf("bits(dshl(%s, %s), 0, %d)", a_expr.c_str(), gen_dshl(b_expr, b_width).c_str(), y_width);
987 std::string dshr = stringf("dshr(%s, %s)", a_expr.c_str(), b_string);
988 expr = stringf("mux(%s < 0, %s, %s)",
989 b_string,
990 dshl.c_str(),
991 dshr.c_str()
992 );
993 } else {
994 expr = stringf("dshr(%s, %s)", a_expr.c_str(), b_string);
995 }
996 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
997 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
998 continue;
999 }
1000 if (cell->type == "$pos") {
1001 // assign y = a;
1002 // printCell(cell);
1003 string a_expr = make_expr(cell->getPort("\\A"));
1004 // Verilog appears to treat the result as signed, so if the result is wider than "A",
1005 // we need to pad.
1006 if (a_width < y_width) {
1007 a_expr = stringf("pad(%s, %d)", a_expr.c_str(), y_width);
1008 }
1009 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
1010 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), a_expr.c_str()));
1011 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
1012 continue;
1013 }
1014 log_error("Cell type not supported: %s (%s.%s)\n", log_id(cell->type), log_id(module), log_id(cell));
1015 }
1016
1017 for (auto conn : module->connections())
1018 {
1019 string y_id = next_id();
1020 int y_width = GetSize(conn.first);
1021 string expr = make_expr(conn.second);
1022
1023 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
1024 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
1025 register_reverse_wire_map(y_id, conn.first);
1026 }
1027
1028 for (auto wire : module->wires())
1029 {
1030 string expr;
1031
1032 if (wire->port_input)
1033 continue;
1034
1035 int cursor = 0;
1036 bool is_valid = false;
1037 bool make_unconn_id = false;
1038
1039 while (cursor < wire->width)
1040 {
1041 int chunk_width = 1;
1042 string new_expr;
1043
1044 SigBit start_bit(wire, cursor);
1045
1046 if (reverse_wire_map.count(start_bit))
1047 {
1048 pair<string, int> start_map = reverse_wire_map.at(start_bit);
1049
1050 while (cursor+chunk_width < wire->width)
1051 {
1052 SigBit stop_bit(wire, cursor+chunk_width);
1053
1054 if (reverse_wire_map.count(stop_bit) == 0)
1055 break;
1056
1057 pair<string, int> stop_map = reverse_wire_map.at(stop_bit);
1058 stop_map.second -= chunk_width;
1059
1060 if (start_map != stop_map)
1061 break;
1062
1063 chunk_width++;
1064 }
1065
1066 new_expr = stringf("bits(%s, %d, %d)", start_map.first.c_str(),
1067 start_map.second + chunk_width - 1, start_map.second);
1068 is_valid = true;
1069 }
1070 else
1071 {
1072 if (unconn_id.empty()) {
1073 unconn_id = next_id();
1074 make_unconn_id = true;
1075 }
1076 new_expr = unconn_id;
1077 }
1078
1079 if (expr.empty())
1080 expr = new_expr;
1081 else
1082 expr = "cat(" + new_expr + ", " + expr + ")";
1083
1084 cursor += chunk_width;
1085 }
1086
1087 if (is_valid) {
1088 if (make_unconn_id) {
1089 wire_decls.push_back(stringf(" wire %s: UInt<1>\n", unconn_id.c_str()));
1090 wire_decls.push_back(stringf(" %s is invalid\n", unconn_id.c_str()));
1091 }
1092 wire_exprs.push_back(stringf(" %s <= %s\n", make_id(wire->name), expr.c_str()));
1093 } else {
1094 if (make_unconn_id) {
1095 unconn_id.clear();
1096 }
1097 wire_decls.push_back(stringf(" %s is invalid\n", make_id(wire->name)));
1098 }
1099 }
1100
1101 for (auto str : port_decls)
1102 f << str;
1103
1104 f << stringf("\n");
1105
1106 for (auto str : wire_decls)
1107 f << str;
1108
1109 f << stringf("\n");
1110
1111 // If we have any memory definitions, output them.
1112 for (auto kv : memories) {
1113 memory &m = kv.second;
1114 f << stringf(" mem %s:\n", m.name.c_str());
1115 f << stringf(" data-type => UInt<%d>\n", m.width);
1116 f << stringf(" depth => %d\n", m.size);
1117 for (int i = 0; i < (int) m.read_ports.size(); i += 1) {
1118 f << stringf(" reader => r%d\n", i);
1119 }
1120 for (int i = 0; i < (int) m.write_ports.size(); i += 1) {
1121 f << stringf(" writer => w%d\n", i);
1122 }
1123 f << stringf(" read-latency => %d\n", m.read_latency);
1124 f << stringf(" write-latency => %d\n", m.write_latency);
1125 f << stringf(" read-under-write => undefined\n");
1126 }
1127 f << stringf("\n");
1128
1129 for (auto str : cell_exprs)
1130 f << str;
1131
1132 f << stringf("\n");
1133
1134 for (auto str : wire_exprs)
1135 f << str;
1136 }
1137 };
1138
1139 struct FirrtlBackend : public Backend {
1140 FirrtlBackend() : Backend("firrtl", "write design to a FIRRTL file") { }
1141 void help() YS_OVERRIDE
1142 {
1143 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1144 log("\n");
1145 log(" write_firrtl [options] [filename]\n");
1146 log("\n");
1147 log("Write a FIRRTL netlist of the current design.\n");
1148 log("The following commands are executed by this command:\n");
1149 log(" pmuxtree\n");
1150 log("\n");
1151 }
1152 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
1153 {
1154 size_t argidx = args.size(); // We aren't expecting any arguments.
1155
1156 // If we weren't explicitly passed a filename, use the last argument (if it isn't a flag).
1157 if (filename == "") {
1158 if (argidx > 0 && args[argidx - 1][0] != '-') {
1159 // extra_args and friends need to see this argument.
1160 argidx -= 1;
1161 filename = args[argidx];
1162 }
1163 }
1164 extra_args(f, filename, args, argidx);
1165
1166 if (!design->full_selection())
1167 log_cmd_error("This command only operates on fully selected designs!\n");
1168
1169 log_header(design, "Executing FIRRTL backend.\n");
1170 log_push();
1171
1172 Pass::call(design, stringf("pmuxtree"));
1173
1174 namecache.clear();
1175 autoid_counter = 0;
1176
1177 // Get the top module, or a reasonable facsimile - we need something for the circuit name.
1178 Module *top = design->top_module();
1179 Module *last = nullptr;
1180 // Generate module and wire names.
1181 for (auto module : design->modules()) {
1182 make_id(module->name);
1183 last = module;
1184 if (top == nullptr && module->get_bool_attribute("\\top")) {
1185 top = module;
1186 }
1187 for (auto wire : module->wires())
1188 if (wire->port_id)
1189 make_id(wire->name);
1190 }
1191
1192 if (top == nullptr)
1193 top = last;
1194
1195 auto circuitFileinfo = getFileinfo(top->attributes);
1196 *f << stringf("circuit %s: @[%s]\n", make_id(top->name), circuitFileinfo.c_str());
1197
1198 for (auto module : design->modules())
1199 {
1200 FirrtlWorker worker(module, *f, design);
1201 worker.run();
1202 }
1203
1204 namecache.clear();
1205 autoid_counter = 0;
1206 }
1207 } FirrtlBackend;
1208
1209 PRIVATE_NAMESPACE_END