Merge remote-tracking branch 'origin/master' into xc7srl
[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 <regex>
29 #include <vector>
30 #include <cmath>
31
32 USING_YOSYS_NAMESPACE
33 PRIVATE_NAMESPACE_BEGIN
34
35 pool<string> used_names;
36 dict<IdString, string> namecache;
37 int autoid_counter;
38
39 typedef unsigned FDirection;
40 static const FDirection FD_NODIRECTION = 0x0;
41 static const FDirection FD_IN = 0x1;
42 static const FDirection FD_OUT = 0x2;
43 static const FDirection FD_INOUT = 0x3;
44 static const int FIRRTL_MAX_DSH_WIDTH_ERROR = 20; // For historic reasons, this is actually one greater than the maximum allowed shift width
45
46 // Get a port direction with respect to a specific module.
47 FDirection getPortFDirection(IdString id, Module *module)
48 {
49 Wire *wire = module->wires_.at(id);
50 FDirection direction = FD_NODIRECTION;
51 if (wire && wire->port_id)
52 {
53 if (wire->port_input)
54 direction |= FD_IN;
55 if (wire->port_output)
56 direction |= FD_OUT;
57 }
58 return direction;
59 }
60
61 string next_id()
62 {
63 string new_id;
64
65 while (1) {
66 new_id = stringf("_%d", autoid_counter++);
67 if (used_names.count(new_id) == 0) break;
68 }
69
70 used_names.insert(new_id);
71 return new_id;
72 }
73
74 const char *make_id(IdString id)
75 {
76 if (namecache.count(id) != 0)
77 return namecache.at(id).c_str();
78
79 string new_id = log_id(id);
80
81 for (int i = 0; i < GetSize(new_id); i++)
82 {
83 char &ch = new_id[i];
84 if ('a' <= ch && ch <= 'z') continue;
85 if ('A' <= ch && ch <= 'Z') continue;
86 if ('0' <= ch && ch <= '9' && i != 0) continue;
87 if ('_' == ch) continue;
88 ch = '_';
89 }
90
91 while (used_names.count(new_id) != 0)
92 new_id += '_';
93
94 namecache[id] = new_id;
95 used_names.insert(new_id);
96 return namecache.at(id).c_str();
97 }
98
99 struct FirrtlWorker
100 {
101 Module *module;
102 std::ostream &f;
103
104 dict<SigBit, pair<string, int>> reverse_wire_map;
105 string unconn_id;
106 RTLIL::Design *design;
107 std::string indent;
108
109 // Define read/write ports and memories.
110 // We'll collect their definitions and emit the corresponding FIRRTL definitions at the appropriate point in module construction.
111 // For the moment, we don't handle $readmemh or $readmemb.
112 // These will be part of a subsequent PR.
113 struct read_port {
114 string name;
115 bool clk_enable;
116 bool clk_parity;
117 bool transparent;
118 RTLIL::SigSpec clk;
119 RTLIL::SigSpec ena;
120 RTLIL::SigSpec addr;
121 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) {
122 // Current (3/13/2019) conventions:
123 // generate a constant 0 for clock and a constant 1 for enable if they are undefined.
124 if (!clk.is_fully_def())
125 this->clk = SigSpec(RTLIL::Const(0, 1));
126 if (!ena.is_fully_def())
127 this->ena = SigSpec(RTLIL::Const(1, 1));
128 }
129 string gen_read(const char * indent) {
130 string addr_expr = make_expr(addr);
131 string ena_expr = make_expr(ena);
132 string clk_expr = make_expr(clk);
133 string addr_str = stringf("%s%s.addr <= %s\n", indent, name.c_str(), addr_expr.c_str());
134 string ena_str = stringf("%s%s.en <= %s\n", indent, name.c_str(), ena_expr.c_str());
135 string clk_str = stringf("%s%s.clk <= asClock(%s)\n", indent, name.c_str(), clk_expr.c_str());
136 return addr_str + ena_str + clk_str;
137 }
138 };
139 struct write_port : read_port {
140 RTLIL::SigSpec mask;
141 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) {
142 if (!clk.is_fully_def())
143 this->clk = SigSpec(RTLIL::Const(0));
144 if (!ena.is_fully_def())
145 this->ena = SigSpec(RTLIL::Const(0));
146 if (!mask.is_fully_def())
147 this->ena = SigSpec(RTLIL::Const(1));
148 }
149 string gen_read(const char * /* indent */) {
150 log_error("gen_read called on write_port: %s\n", name.c_str());
151 return stringf("gen_read called on write_port: %s\n", name.c_str());
152 }
153 string gen_write(const char * indent) {
154 string addr_expr = make_expr(addr);
155 string ena_expr = make_expr(ena);
156 string clk_expr = make_expr(clk);
157 string mask_expr = make_expr(mask);
158 string mask_str = stringf("%s%s.mask <= %s\n", indent, name.c_str(), mask_expr.c_str());
159 string addr_str = stringf("%s%s.addr <= %s\n", indent, name.c_str(), addr_expr.c_str());
160 string ena_str = stringf("%s%s.en <= %s\n", indent, name.c_str(), ena_expr.c_str());
161 string clk_str = stringf("%s%s.clk <= asClock(%s)\n", indent, name.c_str(), clk_expr.c_str());
162 return addr_str + ena_str + clk_str + mask_str;
163 }
164 };
165 /* Memories defined within this module. */
166 struct memory {
167 string name; // memory name
168 int abits; // number of address bits
169 int size; // size (in units) of the memory
170 int width; // size (in bits) of each element
171 int read_latency;
172 int write_latency;
173 vector<read_port> read_ports;
174 vector<write_port> write_ports;
175 std::string init_file;
176 std::string init_file_srcFileSpec;
177 memory(string name, int abits, int size, int width) : name(name), abits(abits), size(size), width(width), read_latency(0), write_latency(1), init_file(""), init_file_srcFileSpec("") {}
178 memory() : read_latency(0), write_latency(1), init_file(""), init_file_srcFileSpec(""){}
179 void add_memory_read_port(read_port &rp) {
180 read_ports.push_back(rp);
181 }
182 void add_memory_write_port(write_port &wp) {
183 write_ports.push_back(wp);
184 }
185 void add_memory_file(std::string init_file, std::string init_file_srcFileSpec) {
186 this->init_file = init_file;
187 this->init_file_srcFileSpec = init_file_srcFileSpec;
188 }
189
190 };
191 dict<string, memory> memories;
192
193 void register_memory(memory &m)
194 {
195 memories[m.name] = m;
196 }
197
198 void register_reverse_wire_map(string id, SigSpec sig)
199 {
200 for (int i = 0; i < GetSize(sig); i++)
201 reverse_wire_map[sig[i]] = make_pair(id, i);
202 }
203
204 FirrtlWorker(Module *module, std::ostream &f, RTLIL::Design *theDesign) : module(module), f(f), design(theDesign), indent(" ")
205 {
206 }
207
208 static string make_expr(const SigSpec &sig)
209 {
210 string expr;
211
212 for (auto chunk : sig.chunks())
213 {
214 string new_expr;
215
216 if (chunk.wire == nullptr)
217 {
218 std::vector<RTLIL::State> bits = chunk.data;
219 new_expr = stringf("UInt<%d>(\"h", GetSize(bits));
220
221 while (GetSize(bits) % 4 != 0)
222 bits.push_back(State::S0);
223
224 for (int i = GetSize(bits)-4; i >= 0; i -= 4)
225 {
226 int val = 0;
227 if (bits[i+0] == State::S1) val += 1;
228 if (bits[i+1] == State::S1) val += 2;
229 if (bits[i+2] == State::S1) val += 4;
230 if (bits[i+3] == State::S1) val += 8;
231 new_expr.push_back(val < 10 ? '0' + val : 'a' + val - 10);
232 }
233
234 new_expr += "\")";
235 }
236 else if (chunk.offset == 0 && chunk.width == chunk.wire->width)
237 {
238 new_expr = make_id(chunk.wire->name);
239 }
240 else
241 {
242 string wire_id = make_id(chunk.wire->name);
243 new_expr = stringf("bits(%s, %d, %d)", wire_id.c_str(), chunk.offset + chunk.width - 1, chunk.offset);
244 }
245
246 if (expr.empty())
247 expr = new_expr;
248 else
249 expr = "cat(" + new_expr + ", " + expr + ")";
250 }
251
252 return expr;
253 }
254
255 std::string fid(RTLIL::IdString internal_id)
256 {
257 return make_id(internal_id);
258 }
259
260 std::string cellname(RTLIL::Cell *cell)
261 {
262 return fid(cell->name).c_str();
263 }
264
265 void process_instance(RTLIL::Cell *cell, vector<string> &wire_exprs)
266 {
267 std::string cell_type = fid(cell->type);
268 std::string instanceOf;
269 // If this is a parameterized module, its parent module is encoded in the cell type
270 if (cell->type.substr(0, 8) == "$paramod")
271 {
272 std::string::iterator it;
273 for (it = cell_type.begin(); it < cell_type.end(); it++)
274 {
275 switch (*it) {
276 case '\\': /* FALL_THROUGH */
277 case '=': /* FALL_THROUGH */
278 case '\'': /* FALL_THROUGH */
279 case '$': instanceOf.append("_"); break;
280 default: instanceOf.append(1, *it); break;
281 }
282 }
283 }
284 else
285 {
286 instanceOf = cell_type;
287 }
288
289 std::string cell_name = cellname(cell);
290 std::string cell_name_comment;
291 if (cell_name != fid(cell->name))
292 cell_name_comment = " /* " + fid(cell->name) + " */ ";
293 else
294 cell_name_comment = "";
295 // Find the module corresponding to this instance.
296 auto instModule = design->module(cell->type);
297 // If there is no instance for this, just return.
298 if (instModule == NULL)
299 {
300 log_warning("No instance for %s.%s\n", cell_type.c_str(), cell_name.c_str());
301 return;
302 }
303 wire_exprs.push_back(stringf("%s" "inst %s%s of %s", indent.c_str(), cell_name.c_str(), cell_name_comment.c_str(), instanceOf.c_str()));
304
305 for (auto it = cell->connections().begin(); it != cell->connections().end(); ++it) {
306 if (it->second.size() > 0) {
307 const SigSpec &secondSig = it->second;
308 const std::string firstName = cell_name + "." + make_id(it->first);
309 const std::string secondExpr = make_expr(secondSig);
310 // Find the direction for this port.
311 FDirection dir = getPortFDirection(it->first, instModule);
312 std::string sourceExpr, sinkExpr;
313 const SigSpec *sinkSig = nullptr;
314 switch (dir) {
315 case FD_INOUT:
316 log_warning("Instance port connection %s.%s is INOUT; treating as OUT\n", cell_type.c_str(), log_signal(it->second));
317 case FD_OUT:
318 sourceExpr = firstName;
319 sinkExpr = secondExpr;
320 sinkSig = &secondSig;
321 break;
322 case FD_NODIRECTION:
323 log_warning("Instance port connection %s.%s is NODIRECTION; treating as IN\n", cell_type.c_str(), log_signal(it->second));
324 /* FALL_THROUGH */
325 case FD_IN:
326 sourceExpr = secondExpr;
327 sinkExpr = firstName;
328 break;
329 default:
330 log_error("Instance port %s.%s unrecognized connection direction 0x%x !\n", cell_type.c_str(), log_signal(it->second), dir);
331 break;
332 }
333 // Check for subfield assignment.
334 std::string bitsString = "bits(";
335 if (sinkExpr.substr(0, bitsString.length()) == bitsString ) {
336 if (sinkSig == nullptr)
337 log_error("Unknown subfield %s.%s\n", cell_type.c_str(), sinkExpr.c_str());
338 // Don't generate the assignment here.
339 // Add the source and sink to the "reverse_wire_map" and we'll output the assignment
340 // as part of the coalesced subfield assignments for this wire.
341 register_reverse_wire_map(sourceExpr, *sinkSig);
342 } else {
343 wire_exprs.push_back(stringf("\n%s%s <= %s", indent.c_str(), sinkExpr.c_str(), sourceExpr.c_str()));
344 }
345 }
346 }
347 wire_exprs.push_back(stringf("\n"));
348
349 }
350
351 // Given an expression for a shift amount, and a maximum width,
352 // generate the FIRRTL expression for equivalent dynamic shift taking into account FIRRTL shift semantics.
353 std::string gen_dshl(const string b_expr, const int b_padded_width)
354 {
355 string result = b_expr;
356 if (b_padded_width >= FIRRTL_MAX_DSH_WIDTH_ERROR) {
357 int max_shift_width_bits = FIRRTL_MAX_DSH_WIDTH_ERROR - 1;
358 string max_shift_string = stringf("UInt<%d>(%d)", max_shift_width_bits, (1<<max_shift_width_bits) - 1);
359 // Deal with the difference in semantics between FIRRTL and verilog
360 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);
361 }
362 return result;
363 }
364
365 void run()
366 {
367 f << stringf(" module %s:\n", make_id(module->name));
368 vector<string> port_decls, wire_decls, cell_exprs, wire_exprs;
369
370 for (auto wire : module->wires())
371 {
372 const auto wireName = make_id(wire->name);
373 // If a wire has initial data, issue a warning since FIRRTL doesn't currently support it.
374 if (wire->attributes.count("\\init")) {
375 log_warning("Initial value (%s) for (%s.%s) not supported\n",
376 wire->attributes.at("\\init").as_string().c_str(),
377 log_id(module), log_id(wire));
378 }
379 if (wire->port_id)
380 {
381 if (wire->port_input && wire->port_output)
382 log_error("Module port %s.%s is inout!\n", log_id(module), log_id(wire));
383 port_decls.push_back(stringf(" %s %s: UInt<%d>\n", wire->port_input ? "input" : "output",
384 wireName, wire->width));
385 }
386 else
387 {
388 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", wireName, wire->width));
389 }
390 }
391
392 for (auto cell : module->cells())
393 {
394 bool extract_y_bits = false; // Assume no extraction of final bits will be required.
395 // Is this cell is a module instance?
396 if (cell->type[0] != '$')
397 {
398 process_instance(cell, wire_exprs);
399 continue;
400 }
401 if (cell->type.in("$not", "$logic_not", "$neg", "$reduce_and", "$reduce_or", "$reduce_xor", "$reduce_bool", "$reduce_xnor"))
402 {
403 string y_id = make_id(cell->name);
404 bool is_signed = cell->parameters.at("\\A_SIGNED").as_bool();
405 int y_width = cell->parameters.at("\\Y_WIDTH").as_int();
406 string a_expr = make_expr(cell->getPort("\\A"));
407 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
408
409 if (cell->parameters.at("\\A_SIGNED").as_bool()) {
410 a_expr = "asSInt(" + a_expr + ")";
411 }
412
413 // Don't use the results of logical operations (a single bit) to control padding
414 if (!(cell->type.in("$eq", "$eqx", "$gt", "$ge", "$lt", "$le", "$ne", "$nex", "$reduce_bool", "$logic_not") && y_width == 1) ) {
415 a_expr = stringf("pad(%s, %d)", a_expr.c_str(), y_width);
416 }
417
418 string primop;
419 bool always_uint = false;
420 if (cell->type == "$not") primop = "not";
421 else if (cell->type == "$neg") primop = "neg";
422 else if (cell->type == "$logic_not") {
423 primop = "eq";
424 a_expr = stringf("%s, UInt(0)", a_expr.c_str());
425 }
426 else if (cell->type == "$reduce_and") primop = "andr";
427 else if (cell->type == "$reduce_or") primop = "orr";
428 else if (cell->type == "$reduce_xor") primop = "xorr";
429 else if (cell->type == "$reduce_xnor") {
430 primop = "not";
431 a_expr = stringf("xorr(%s)", a_expr.c_str());
432 }
433 else if (cell->type == "$reduce_bool") {
434 primop = "neq";
435 // Use the sign of the a_expr and its width as the type (UInt/SInt) and width of the comparand.
436 bool a_signed = cell->parameters.at("\\A_SIGNED").as_bool();
437 int a_width = cell->parameters.at("\\A_WIDTH").as_int();
438 a_expr = stringf("%s, %cInt<%d>(0)", a_expr.c_str(), a_signed ? 'S' : 'U', a_width);
439 }
440
441 string expr = stringf("%s(%s)", primop.c_str(), a_expr.c_str());
442
443 if ((is_signed && !always_uint))
444 expr = stringf("asUInt(%s)", expr.c_str());
445
446 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
447 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
448
449 continue;
450 }
451 if (cell->type.in("$add", "$sub", "$mul", "$div", "$mod", "$xor", "$and", "$or", "$eq", "$eqx",
452 "$gt", "$ge", "$lt", "$le", "$ne", "$nex", "$shr", "$sshr", "$sshl", "$shl",
453 "$logic_and", "$logic_or"))
454 {
455 string y_id = make_id(cell->name);
456 bool is_signed = cell->parameters.at("\\A_SIGNED").as_bool();
457 int y_width = cell->parameters.at("\\Y_WIDTH").as_int();
458 string a_expr = make_expr(cell->getPort("\\A"));
459 string b_expr = make_expr(cell->getPort("\\B"));
460 int b_padded_width = cell->parameters.at("\\B_WIDTH").as_int();
461 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
462
463 if (cell->parameters.at("\\A_SIGNED").as_bool()) {
464 a_expr = "asSInt(" + a_expr + ")";
465 }
466 // Shift amount is always unsigned, and needn't be padded to result width.
467 if (!cell->type.in("$shr", "$sshr", "$shl", "$sshl")) {
468 if (cell->parameters.at("\\B_SIGNED").as_bool()) {
469 b_expr = "asSInt(" + b_expr + ")";
470 }
471 if (b_padded_width < y_width) {
472 auto b_sig = cell->getPort("\\B");
473 b_padded_width = y_width;
474 }
475 }
476
477 auto a_sig = cell->getPort("\\A");
478
479 if (cell->parameters.at("\\A_SIGNED").as_bool() & (cell->type == "$shr")) {
480 a_expr = "asUInt(" + a_expr + ")";
481 }
482
483 string primop;
484 bool always_uint = false;
485 if (cell->type == "$add") primop = "add";
486 else if (cell->type == "$sub") primop = "sub";
487 else if (cell->type == "$mul") primop = "mul";
488 else if (cell->type == "$div") primop = "div";
489 else if (cell->type == "$mod") primop = "rem";
490 else if (cell->type == "$and") {
491 primop = "and";
492 always_uint = true;
493 }
494 else if (cell->type == "$or" ) {
495 primop = "or";
496 always_uint = true;
497 }
498 else if (cell->type == "$xor") {
499 primop = "xor";
500 always_uint = true;
501 }
502 else if ((cell->type == "$eq") | (cell->type == "$eqx")) {
503 primop = "eq";
504 always_uint = true;
505 }
506 else if ((cell->type == "$ne") | (cell->type == "$nex")) {
507 primop = "neq";
508 always_uint = true;
509 }
510 else if (cell->type == "$gt") {
511 primop = "gt";
512 always_uint = true;
513 }
514 else if (cell->type == "$ge") {
515 primop = "geq";
516 always_uint = true;
517 }
518 else if (cell->type == "$lt") {
519 primop = "lt";
520 always_uint = true;
521 }
522 else if (cell->type == "$le") {
523 primop = "leq";
524 always_uint = true;
525 }
526 else if ((cell->type == "$shl") | (cell->type == "$sshl")) {
527 // FIRRTL will widen the result (y) by the amount of the shift.
528 // We'll need to offset this by extracting the un-widened portion as Verilog would do.
529 extract_y_bits = true;
530 // Is the shift amount constant?
531 auto b_sig = cell->getPort("\\B");
532 if (b_sig.is_fully_const()) {
533 primop = "shl";
534 } else {
535 primop = "dshl";
536 // Convert from FIRRTL left shift semantics.
537 b_expr = gen_dshl(b_expr, b_padded_width);
538 }
539 }
540 else if ((cell->type == "$shr") | (cell->type == "$sshr")) {
541 // We don't need to extract a specific range of bits.
542 extract_y_bits = false;
543 // Is the shift amount constant?
544 auto b_sig = cell->getPort("\\B");
545 if (b_sig.is_fully_const()) {
546 primop = "shr";
547 } else {
548 primop = "dshr";
549 }
550 }
551 else if ((cell->type == "$logic_and")) {
552 primop = "and";
553 a_expr = "neq(" + a_expr + ", UInt(0))";
554 b_expr = "neq(" + b_expr + ", UInt(0))";
555 always_uint = true;
556 }
557 else if ((cell->type == "$logic_or")) {
558 primop = "or";
559 a_expr = "neq(" + a_expr + ", UInt(0))";
560 b_expr = "neq(" + b_expr + ", UInt(0))";
561 always_uint = true;
562 }
563
564 if (!cell->parameters.at("\\B_SIGNED").as_bool()) {
565 b_expr = "asUInt(" + b_expr + ")";
566 }
567
568 string expr = stringf("%s(%s, %s)", primop.c_str(), a_expr.c_str(), b_expr.c_str());
569
570 // Deal with FIRRTL's "shift widens" semantics
571 if (extract_y_bits) {
572 expr = stringf("bits(%s, %d, 0)", expr.c_str(), y_width - 1);
573 }
574
575 if ((is_signed && !always_uint) || cell->type.in("$sub"))
576 expr = stringf("asUInt(%s)", expr.c_str());
577
578 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
579 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
580
581 continue;
582 }
583
584 if (cell->type.in("$mux"))
585 {
586 string y_id = make_id(cell->name);
587 int width = cell->parameters.at("\\WIDTH").as_int();
588 string a_expr = make_expr(cell->getPort("\\A"));
589 string b_expr = make_expr(cell->getPort("\\B"));
590 string s_expr = make_expr(cell->getPort("\\S"));
591 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), width));
592
593 string expr = stringf("mux(%s, %s, %s)", s_expr.c_str(), b_expr.c_str(), a_expr.c_str());
594
595 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
596 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
597
598 continue;
599 }
600
601 if (cell->type.in("$mem"))
602 {
603 string mem_id = make_id(cell->name);
604 int abits = cell->parameters.at("\\ABITS").as_int();
605 int width = cell->parameters.at("\\WIDTH").as_int();
606 int size = cell->parameters.at("\\SIZE").as_int();
607 memory m(mem_id, abits, size, width);
608 int rd_ports = cell->parameters.at("\\RD_PORTS").as_int();
609 int wr_ports = cell->parameters.at("\\WR_PORTS").as_int();
610
611 Const initdata = cell->parameters.at("\\INIT");
612 for (State bit : initdata.bits)
613 if (bit != State::Sx)
614 log_error("Memory with initialization data: %s.%s\n", log_id(module), log_id(cell));
615
616 Const rd_clk_enable = cell->parameters.at("\\RD_CLK_ENABLE");
617 Const wr_clk_enable = cell->parameters.at("\\WR_CLK_ENABLE");
618 Const wr_clk_polarity = cell->parameters.at("\\WR_CLK_POLARITY");
619
620 int offset = cell->parameters.at("\\OFFSET").as_int();
621 if (offset != 0)
622 log_error("Memory with nonzero offset: %s.%s\n", log_id(module), log_id(cell));
623
624 for (int i = 0; i < rd_ports; i++)
625 {
626 if (rd_clk_enable[i] != State::S0)
627 log_error("Clocked read port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
628
629 SigSpec addr_sig = cell->getPort("\\RD_ADDR").extract(i*abits, abits);
630 SigSpec data_sig = cell->getPort("\\RD_DATA").extract(i*width, width);
631 string addr_expr = make_expr(addr_sig);
632 string name(stringf("%s.r%d", m.name.c_str(), i));
633 bool clk_enable = false;
634 bool clk_parity = true;
635 bool transparency = false;
636 SigSpec ena_sig = RTLIL::SigSpec(RTLIL::State::S1, 1);
637 SigSpec clk_sig = RTLIL::SigSpec(RTLIL::State::S0, 1);
638 read_port rp(name, clk_enable, clk_parity, transparency, clk_sig, ena_sig, addr_sig);
639 m.add_memory_read_port(rp);
640 cell_exprs.push_back(rp.gen_read(indent.c_str()));
641 register_reverse_wire_map(stringf("%s.data", name.c_str()), data_sig);
642 }
643
644 for (int i = 0; i < wr_ports; i++)
645 {
646 if (wr_clk_enable[i] != State::S1)
647 log_error("Unclocked write port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
648
649 if (wr_clk_polarity[i] != State::S1)
650 log_error("Negedge write port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
651
652 string name(stringf("%s.w%d", m.name.c_str(), i));
653 bool clk_enable = true;
654 bool clk_parity = true;
655 bool transparency = false;
656 SigSpec addr_sig =cell->getPort("\\WR_ADDR").extract(i*abits, abits);
657 string addr_expr = make_expr(addr_sig);
658 SigSpec data_sig =cell->getPort("\\WR_DATA").extract(i*width, width);
659 string data_expr = make_expr(data_sig);
660 SigSpec clk_sig = cell->getPort("\\WR_CLK").extract(i);
661 string clk_expr = make_expr(clk_sig);
662
663 SigSpec wen_sig = cell->getPort("\\WR_EN").extract(i*width, width);
664 string wen_expr = make_expr(wen_sig[0]);
665
666 for (int i = 1; i < GetSize(wen_sig); i++)
667 if (wen_sig[0] != wen_sig[i])
668 log_error("Complex write enable on port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
669
670 SigSpec mask_sig = RTLIL::SigSpec(RTLIL::State::S1, 1);
671 write_port wp(name, clk_enable, clk_parity, transparency, clk_sig, wen_sig[0], addr_sig, mask_sig);
672 m.add_memory_write_port(wp);
673 cell_exprs.push_back(stringf("%s%s.data <= %s\n", indent.c_str(), name.c_str(), data_expr.c_str()));
674 cell_exprs.push_back(wp.gen_write(indent.c_str()));
675 }
676 register_memory(m);
677 continue;
678 }
679
680 if (cell->type.in("$memwr", "$memrd", "$meminit"))
681 {
682 std::string cell_type = fid(cell->type);
683 std::string mem_id = make_id(cell->parameters["\\MEMID"].decode_string());
684 memory *mp = nullptr;
685 if (cell->type == "$meminit" ) {
686 log_error("$meminit (%s.%s.%s) currently unsupported\n", log_id(module), log_id(cell), mem_id.c_str());
687 } else {
688 // It's a $memwr or $memrd. Remember the read/write port parameters for the eventual FIRRTL memory definition.
689 auto addrSig = cell->getPort("\\ADDR");
690 auto dataSig = cell->getPort("\\DATA");
691 auto enableSig = cell->getPort("\\EN");
692 auto clockSig = cell->getPort("\\CLK");
693 Const clk_enable = cell->parameters.at("\\CLK_ENABLE");
694 Const clk_polarity = cell->parameters.at("\\CLK_POLARITY");
695
696 mp = &memories.at(mem_id);
697 int portNum = 0;
698 bool transparency = false;
699 string data_expr = make_expr(dataSig);
700 if (cell->type.in("$memwr")) {
701 portNum = (int) mp->write_ports.size();
702 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);
703 mp->add_memory_write_port(wp);
704 cell_exprs.push_back(stringf("%s%s.data <= %s\n", indent.c_str(), wp.name.c_str(), data_expr.c_str()));
705 cell_exprs.push_back(wp.gen_write(indent.c_str()));
706 } else if (cell->type.in("$memrd")) {
707 portNum = (int) mp->read_ports.size();
708 read_port rp(stringf("%s.r%d", mem_id.c_str(), portNum), clk_enable.as_bool(), clk_polarity.as_bool(), transparency, clockSig, enableSig, addrSig);
709 mp->add_memory_read_port(rp);
710 cell_exprs.push_back(rp.gen_read(indent.c_str()));
711 register_reverse_wire_map(stringf("%s.data", rp.name.c_str()), dataSig);
712 }
713 }
714 continue;
715 }
716
717 if (cell->type.in("$dff"))
718 {
719 bool clkpol = cell->parameters.at("\\CLK_POLARITY").as_bool();
720 if (clkpol == false)
721 log_error("Negative edge clock on FF %s.%s.\n", log_id(module), log_id(cell));
722
723 string q_id = make_id(cell->name);
724 int width = cell->parameters.at("\\WIDTH").as_int();
725 string expr = make_expr(cell->getPort("\\D"));
726 string clk_expr = "asClock(" + make_expr(cell->getPort("\\CLK")) + ")";
727
728 wire_decls.push_back(stringf(" reg %s: UInt<%d>, %s\n", q_id.c_str(), width, clk_expr.c_str()));
729
730 cell_exprs.push_back(stringf(" %s <= %s\n", q_id.c_str(), expr.c_str()));
731 register_reverse_wire_map(q_id, cell->getPort("\\Q"));
732
733 continue;
734 }
735
736 // This may be a parameterized module - paramod.
737 if (cell->type.substr(0, 8) == "$paramod")
738 {
739 process_instance(cell, wire_exprs);
740 continue;
741 }
742 if (cell->type == "$shiftx") {
743 // assign y = a[b +: y_width];
744 // We'll extract the correct bits as part of the primop.
745
746 string y_id = make_id(cell->name);
747 int y_width = cell->parameters.at("\\Y_WIDTH").as_int();
748 string a_expr = make_expr(cell->getPort("\\A"));
749 // Get the initial bit selector
750 string b_expr = make_expr(cell->getPort("\\B"));
751 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
752
753 if (cell->getParam("\\B_SIGNED").as_bool()) {
754 // Use validif to constrain the selection (test the sign bit)
755 auto b_string = b_expr.c_str();
756 int b_sign = cell->parameters.at("\\B_WIDTH").as_int() - 1;
757 b_expr = stringf("validif(not(bits(%s, %d, %d)), %s)", b_string, b_sign, b_sign, b_string);
758 }
759 string expr = stringf("dshr(%s, %s)", a_expr.c_str(), b_expr.c_str());
760
761 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
762 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
763 continue;
764 }
765 if (cell->type == "$shift") {
766 // assign y = a >> b;
767 // where b may be negative
768
769 string y_id = make_id(cell->name);
770 int y_width = cell->parameters.at("\\Y_WIDTH").as_int();
771 string a_expr = make_expr(cell->getPort("\\A"));
772 string b_expr = make_expr(cell->getPort("\\B"));
773 auto b_string = b_expr.c_str();
774 int b_padded_width = cell->parameters.at("\\B_WIDTH").as_int();
775 string expr;
776 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
777
778 if (cell->getParam("\\B_SIGNED").as_bool()) {
779 // We generate a left or right shift based on the sign of b.
780 std::string dshl = stringf("bits(dshl(%s, %s), 0, %d)", a_expr.c_str(), gen_dshl(b_expr, b_padded_width).c_str(), y_width);
781 std::string dshr = stringf("dshr(%s, %s)", a_expr.c_str(), b_string);
782 expr = stringf("mux(%s < 0, %s, %s)",
783 b_string,
784 dshl.c_str(),
785 dshr.c_str()
786 );
787 } else {
788 expr = stringf("dshr(%s, %s)", a_expr.c_str(), b_string);
789 }
790 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
791 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
792 continue;
793 }
794 log_warning("Cell type not supported: %s (%s.%s)\n", log_id(cell->type), log_id(module), log_id(cell));
795 }
796
797 for (auto conn : module->connections())
798 {
799 string y_id = next_id();
800 int y_width = GetSize(conn.first);
801 string expr = make_expr(conn.second);
802
803 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
804 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
805 register_reverse_wire_map(y_id, conn.first);
806 }
807
808 for (auto wire : module->wires())
809 {
810 string expr;
811
812 if (wire->port_input)
813 continue;
814
815 int cursor = 0;
816 bool is_valid = false;
817 bool make_unconn_id = false;
818
819 while (cursor < wire->width)
820 {
821 int chunk_width = 1;
822 string new_expr;
823
824 SigBit start_bit(wire, cursor);
825
826 if (reverse_wire_map.count(start_bit))
827 {
828 pair<string, int> start_map = reverse_wire_map.at(start_bit);
829
830 while (cursor+chunk_width < wire->width)
831 {
832 SigBit stop_bit(wire, cursor+chunk_width);
833
834 if (reverse_wire_map.count(stop_bit) == 0)
835 break;
836
837 pair<string, int> stop_map = reverse_wire_map.at(stop_bit);
838 stop_map.second -= chunk_width;
839
840 if (start_map != stop_map)
841 break;
842
843 chunk_width++;
844 }
845
846 new_expr = stringf("bits(%s, %d, %d)", start_map.first.c_str(),
847 start_map.second + chunk_width - 1, start_map.second);
848 is_valid = true;
849 }
850 else
851 {
852 if (unconn_id.empty()) {
853 unconn_id = next_id();
854 make_unconn_id = true;
855 }
856 new_expr = unconn_id;
857 }
858
859 if (expr.empty())
860 expr = new_expr;
861 else
862 expr = "cat(" + new_expr + ", " + expr + ")";
863
864 cursor += chunk_width;
865 }
866
867 if (is_valid) {
868 if (make_unconn_id) {
869 wire_decls.push_back(stringf(" wire %s: UInt<1>\n", unconn_id.c_str()));
870 wire_decls.push_back(stringf(" %s is invalid\n", unconn_id.c_str()));
871 }
872 wire_exprs.push_back(stringf(" %s <= %s\n", make_id(wire->name), expr.c_str()));
873 } else {
874 if (make_unconn_id) {
875 unconn_id.clear();
876 }
877 wire_decls.push_back(stringf(" %s is invalid\n", make_id(wire->name)));
878 }
879 }
880
881 for (auto str : port_decls)
882 f << str;
883
884 f << stringf("\n");
885
886 for (auto str : wire_decls)
887 f << str;
888
889 f << stringf("\n");
890
891 // If we have any memory definitions, output them.
892 for (auto kv : memories) {
893 memory m = kv.second;
894 f << stringf(" mem %s:\n", m.name.c_str());
895 f << stringf(" data-type => UInt<%d>\n", m.width);
896 f << stringf(" depth => %d\n", m.size);
897 for (int i = 0; i < (int) m.read_ports.size(); i += 1) {
898 f << stringf(" reader => r%d\n", i);
899 }
900 for (int i = 0; i < (int) m.write_ports.size(); i += 1) {
901 f << stringf(" writer => w%d\n", i);
902 }
903 f << stringf(" read-latency => %d\n", m.read_latency);
904 f << stringf(" write-latency => %d\n", m.write_latency);
905 f << stringf(" read-under-write => undefined\n");
906 }
907 f << stringf("\n");
908
909 for (auto str : cell_exprs)
910 f << str;
911
912 f << stringf("\n");
913
914 for (auto str : wire_exprs)
915 f << str;
916 }
917 };
918
919 struct FirrtlBackend : public Backend {
920 FirrtlBackend() : Backend("firrtl", "write design to a FIRRTL file") { }
921 void help() YS_OVERRIDE
922 {
923 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
924 log("\n");
925 log(" write_firrtl [options] [filename]\n");
926 log("\n");
927 log("Write a FIRRTL netlist of the current design.\n");
928 log("The following commands are executed by this command:\n");
929 log(" pmuxtree\n");
930 log("\n");
931 }
932 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
933 {
934 size_t argidx = args.size(); // We aren't expecting any arguments.
935
936 // If we weren't explicitly passed a filename, use the last argument (if it isn't a flag).
937 if (filename == "") {
938 if (argidx > 0 && args[argidx - 1][0] != '-') {
939 // extra_args and friends need to see this argument.
940 argidx -= 1;
941 filename = args[argidx];
942 }
943 }
944 extra_args(f, filename, args, argidx);
945
946 if (!design->full_selection())
947 log_cmd_error("This command only operates on fully selected designs!\n");
948
949 log_header(design, "Executing FIRRTL backend.\n");
950 log_push();
951
952 Pass::call(design, stringf("pmuxtree"));
953
954 namecache.clear();
955 autoid_counter = 0;
956
957 // Get the top module, or a reasonable facsimile - we need something for the circuit name.
958 Module *top = design->top_module();
959 Module *last = nullptr;
960 // Generate module and wire names.
961 for (auto module : design->modules()) {
962 make_id(module->name);
963 last = module;
964 if (top == nullptr && module->get_bool_attribute("\\top")) {
965 top = module;
966 }
967 for (auto wire : module->wires())
968 if (wire->port_id)
969 make_id(wire->name);
970 }
971
972 if (top == nullptr)
973 top = last;
974
975 *f << stringf("circuit %s:\n", make_id(top->name));
976
977 for (auto module : design->modules())
978 {
979 FirrtlWorker worker(module, *f, design);
980 worker.run();
981 }
982
983 namecache.clear();
984 autoid_counter = 0;
985 }
986 } FirrtlBackend;
987
988 PRIVATE_NAMESPACE_END