Merge pull request #875 from YosysHQ/clifford/mutate
[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 void register_reverse_wire_map(string id, SigSpec sig)
110 {
111 for (int i = 0; i < GetSize(sig); i++)
112 reverse_wire_map[sig[i]] = make_pair(id, i);
113 }
114
115 FirrtlWorker(Module *module, std::ostream &f, RTLIL::Design *theDesign) : module(module), f(f), design(theDesign), indent(" ")
116 {
117 }
118
119 string make_expr(const SigSpec &sig)
120 {
121 string expr;
122
123 for (auto chunk : sig.chunks())
124 {
125 string new_expr;
126
127 if (chunk.wire == nullptr)
128 {
129 std::vector<RTLIL::State> bits = chunk.data;
130 new_expr = stringf("UInt<%d>(\"h", GetSize(bits));
131
132 while (GetSize(bits) % 4 != 0)
133 bits.push_back(State::S0);
134
135 for (int i = GetSize(bits)-4; i >= 0; i -= 4)
136 {
137 int val = 0;
138 if (bits[i+0] == State::S1) val += 1;
139 if (bits[i+1] == State::S1) val += 2;
140 if (bits[i+2] == State::S1) val += 4;
141 if (bits[i+3] == State::S1) val += 8;
142 new_expr.push_back(val < 10 ? '0' + val : 'a' + val - 10);
143 }
144
145 new_expr += "\")";
146 }
147 else if (chunk.offset == 0 && chunk.width == chunk.wire->width)
148 {
149 new_expr = make_id(chunk.wire->name);
150 }
151 else
152 {
153 string wire_id = make_id(chunk.wire->name);
154 new_expr = stringf("bits(%s, %d, %d)", wire_id.c_str(), chunk.offset + chunk.width - 1, chunk.offset);
155 }
156
157 if (expr.empty())
158 expr = new_expr;
159 else
160 expr = "cat(" + new_expr + ", " + expr + ")";
161 }
162
163 return expr;
164 }
165
166 std::string fid(RTLIL::IdString internal_id)
167 {
168 return make_id(internal_id);
169 }
170
171 std::string cellname(RTLIL::Cell *cell)
172 {
173 return fid(cell->name).c_str();
174 }
175
176 void process_instance(RTLIL::Cell *cell, vector<string> &wire_exprs)
177 {
178 std::string cell_type = fid(cell->type);
179 std::string instanceOf;
180 // If this is a parameterized module, its parent module is encoded in the cell type
181 if (cell->type.substr(0, 8) == "$paramod")
182 {
183 std::string::iterator it;
184 for (it = cell_type.begin(); it < cell_type.end(); it++)
185 {
186 switch (*it) {
187 case '\\': /* FALL_THROUGH */
188 case '=': /* FALL_THROUGH */
189 case '\'': /* FALL_THROUGH */
190 case '$': instanceOf.append("_"); break;
191 default: instanceOf.append(1, *it); break;
192 }
193 }
194 }
195 else
196 {
197 instanceOf = cell_type;
198 }
199
200 std::string cell_name = cellname(cell);
201 std::string cell_name_comment;
202 if (cell_name != fid(cell->name))
203 cell_name_comment = " /* " + fid(cell->name) + " */ ";
204 else
205 cell_name_comment = "";
206 // Find the module corresponding to this instance.
207 auto instModule = design->module(cell->type);
208 // If there is no instance for this, just return.
209 if (instModule == NULL)
210 {
211 log_warning("No instance for %s.%s\n", cell_type.c_str(), cell_name.c_str());
212 return;
213 }
214 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()));
215
216 for (auto it = cell->connections().begin(); it != cell->connections().end(); ++it) {
217 if (it->second.size() > 0) {
218 const SigSpec &secondSig = it->second;
219 const std::string firstName = cell_name + "." + make_id(it->first);
220 const std::string secondExpr = make_expr(secondSig);
221 // Find the direction for this port.
222 FDirection dir = getPortFDirection(it->first, instModule);
223 std::string sourceExpr, sinkExpr;
224 const SigSpec *sinkSig = nullptr;
225 switch (dir) {
226 case FD_INOUT:
227 log_warning("Instance port connection %s.%s is INOUT; treating as OUT\n", cell_type.c_str(), log_signal(it->second));
228 case FD_OUT:
229 sourceExpr = firstName;
230 sinkExpr = secondExpr;
231 sinkSig = &secondSig;
232 break;
233 case FD_NODIRECTION:
234 log_warning("Instance port connection %s.%s is NODIRECTION; treating as IN\n", cell_type.c_str(), log_signal(it->second));
235 /* FALL_THROUGH */
236 case FD_IN:
237 sourceExpr = secondExpr;
238 sinkExpr = firstName;
239 break;
240 default:
241 log_error("Instance port %s.%s unrecognized connection direction 0x%x !\n", cell_type.c_str(), log_signal(it->second), dir);
242 break;
243 }
244 // Check for subfield assignment.
245 std::string bitsString = "bits(";
246 if (sinkExpr.substr(0, bitsString.length()) == bitsString ) {
247 if (sinkSig == nullptr)
248 log_error("Unknown subfield %s.%s\n", cell_type.c_str(), sinkExpr.c_str());
249 // Don't generate the assignment here.
250 // Add the source and sink to the "reverse_wire_map" and we'll output the assignment
251 // as part of the coalesced subfield assignments for this wire.
252 register_reverse_wire_map(sourceExpr, *sinkSig);
253 } else {
254 wire_exprs.push_back(stringf("\n%s%s <= %s", indent.c_str(), sinkExpr.c_str(), sourceExpr.c_str()));
255 }
256 }
257 }
258 wire_exprs.push_back(stringf("\n"));
259
260 }
261
262 // Given an expression for a shift amount, and a maximum width,
263 // generate the FIRRTL expression for equivalent dynamic shift taking into account FIRRTL shift semantics.
264 std::string gen_dshl(const string b_expr, const int b_padded_width)
265 {
266 string result = b_expr;
267 if (b_padded_width >= FIRRTL_MAX_DSH_WIDTH_ERROR) {
268 int max_shift_width_bits = FIRRTL_MAX_DSH_WIDTH_ERROR - 1;
269 string max_shift_string = stringf("UInt<%d>(%d)", max_shift_width_bits, (1<<max_shift_width_bits) - 1);
270 // Deal with the difference in semantics between FIRRTL and verilog
271 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);
272 }
273 return result;
274 }
275
276 void run()
277 {
278 f << stringf(" module %s:\n", make_id(module->name));
279 vector<string> port_decls, wire_decls, cell_exprs, wire_exprs;
280
281 for (auto wire : module->wires())
282 {
283 const auto wireName = make_id(wire->name);
284 // If a wire has initial data, issue a warning since FIRRTL doesn't currently support it.
285 if (wire->attributes.count("\\init")) {
286 log_warning("Initial value (%s) for (%s.%s) not supported\n",
287 wire->attributes.at("\\init").as_string().c_str(),
288 log_id(module), log_id(wire));
289 }
290 if (wire->port_id)
291 {
292 if (wire->port_input && wire->port_output)
293 log_error("Module port %s.%s is inout!\n", log_id(module), log_id(wire));
294 port_decls.push_back(stringf(" %s %s: UInt<%d>\n", wire->port_input ? "input" : "output",
295 wireName, wire->width));
296 }
297 else
298 {
299 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", wireName, wire->width));
300 }
301 }
302
303 for (auto cell : module->cells())
304 {
305 bool extract_y_bits = false; // Assume no extraction of final bits will be required.
306 // Is this cell is a module instance?
307 if (cell->type[0] != '$')
308 {
309 process_instance(cell, wire_exprs);
310 continue;
311 }
312 if (cell->type.in("$not", "$logic_not", "$neg", "$reduce_and", "$reduce_or", "$reduce_xor", "$reduce_bool", "$reduce_xnor"))
313 {
314 string y_id = make_id(cell->name);
315 bool is_signed = cell->parameters.at("\\A_SIGNED").as_bool();
316 int y_width = cell->parameters.at("\\Y_WIDTH").as_int();
317 string a_expr = make_expr(cell->getPort("\\A"));
318 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
319
320 if (cell->parameters.at("\\A_SIGNED").as_bool()) {
321 a_expr = "asSInt(" + a_expr + ")";
322 }
323
324 // Don't use the results of logical operations (a single bit) to control padding
325 if (!(cell->type.in("$eq", "$eqx", "$gt", "$ge", "$lt", "$le", "$ne", "$nex", "$reduce_bool", "$logic_not") && y_width == 1) ) {
326 a_expr = stringf("pad(%s, %d)", a_expr.c_str(), y_width);
327 }
328
329 string primop;
330 bool always_uint = false;
331 if (cell->type == "$not") primop = "not";
332 else if (cell->type == "$neg") primop = "neg";
333 else if (cell->type == "$logic_not") {
334 primop = "eq";
335 a_expr = stringf("%s, UInt(0)", a_expr.c_str());
336 }
337 else if (cell->type == "$reduce_and") primop = "andr";
338 else if (cell->type == "$reduce_or") primop = "orr";
339 else if (cell->type == "$reduce_xor") primop = "xorr";
340 else if (cell->type == "$reduce_xnor") {
341 primop = "not";
342 a_expr = stringf("xorr(%s)", a_expr.c_str());
343 }
344 else if (cell->type == "$reduce_bool") {
345 primop = "neq";
346 // Use the sign of the a_expr and its width as the type (UInt/SInt) and width of the comparand.
347 bool a_signed = cell->parameters.at("\\A_SIGNED").as_bool();
348 int a_width = cell->parameters.at("\\A_WIDTH").as_int();
349 a_expr = stringf("%s, %cInt<%d>(0)", a_expr.c_str(), a_signed ? 'S' : 'U', a_width);
350 }
351
352 string expr = stringf("%s(%s)", primop.c_str(), a_expr.c_str());
353
354 if ((is_signed && !always_uint))
355 expr = stringf("asUInt(%s)", expr.c_str());
356
357 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
358 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
359
360 continue;
361 }
362 if (cell->type.in("$add", "$sub", "$mul", "$div", "$mod", "$xor", "$and", "$or", "$eq", "$eqx",
363 "$gt", "$ge", "$lt", "$le", "$ne", "$nex", "$shr", "$sshr", "$sshl", "$shl",
364 "$logic_and", "$logic_or"))
365 {
366 string y_id = make_id(cell->name);
367 bool is_signed = cell->parameters.at("\\A_SIGNED").as_bool();
368 int y_width = cell->parameters.at("\\Y_WIDTH").as_int();
369 string a_expr = make_expr(cell->getPort("\\A"));
370 string b_expr = make_expr(cell->getPort("\\B"));
371 int b_padded_width = cell->parameters.at("\\B_WIDTH").as_int();
372 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
373
374 if (cell->parameters.at("\\A_SIGNED").as_bool()) {
375 a_expr = "asSInt(" + a_expr + ")";
376 }
377 // Shift amount is always unsigned, and needn't be padded to result width.
378 if (!cell->type.in("$shr", "$sshr", "$shl", "$sshl")) {
379 if (cell->parameters.at("\\B_SIGNED").as_bool()) {
380 b_expr = "asSInt(" + b_expr + ")";
381 }
382 if (b_padded_width < y_width) {
383 auto b_sig = cell->getPort("\\B");
384 b_padded_width = y_width;
385 }
386 }
387
388 auto a_sig = cell->getPort("\\A");
389
390 if (cell->parameters.at("\\A_SIGNED").as_bool() & (cell->type == "$shr")) {
391 a_expr = "asUInt(" + a_expr + ")";
392 }
393
394 string primop;
395 bool always_uint = false;
396 if (cell->type == "$add") primop = "add";
397 else if (cell->type == "$sub") primop = "sub";
398 else if (cell->type == "$mul") primop = "mul";
399 else if (cell->type == "$div") primop = "div";
400 else if (cell->type == "$mod") primop = "rem";
401 else if (cell->type == "$and") {
402 primop = "and";
403 always_uint = true;
404 }
405 else if (cell->type == "$or" ) {
406 primop = "or";
407 always_uint = true;
408 }
409 else if (cell->type == "$xor") {
410 primop = "xor";
411 always_uint = true;
412 }
413 else if ((cell->type == "$eq") | (cell->type == "$eqx")) {
414 primop = "eq";
415 always_uint = true;
416 }
417 else if ((cell->type == "$ne") | (cell->type == "$nex")) {
418 primop = "neq";
419 always_uint = true;
420 }
421 else if (cell->type == "$gt") {
422 primop = "gt";
423 always_uint = true;
424 }
425 else if (cell->type == "$ge") {
426 primop = "geq";
427 always_uint = true;
428 }
429 else if (cell->type == "$lt") {
430 primop = "lt";
431 always_uint = true;
432 }
433 else if (cell->type == "$le") {
434 primop = "leq";
435 always_uint = true;
436 }
437 else if ((cell->type == "$shl") | (cell->type == "$sshl")) {
438 // FIRRTL will widen the result (y) by the amount of the shift.
439 // We'll need to offset this by extracting the un-widened portion as Verilog would do.
440 extract_y_bits = true;
441 // Is the shift amount constant?
442 auto b_sig = cell->getPort("\\B");
443 if (b_sig.is_fully_const()) {
444 primop = "shl";
445 } else {
446 primop = "dshl";
447 // Convert from FIRRTL left shift semantics.
448 b_expr = gen_dshl(b_expr, b_padded_width);
449 }
450 }
451 else if ((cell->type == "$shr") | (cell->type == "$sshr")) {
452 // We don't need to extract a specific range of bits.
453 extract_y_bits = false;
454 // Is the shift amount constant?
455 auto b_sig = cell->getPort("\\B");
456 if (b_sig.is_fully_const()) {
457 primop = "shr";
458 } else {
459 primop = "dshr";
460 }
461 }
462 else if ((cell->type == "$logic_and")) {
463 primop = "and";
464 a_expr = "neq(" + a_expr + ", UInt(0))";
465 b_expr = "neq(" + b_expr + ", UInt(0))";
466 always_uint = true;
467 }
468 else if ((cell->type == "$logic_or")) {
469 primop = "or";
470 a_expr = "neq(" + a_expr + ", UInt(0))";
471 b_expr = "neq(" + b_expr + ", UInt(0))";
472 always_uint = true;
473 }
474
475 if (!cell->parameters.at("\\B_SIGNED").as_bool()) {
476 b_expr = "asUInt(" + b_expr + ")";
477 }
478
479 string expr = stringf("%s(%s, %s)", primop.c_str(), a_expr.c_str(), b_expr.c_str());
480
481 // Deal with FIRRTL's "shift widens" semantics
482 if (extract_y_bits) {
483 expr = stringf("bits(%s, %d, 0)", expr.c_str(), y_width - 1);
484 }
485
486 if ((is_signed && !always_uint) || cell->type.in("$sub"))
487 expr = stringf("asUInt(%s)", expr.c_str());
488
489 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
490 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
491
492 continue;
493 }
494
495 if (cell->type.in("$mux"))
496 {
497 string y_id = make_id(cell->name);
498 int width = cell->parameters.at("\\WIDTH").as_int();
499 string a_expr = make_expr(cell->getPort("\\A"));
500 string b_expr = make_expr(cell->getPort("\\B"));
501 string s_expr = make_expr(cell->getPort("\\S"));
502 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), width));
503
504 string expr = stringf("mux(%s, %s, %s)", s_expr.c_str(), b_expr.c_str(), a_expr.c_str());
505
506 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
507 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
508
509 continue;
510 }
511
512 if (cell->type.in("$mem"))
513 {
514 string mem_id = make_id(cell->name);
515 int abits = cell->parameters.at("\\ABITS").as_int();
516 int width = cell->parameters.at("\\WIDTH").as_int();
517 int size = cell->parameters.at("\\SIZE").as_int();
518 int rd_ports = cell->parameters.at("\\RD_PORTS").as_int();
519 int wr_ports = cell->parameters.at("\\WR_PORTS").as_int();
520
521 Const initdata = cell->parameters.at("\\INIT");
522 for (State bit : initdata.bits)
523 if (bit != State::Sx)
524 log_error("Memory with initialization data: %s.%s\n", log_id(module), log_id(cell));
525
526 Const rd_clk_enable = cell->parameters.at("\\RD_CLK_ENABLE");
527 Const wr_clk_enable = cell->parameters.at("\\WR_CLK_ENABLE");
528 Const wr_clk_polarity = cell->parameters.at("\\WR_CLK_POLARITY");
529
530 int offset = cell->parameters.at("\\OFFSET").as_int();
531 if (offset != 0)
532 log_error("Memory with nonzero offset: %s.%s\n", log_id(module), log_id(cell));
533
534 cell_exprs.push_back(stringf(" mem %s:\n", mem_id.c_str()));
535 cell_exprs.push_back(stringf(" data-type => UInt<%d>\n", width));
536 cell_exprs.push_back(stringf(" depth => %d\n", size));
537
538 for (int i = 0; i < rd_ports; i++)
539 cell_exprs.push_back(stringf(" reader => r%d\n", i));
540
541 for (int i = 0; i < wr_ports; i++)
542 cell_exprs.push_back(stringf(" writer => w%d\n", i));
543
544 cell_exprs.push_back(stringf(" read-latency => 0\n"));
545 cell_exprs.push_back(stringf(" write-latency => 1\n"));
546 cell_exprs.push_back(stringf(" read-under-write => undefined\n"));
547
548 for (int i = 0; i < rd_ports; i++)
549 {
550 if (rd_clk_enable[i] != State::S0)
551 log_error("Clocked read port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
552
553 SigSpec data_sig = cell->getPort("\\RD_DATA").extract(i*width, width);
554 string addr_expr = make_expr(cell->getPort("\\RD_ADDR").extract(i*abits, abits));
555
556 cell_exprs.push_back(stringf(" %s.r%d.addr <= %s\n", mem_id.c_str(), i, addr_expr.c_str()));
557 cell_exprs.push_back(stringf(" %s.r%d.en <= UInt<1>(1)\n", mem_id.c_str(), i));
558 cell_exprs.push_back(stringf(" %s.r%d.clk <= asClock(UInt<1>(0))\n", mem_id.c_str(), i));
559
560 register_reverse_wire_map(stringf("%s.r%d.data", mem_id.c_str(), i), data_sig);
561 }
562
563 for (int i = 0; i < wr_ports; i++)
564 {
565 if (wr_clk_enable[i] != State::S1)
566 log_error("Unclocked write port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
567
568 if (wr_clk_polarity[i] != State::S1)
569 log_error("Negedge write port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
570
571 string addr_expr = make_expr(cell->getPort("\\WR_ADDR").extract(i*abits, abits));
572 string data_expr = make_expr(cell->getPort("\\WR_DATA").extract(i*width, width));
573 string clk_expr = make_expr(cell->getPort("\\WR_CLK").extract(i));
574
575 SigSpec wen_sig = cell->getPort("\\WR_EN").extract(i*width, width);
576 string wen_expr = make_expr(wen_sig[0]);
577
578 for (int i = 1; i < GetSize(wen_sig); i++)
579 if (wen_sig[0] != wen_sig[i])
580 log_error("Complex write enable on port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
581
582 cell_exprs.push_back(stringf(" %s.w%d.addr <= %s\n", mem_id.c_str(), i, addr_expr.c_str()));
583 cell_exprs.push_back(stringf(" %s.w%d.data <= %s\n", mem_id.c_str(), i, data_expr.c_str()));
584 cell_exprs.push_back(stringf(" %s.w%d.en <= %s\n", mem_id.c_str(), i, wen_expr.c_str()));
585 cell_exprs.push_back(stringf(" %s.w%d.mask <= UInt<1>(1)\n", mem_id.c_str(), i));
586 cell_exprs.push_back(stringf(" %s.w%d.clk <= asClock(%s)\n", mem_id.c_str(), i, clk_expr.c_str()));
587 }
588
589 continue;
590 }
591
592 if (cell->type.in("$dff"))
593 {
594 bool clkpol = cell->parameters.at("\\CLK_POLARITY").as_bool();
595 if (clkpol == false)
596 log_error("Negative edge clock on FF %s.%s.\n", log_id(module), log_id(cell));
597
598 string q_id = make_id(cell->name);
599 int width = cell->parameters.at("\\WIDTH").as_int();
600 string expr = make_expr(cell->getPort("\\D"));
601 string clk_expr = "asClock(" + make_expr(cell->getPort("\\CLK")) + ")";
602
603 wire_decls.push_back(stringf(" reg %s: UInt<%d>, %s\n", q_id.c_str(), width, clk_expr.c_str()));
604
605 cell_exprs.push_back(stringf(" %s <= %s\n", q_id.c_str(), expr.c_str()));
606 register_reverse_wire_map(q_id, cell->getPort("\\Q"));
607
608 continue;
609 }
610
611 // This may be a parameterized module - paramod.
612 if (cell->type.substr(0, 8) == "$paramod")
613 {
614 process_instance(cell, wire_exprs);
615 continue;
616 }
617 if (cell->type == "$shiftx") {
618 // assign y = a[b +: y_width];
619 // We'll extract the correct bits as part of the primop.
620
621 string y_id = make_id(cell->name);
622 int y_width = cell->parameters.at("\\Y_WIDTH").as_int();
623 string a_expr = make_expr(cell->getPort("\\A"));
624 // Get the initial bit selector
625 string b_expr = make_expr(cell->getPort("\\B"));
626 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
627
628 if (cell->getParam("\\B_SIGNED").as_bool()) {
629 // Use validif to constrain the selection (test the sign bit)
630 auto b_string = b_expr.c_str();
631 int b_sign = cell->parameters.at("\\B_WIDTH").as_int() - 1;
632 b_expr = stringf("validif(not(bits(%s, %d, %d)), %s)", b_string, b_sign, b_sign, b_string);
633 }
634 string expr = stringf("dshr(%s, %s)", a_expr.c_str(), b_expr.c_str());
635
636 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
637 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
638 continue;
639 }
640 if (cell->type == "$shift") {
641 // assign y = a >> b;
642 // where b may be negative
643
644 string y_id = make_id(cell->name);
645 int y_width = cell->parameters.at("\\Y_WIDTH").as_int();
646 string a_expr = make_expr(cell->getPort("\\A"));
647 string b_expr = make_expr(cell->getPort("\\B"));
648 auto b_string = b_expr.c_str();
649 int b_padded_width = cell->parameters.at("\\B_WIDTH").as_int();
650 string expr;
651 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
652
653 if (cell->getParam("\\B_SIGNED").as_bool()) {
654 // We generate a left or right shift based on the sign of b.
655 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);
656 std::string dshr = stringf("dshr(%s, %s)", a_expr.c_str(), b_string);
657 expr = stringf("mux(%s < 0, %s, %s)",
658 b_string,
659 dshl.c_str(),
660 dshr.c_str()
661 );
662 } else {
663 expr = stringf("dshr(%s, %s)", a_expr.c_str(), b_string);
664 }
665 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
666 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
667 continue;
668 }
669 log_warning("Cell type not supported: %s (%s.%s)\n", log_id(cell->type), log_id(module), log_id(cell));
670 }
671
672 for (auto conn : module->connections())
673 {
674 string y_id = next_id();
675 int y_width = GetSize(conn.first);
676 string expr = make_expr(conn.second);
677
678 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
679 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
680 register_reverse_wire_map(y_id, conn.first);
681 }
682
683 for (auto wire : module->wires())
684 {
685 string expr;
686
687 if (wire->port_input)
688 continue;
689
690 int cursor = 0;
691 bool is_valid = false;
692 bool make_unconn_id = false;
693
694 while (cursor < wire->width)
695 {
696 int chunk_width = 1;
697 string new_expr;
698
699 SigBit start_bit(wire, cursor);
700
701 if (reverse_wire_map.count(start_bit))
702 {
703 pair<string, int> start_map = reverse_wire_map.at(start_bit);
704
705 while (cursor+chunk_width < wire->width)
706 {
707 SigBit stop_bit(wire, cursor+chunk_width);
708
709 if (reverse_wire_map.count(stop_bit) == 0)
710 break;
711
712 pair<string, int> stop_map = reverse_wire_map.at(stop_bit);
713 stop_map.second -= chunk_width;
714
715 if (start_map != stop_map)
716 break;
717
718 chunk_width++;
719 }
720
721 new_expr = stringf("bits(%s, %d, %d)", start_map.first.c_str(),
722 start_map.second + chunk_width - 1, start_map.second);
723 is_valid = true;
724 }
725 else
726 {
727 if (unconn_id.empty()) {
728 unconn_id = next_id();
729 make_unconn_id = true;
730 }
731 new_expr = unconn_id;
732 }
733
734 if (expr.empty())
735 expr = new_expr;
736 else
737 expr = "cat(" + new_expr + ", " + expr + ")";
738
739 cursor += chunk_width;
740 }
741
742 if (is_valid) {
743 if (make_unconn_id) {
744 wire_decls.push_back(stringf(" wire %s: UInt<1>\n", unconn_id.c_str()));
745 wire_decls.push_back(stringf(" %s is invalid\n", unconn_id.c_str()));
746 }
747 wire_exprs.push_back(stringf(" %s <= %s\n", make_id(wire->name), expr.c_str()));
748 } else {
749 if (make_unconn_id) {
750 unconn_id.clear();
751 }
752 wire_decls.push_back(stringf(" %s is invalid\n", make_id(wire->name)));
753 }
754 }
755
756 for (auto str : port_decls)
757 f << str;
758
759 f << stringf("\n");
760
761 for (auto str : wire_decls)
762 f << str;
763
764 f << stringf("\n");
765
766 for (auto str : cell_exprs)
767 f << str;
768
769 f << stringf("\n");
770
771 for (auto str : wire_exprs)
772 f << str;
773 }
774 };
775
776 struct FirrtlBackend : public Backend {
777 FirrtlBackend() : Backend("firrtl", "write design to a FIRRTL file") { }
778 void help() YS_OVERRIDE
779 {
780 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
781 log("\n");
782 log(" write_firrtl [options] [filename]\n");
783 log("\n");
784 log("Write a FIRRTL netlist of the current design.\n");
785 log("The following commands are executed by this command:\n");
786 log(" pmuxtree\n");
787 log("\n");
788 }
789 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
790 {
791 size_t argidx = args.size(); // We aren't expecting any arguments.
792
793 // If we weren't explicitly passed a filename, use the last argument (if it isn't a flag).
794 if (filename == "") {
795 if (argidx > 0 && args[argidx - 1][0] != '-') {
796 // extra_args and friends need to see this argument.
797 argidx -= 1;
798 filename = args[argidx];
799 }
800 }
801 extra_args(f, filename, args, argidx);
802
803 if (!design->full_selection())
804 log_cmd_error("This command only operates on fully selected designs!\n");
805
806 log_header(design, "Executing FIRRTL backend.\n");
807 log_push();
808
809 Pass::call(design, stringf("pmuxtree"));
810
811 namecache.clear();
812 autoid_counter = 0;
813
814 // Get the top module, or a reasonable facsimile - we need something for the circuit name.
815 Module *top = design->top_module();
816 Module *last = nullptr;
817 // Generate module and wire names.
818 for (auto module : design->modules()) {
819 make_id(module->name);
820 last = module;
821 if (top == nullptr && module->get_bool_attribute("\\top")) {
822 top = module;
823 }
824 for (auto wire : module->wires())
825 if (wire->port_id)
826 make_id(wire->name);
827 }
828
829 if (top == nullptr)
830 top = last;
831
832 *f << stringf("circuit %s:\n", make_id(top->name));
833
834 for (auto module : design->modules())
835 {
836 FirrtlWorker worker(module, *f, design);
837 worker.run();
838 }
839
840 namecache.clear();
841 autoid_counter = 0;
842 }
843 } FirrtlBackend;
844
845 PRIVATE_NAMESPACE_END