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