Added support for "upto" wires to Verilog front- and back-end
[yosys.git] / frontends / ast / genrtlil.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 * This is the AST frontend library.
21 *
22 * The AST frontend library is not a frontend on it's own but provides a
23 * generic abstract syntax tree (AST) abstraction for HDL code and can be
24 * used by HDL frontends. See "ast.h" for an overview of the API and the
25 * Verilog frontend for an usage example.
26 *
27 */
28
29 #include "kernel/log.h"
30 #include "libs/sha1/sha1.h"
31 #include "ast.h"
32
33 #include <sstream>
34 #include <stdarg.h>
35 #include <algorithm>
36
37 using namespace AST;
38 using namespace AST_INTERNAL;
39
40 // helper function for creating RTLIL code for unary operations
41 static RTLIL::SigSpec uniop2rtlil(AstNode *that, std::string type, int result_width, const RTLIL::SigSpec &arg, bool gen_attributes = true)
42 {
43 std::stringstream sstr;
44 sstr << type << "$" << that->filename << ":" << that->linenum << "$" << (RTLIL::autoidx++);
45
46 RTLIL::Cell *cell = current_module->addCell(sstr.str(), type);
47 cell->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
48
49 RTLIL::Wire *wire = current_module->addWire(cell->name + "_Y", result_width);
50 wire->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
51
52 if (gen_attributes)
53 for (auto &attr : that->attributes) {
54 if (attr.second->type != AST_CONSTANT)
55 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
56 attr.first.c_str(), that->filename.c_str(), that->linenum);
57 cell->attributes[attr.first] = attr.second->asAttrConst();
58 }
59
60 cell->parameters["\\A_SIGNED"] = RTLIL::Const(that->children[0]->is_signed);
61 cell->parameters["\\A_WIDTH"] = RTLIL::Const(arg.size());
62 cell->set("\\A", arg);
63
64 cell->parameters["\\Y_WIDTH"] = result_width;
65 cell->set("\\Y", wire);
66 return wire;
67 }
68
69 // helper function for extending bit width (preferred over SigSpec::extend() because of correct undef propagation in ConstEval)
70 static void widthExtend(AstNode *that, RTLIL::SigSpec &sig, int width, bool is_signed, std::string celltype)
71 {
72 if (width <= sig.size()) {
73 sig.extend(width, is_signed);
74 return;
75 }
76
77 std::stringstream sstr;
78 sstr << "$extend" << "$" << that->filename << ":" << that->linenum << "$" << (RTLIL::autoidx++);
79
80 RTLIL::Cell *cell = current_module->addCell(sstr.str(), celltype);
81 cell->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
82
83 RTLIL::Wire *wire = current_module->addWire(cell->name + "_Y", width);
84 wire->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
85
86 if (that != NULL)
87 for (auto &attr : that->attributes) {
88 if (attr.second->type != AST_CONSTANT)
89 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
90 attr.first.c_str(), that->filename.c_str(), that->linenum);
91 cell->attributes[attr.first] = attr.second->asAttrConst();
92 }
93
94 cell->parameters["\\A_SIGNED"] = RTLIL::Const(is_signed);
95 cell->parameters["\\A_WIDTH"] = RTLIL::Const(sig.size());
96 cell->set("\\A", sig);
97
98 cell->parameters["\\Y_WIDTH"] = width;
99 cell->set("\\Y", wire);
100 sig = wire;
101 }
102
103 // helper function for creating RTLIL code for binary operations
104 static RTLIL::SigSpec binop2rtlil(AstNode *that, std::string type, int result_width, const RTLIL::SigSpec &left, const RTLIL::SigSpec &right)
105 {
106 std::stringstream sstr;
107 sstr << type << "$" << that->filename << ":" << that->linenum << "$" << (RTLIL::autoidx++);
108
109 RTLIL::Cell *cell = current_module->addCell(sstr.str(), type);
110 cell->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
111
112 RTLIL::Wire *wire = current_module->addWire(cell->name + "_Y", result_width);
113 wire->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
114
115 for (auto &attr : that->attributes) {
116 if (attr.second->type != AST_CONSTANT)
117 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
118 attr.first.c_str(), that->filename.c_str(), that->linenum);
119 cell->attributes[attr.first] = attr.second->asAttrConst();
120 }
121
122 cell->parameters["\\A_SIGNED"] = RTLIL::Const(that->children[0]->is_signed);
123 cell->parameters["\\B_SIGNED"] = RTLIL::Const(that->children[1]->is_signed);
124
125 cell->parameters["\\A_WIDTH"] = RTLIL::Const(left.size());
126 cell->parameters["\\B_WIDTH"] = RTLIL::Const(right.size());
127
128 cell->set("\\A", left);
129 cell->set("\\B", right);
130
131 cell->parameters["\\Y_WIDTH"] = result_width;
132 cell->set("\\Y", wire);
133 return wire;
134 }
135
136 // helper function for creating RTLIL code for multiplexers
137 static RTLIL::SigSpec mux2rtlil(AstNode *that, const RTLIL::SigSpec &cond, const RTLIL::SigSpec &left, const RTLIL::SigSpec &right)
138 {
139 log_assert(cond.size() == 1);
140
141 std::stringstream sstr;
142 sstr << "$ternary$" << that->filename << ":" << that->linenum << "$" << (RTLIL::autoidx++);
143
144 RTLIL::Cell *cell = current_module->addCell(sstr.str(), "$mux");
145 cell->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
146
147 RTLIL::Wire *wire = current_module->addWire(cell->name + "_Y", left.size());
148 wire->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
149
150 for (auto &attr : that->attributes) {
151 if (attr.second->type != AST_CONSTANT)
152 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
153 attr.first.c_str(), that->filename.c_str(), that->linenum);
154 cell->attributes[attr.first] = attr.second->asAttrConst();
155 }
156
157 cell->parameters["\\WIDTH"] = RTLIL::Const(left.size());
158
159 cell->set("\\A", right);
160 cell->set("\\B", left);
161 cell->set("\\S", cond);
162 cell->set("\\Y", wire);
163
164 return wire;
165 }
166
167 // helper class for converting AST always nodes to RTLIL processes
168 struct AST_INTERNAL::ProcessGenerator
169 {
170 // input and output structures
171 AstNode *always;
172 RTLIL::SigSpec initSyncSignals;
173 RTLIL::Process *proc;
174 const RTLIL::SigSpec &outputSignals;
175
176 // This always points to the RTLIL::CaseRule beeing filled at the moment
177 RTLIL::CaseRule *current_case;
178
179 // This two variables contain the replacement pattern to be used in the right hand side
180 // of an assignment. E.g. in the code "foo = bar; foo = func(foo);" the foo in the right
181 // hand side of the 2nd assignment needs to be replace with the temporary signal holding
182 // the value assigned in the first assignment. So when the first assignement is processed
183 // the according information is appended to subst_rvalue_from and subst_rvalue_to.
184 RTLIL::SigSpec subst_rvalue_from, subst_rvalue_to;
185
186 // This two variables contain the replacement pattern to be used in the left hand side
187 // of an assignment. E.g. in the code "always @(posedge clk) foo <= bar" the signal bar
188 // should not be connected to the signal foo. Instead it must be connected to the temporary
189 // signal that is used as input for the register that drives the signal foo.
190 RTLIL::SigSpec subst_lvalue_from, subst_lvalue_to;
191
192 // The code here generates a number of temprorary signal for each output register. This
193 // map helps generating nice numbered names for all this temporary signals.
194 std::map<RTLIL::Wire*, int> new_temp_count;
195
196 // Buffer for generating the init action
197 RTLIL::SigSpec init_lvalue, init_rvalue;
198
199 ProcessGenerator(AstNode *always, RTLIL::SigSpec initSyncSignalsArg = RTLIL::SigSpec()) : always(always), initSyncSignals(initSyncSignalsArg), outputSignals(subst_lvalue_from)
200 {
201 // generate process and simple root case
202 proc = new RTLIL::Process;
203 proc->attributes["\\src"] = stringf("%s:%d", always->filename.c_str(), always->linenum);
204 proc->name = stringf("$proc$%s:%d$%d", always->filename.c_str(), always->linenum, RTLIL::autoidx++);
205 for (auto &attr : always->attributes) {
206 if (attr.second->type != AST_CONSTANT)
207 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
208 attr.first.c_str(), always->filename.c_str(), always->linenum);
209 proc->attributes[attr.first] = attr.second->asAttrConst();
210 }
211 current_module->processes[proc->name] = proc;
212 current_case = &proc->root_case;
213
214 // create initial temporary signal for all output registers
215 collect_lvalues(subst_lvalue_from, always, true, true);
216 subst_lvalue_to = new_temp_signal(subst_lvalue_from);
217
218 bool found_anyedge_syncs = false;
219 for (auto child : always->children)
220 if (child->type == AST_EDGE)
221 found_anyedge_syncs = true;
222
223 if (found_anyedge_syncs) {
224 log("Note: Assuming pure combinatorial block at %s:%d in\n", always->filename.c_str(), always->linenum);
225 log("compliance with IEC 62142(E):2005 / IEEE Std. 1364.1(E):2002. Recommending\n");
226 log("use of @* instead of @(...) for better match of synthesis and simulation.\n");
227 }
228
229 // create syncs for the process
230 bool found_clocked_sync = false;
231 for (auto child : always->children)
232 if (child->type == AST_POSEDGE || child->type == AST_NEGEDGE) {
233 found_clocked_sync = true;
234 if (found_anyedge_syncs)
235 log_error("Found non-synthesizable event list at %s:%d!\n", always->filename.c_str(), always->linenum);
236 RTLIL::SyncRule *syncrule = new RTLIL::SyncRule;
237 syncrule->type = child->type == AST_POSEDGE ? RTLIL::STp : RTLIL::STn;
238 syncrule->signal = child->children[0]->genRTLIL();
239 addChunkActions(syncrule->actions, subst_lvalue_from, subst_lvalue_to, true);
240 proc->syncs.push_back(syncrule);
241 }
242 if (proc->syncs.empty()) {
243 RTLIL::SyncRule *syncrule = new RTLIL::SyncRule;
244 syncrule->type = RTLIL::STa;
245 syncrule->signal = RTLIL::SigSpec();
246 addChunkActions(syncrule->actions, subst_lvalue_from, subst_lvalue_to, true);
247 proc->syncs.push_back(syncrule);
248 }
249
250 // create initial assignments for the temporary signals
251 if ((flag_nolatches || always->get_bool_attribute("\\nolatches") || current_module->get_bool_attribute("\\nolatches")) && !found_clocked_sync) {
252 subst_rvalue_from = subst_lvalue_from;
253 subst_rvalue_to = RTLIL::SigSpec(RTLIL::State::Sx, subst_rvalue_from.size());
254 } else {
255 addChunkActions(current_case->actions, subst_lvalue_to, subst_lvalue_from);
256 }
257
258 // process the AST
259 for (auto child : always->children)
260 if (child->type == AST_BLOCK)
261 processAst(child);
262
263 if (initSyncSignals.size() > 0)
264 {
265 RTLIL::SyncRule *sync = new RTLIL::SyncRule;
266 sync->type = RTLIL::SyncType::STi;
267 proc->syncs.push_back(sync);
268
269 log_assert(init_lvalue.size() == init_rvalue.size());
270
271 int offset = 0;
272 for (auto &init_lvalue_c : init_lvalue.chunks()) {
273 RTLIL::SigSpec lhs = init_lvalue_c;
274 RTLIL::SigSpec rhs = init_rvalue.extract(offset, init_lvalue_c.width);
275 sync->actions.push_back(RTLIL::SigSig(lhs, rhs));
276 offset += lhs.size();
277 }
278 }
279 }
280
281 // create new temporary signals
282 RTLIL::SigSpec new_temp_signal(RTLIL::SigSpec sig)
283 {
284 std::vector<RTLIL::SigChunk> chunks = sig.chunks();
285
286 for (int i = 0; i < SIZE(chunks); i++)
287 {
288 RTLIL::SigChunk &chunk = chunks[i];
289 if (chunk.wire == NULL)
290 continue;
291
292 std::string wire_name;
293 do {
294 wire_name = stringf("$%d%s[%d:%d]", new_temp_count[chunk.wire]++,
295 chunk.wire->name.c_str(), chunk.width+chunk.offset-1, chunk.offset);;
296 if (chunk.wire->name.find('$') != std::string::npos)
297 wire_name += stringf("$%d", RTLIL::autoidx++);
298 } while (current_module->wires_.count(wire_name) > 0);
299
300 RTLIL::Wire *wire = current_module->addWire(wire_name, chunk.width);
301 wire->attributes["\\src"] = stringf("%s:%d", always->filename.c_str(), always->linenum);
302
303 chunk.wire = wire;
304 chunk.offset = 0;
305 }
306
307 return chunks;
308 }
309
310 // recursively traverse the AST an collect all assigned signals
311 void collect_lvalues(RTLIL::SigSpec &reg, AstNode *ast, bool type_eq, bool type_le, bool run_sort_and_unify = true)
312 {
313 switch (ast->type)
314 {
315 case AST_CASE:
316 for (auto child : ast->children)
317 if (child != ast->children[0]) {
318 log_assert(child->type == AST_COND);
319 collect_lvalues(reg, child, type_eq, type_le, false);
320 }
321 break;
322
323 case AST_COND:
324 case AST_ALWAYS:
325 case AST_INITIAL:
326 for (auto child : ast->children)
327 if (child->type == AST_BLOCK)
328 collect_lvalues(reg, child, type_eq, type_le, false);
329 break;
330
331 case AST_BLOCK:
332 for (auto child : ast->children) {
333 if (child->type == AST_ASSIGN_EQ && type_eq)
334 reg.append(child->children[0]->genRTLIL());
335 if (child->type == AST_ASSIGN_LE && type_le)
336 reg.append(child->children[0]->genRTLIL());
337 if (child->type == AST_CASE || child->type == AST_BLOCK)
338 collect_lvalues(reg, child, type_eq, type_le, false);
339 }
340 break;
341
342 default:
343 log_abort();
344 }
345
346 if (run_sort_and_unify)
347 reg.sort_and_unify();
348 }
349
350 // remove all assignments to the given signal pattern in a case and all its children.
351 // e.g. when the last statement in the code "a = 23; if (b) a = 42; a = 0;" is processed this
352 // function is called to clean up the first two assignments as they are overwritten by
353 // the third assignment.
354 void removeSignalFromCaseTree(RTLIL::SigSpec pattern, RTLIL::CaseRule *cs)
355 {
356 for (auto it = cs->actions.begin(); it != cs->actions.end(); it++)
357 it->first.remove2(pattern, &it->second);
358
359 for (auto it = cs->switches.begin(); it != cs->switches.end(); it++)
360 for (auto it2 = (*it)->cases.begin(); it2 != (*it)->cases.end(); it2++)
361 removeSignalFromCaseTree(pattern, *it2);
362 }
363
364 // add an assignment (aka "action") but split it up in chunks. this way huge assignments
365 // are avoided and the generated $mux cells have a more "natural" size.
366 void addChunkActions(std::vector<RTLIL::SigSig> &actions, RTLIL::SigSpec lvalue, RTLIL::SigSpec rvalue, bool inSyncRule = false)
367 {
368 if (inSyncRule && initSyncSignals.size() > 0) {
369 init_lvalue.append(lvalue.extract(initSyncSignals));
370 init_rvalue.append(lvalue.extract(initSyncSignals, &rvalue));
371 lvalue.remove2(initSyncSignals, &rvalue);
372 }
373 log_assert(lvalue.size() == rvalue.size());
374
375 int offset = 0;
376 for (auto &lvalue_c : lvalue.chunks()) {
377 RTLIL::SigSpec lhs = lvalue_c;
378 RTLIL::SigSpec rhs = rvalue.extract(offset, lvalue_c.width);
379 if (inSyncRule && lvalue_c.wire && lvalue_c.wire->get_bool_attribute("\\nosync"))
380 rhs = RTLIL::SigSpec(RTLIL::State::Sx, rhs.size());
381 actions.push_back(RTLIL::SigSig(lhs, rhs));
382 offset += lhs.size();
383 }
384 }
385
386 // recursively process the AST and fill the RTLIL::Process
387 void processAst(AstNode *ast)
388 {
389 switch (ast->type)
390 {
391 case AST_BLOCK:
392 for (auto child : ast->children)
393 processAst(child);
394 break;
395
396 case AST_ASSIGN_EQ:
397 case AST_ASSIGN_LE:
398 {
399 RTLIL::SigSpec unmapped_lvalue = ast->children[0]->genRTLIL(), lvalue = unmapped_lvalue;
400 RTLIL::SigSpec rvalue = ast->children[1]->genWidthRTLIL(lvalue.size(), &subst_rvalue_from, &subst_rvalue_to);
401 lvalue.replace(subst_lvalue_from, subst_lvalue_to);
402
403 if (ast->type == AST_ASSIGN_EQ) {
404 subst_rvalue_from.remove2(unmapped_lvalue, &subst_rvalue_to);
405 subst_rvalue_from.append(unmapped_lvalue);
406 subst_rvalue_to.append(rvalue);
407 }
408
409 removeSignalFromCaseTree(lvalue, current_case);
410 current_case->actions.push_back(RTLIL::SigSig(lvalue, rvalue));
411 }
412 break;
413
414 case AST_CASE:
415 {
416 RTLIL::SwitchRule *sw = new RTLIL::SwitchRule;
417 sw->signal = ast->children[0]->genWidthRTLIL(-1, &subst_rvalue_from, &subst_rvalue_to);
418 current_case->switches.push_back(sw);
419
420 for (auto &attr : ast->attributes) {
421 if (attr.second->type != AST_CONSTANT)
422 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
423 attr.first.c_str(), ast->filename.c_str(), ast->linenum);
424 sw->attributes[attr.first] = attr.second->asAttrConst();
425 }
426
427 RTLIL::SigSpec this_case_eq_lvalue;
428 collect_lvalues(this_case_eq_lvalue, ast, true, false);
429
430 RTLIL::SigSpec this_case_eq_ltemp = new_temp_signal(this_case_eq_lvalue);
431
432 RTLIL::SigSpec this_case_eq_rvalue = this_case_eq_lvalue;
433 this_case_eq_rvalue.replace(subst_rvalue_from, subst_rvalue_to);
434
435 RTLIL::SigSpec backup_subst_lvalue_from = subst_lvalue_from;
436 RTLIL::SigSpec backup_subst_lvalue_to = subst_lvalue_to;
437
438 RTLIL::SigSpec backup_subst_rvalue_from = subst_rvalue_from;
439 RTLIL::SigSpec backup_subst_rvalue_to = subst_rvalue_to;
440
441 RTLIL::CaseRule *default_case = NULL;
442 RTLIL::CaseRule *last_generated_case = NULL;
443 for (auto child : ast->children)
444 {
445 if (child == ast->children[0])
446 continue;
447 log_assert(child->type == AST_COND);
448
449 subst_lvalue_from = backup_subst_lvalue_from;
450 subst_lvalue_to = backup_subst_lvalue_to;
451
452 subst_rvalue_from = backup_subst_rvalue_from;
453 subst_rvalue_to = backup_subst_rvalue_to;
454
455 subst_lvalue_from.remove2(this_case_eq_lvalue, &subst_lvalue_to);
456 subst_lvalue_from.append(this_case_eq_lvalue);
457 subst_lvalue_to.append(this_case_eq_ltemp);
458
459 RTLIL::CaseRule *backup_case = current_case;
460 current_case = new RTLIL::CaseRule;
461 last_generated_case = current_case;
462 addChunkActions(current_case->actions, this_case_eq_ltemp, this_case_eq_rvalue);
463 for (auto node : child->children) {
464 if (node->type == AST_DEFAULT)
465 default_case = current_case;
466 else if (node->type == AST_BLOCK)
467 processAst(node);
468 else
469 current_case->compare.push_back(node->genWidthRTLIL(sw->signal.size(), &subst_rvalue_from, &subst_rvalue_to));
470 }
471 if (default_case != current_case)
472 sw->cases.push_back(current_case);
473 else
474 log_assert(current_case->compare.size() == 0);
475 current_case = backup_case;
476 }
477
478 if (last_generated_case != NULL && ast->get_bool_attribute("\\full_case") && default_case == NULL) {
479 last_generated_case->compare.clear();
480 } else {
481 if (default_case == NULL) {
482 default_case = new RTLIL::CaseRule;
483 addChunkActions(default_case->actions, this_case_eq_ltemp, this_case_eq_rvalue);
484 }
485 sw->cases.push_back(default_case);
486 }
487
488 subst_lvalue_from = backup_subst_lvalue_from;
489 subst_lvalue_to = backup_subst_lvalue_to;
490
491 subst_rvalue_from = backup_subst_rvalue_from;
492 subst_rvalue_to = backup_subst_rvalue_to;
493
494 subst_rvalue_from.remove2(this_case_eq_lvalue, &subst_rvalue_to);
495 subst_rvalue_from.append(this_case_eq_lvalue);
496 subst_rvalue_to.append(this_case_eq_ltemp);
497
498 this_case_eq_lvalue.replace(subst_lvalue_from, subst_lvalue_to);
499 removeSignalFromCaseTree(this_case_eq_lvalue, current_case);
500 addChunkActions(current_case->actions, this_case_eq_lvalue, this_case_eq_ltemp);
501 }
502 break;
503
504 case AST_WIRE:
505 log_error("Found wire declaration in block without label at at %s:%d!\n", ast->filename.c_str(), ast->linenum);
506 break;
507
508 case AST_TCALL:
509 case AST_FOR:
510 break;
511
512 default:
513 log_abort();
514 }
515 }
516 };
517
518 // detect sign and width of an expression
519 void AstNode::detectSignWidthWorker(int &width_hint, bool &sign_hint, bool *found_real)
520 {
521 std::string type_name;
522 bool sub_sign_hint = true;
523 int sub_width_hint = -1;
524 int this_width = 0;
525 AstNode *range = NULL;
526 AstNode *id_ast = NULL;
527
528 bool local_found_real = false;
529 if (found_real == NULL)
530 found_real = &local_found_real;
531
532 switch (type)
533 {
534 case AST_CONSTANT:
535 width_hint = std::max(width_hint, int(bits.size()));
536 if (!is_signed)
537 sign_hint = false;
538 break;
539
540 case AST_REALVALUE:
541 *found_real = true;
542 width_hint = std::max(width_hint, 32);
543 break;
544
545 case AST_IDENTIFIER:
546 id_ast = id2ast;
547 if (id_ast == NULL && current_scope.count(str))
548 id_ast = current_scope.at(str);
549 if (!id_ast)
550 log_error("Failed to resolve identifier %s for width detection at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
551 if (id_ast->type == AST_PARAMETER || id_ast->type == AST_LOCALPARAM) {
552 if (id_ast->children.size() > 1 && id_ast->children[1]->range_valid) {
553 this_width = id_ast->children[1]->range_left - id_ast->children[1]->range_right + 1;
554 } else
555 if (id_ast->children[0]->type == AST_CONSTANT) {
556 this_width = id_ast->children[0]->bits.size();
557 } else
558 log_error("Failed to detect width for parameter %s at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
559 if (children.size() != 0)
560 range = children[0];
561 } else if (id_ast->type == AST_WIRE || id_ast->type == AST_AUTOWIRE) {
562 if (!id_ast->range_valid) {
563 if (id_ast->type == AST_AUTOWIRE)
564 this_width = 1;
565 else {
566 // current_ast_mod->dumpAst(NULL, "mod> ");
567 // log("---\n");
568 // id_ast->dumpAst(NULL, "decl> ");
569 // dumpAst(NULL, "ref> ");
570 log_error("Failed to detect with of signal access `%s' at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
571 }
572 } else {
573 this_width = id_ast->range_left - id_ast->range_right + 1;
574 if (children.size() != 0)
575 range = children[0];
576 }
577 } else if (id_ast->type == AST_GENVAR) {
578 this_width = 32;
579 } else if (id_ast->type == AST_MEMORY) {
580 if (!id_ast->children[0]->range_valid)
581 log_error("Failed to detect with of memory access `%s' at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
582 this_width = id_ast->children[0]->range_left - id_ast->children[0]->range_right + 1;
583 } else
584 log_error("Failed to detect width for identifier %s at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
585 if (range) {
586 if (range->children.size() == 1)
587 this_width = 1;
588 else if (!range->range_valid) {
589 AstNode *left_at_zero_ast = children[0]->children[0]->clone();
590 AstNode *right_at_zero_ast = children[0]->children.size() >= 2 ? children[0]->children[1]->clone() : left_at_zero_ast->clone();
591 while (left_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
592 while (right_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
593 if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
594 log_error("Unsupported expression on dynamic range select on signal `%s' at %s:%d!\n",
595 str.c_str(), filename.c_str(), linenum);
596 this_width = left_at_zero_ast->integer - right_at_zero_ast->integer + 1;
597 delete left_at_zero_ast;
598 delete right_at_zero_ast;
599 } else
600 this_width = range->range_left - range->range_right + 1;
601 sign_hint = false;
602 } else
603 width_hint = std::max(width_hint, this_width);
604 if (!id_ast->is_signed)
605 sign_hint = false;
606 break;
607
608 case AST_TO_BITS:
609 while (children[0]->simplify(true, false, false, 1, -1, false, false) == true) { }
610 if (children[0]->type != AST_CONSTANT)
611 log_error("Left operand of tobits expression is not constant at %s:%d!\n", filename.c_str(), linenum);
612 children[1]->detectSignWidthWorker(sub_width_hint, sign_hint);
613 width_hint = std::max(width_hint, children[0]->bitsAsConst().as_int());
614 break;
615
616 case AST_TO_SIGNED:
617 children.at(0)->detectSignWidthWorker(width_hint, sub_sign_hint);
618 break;
619
620 case AST_TO_UNSIGNED:
621 children.at(0)->detectSignWidthWorker(width_hint, sub_sign_hint);
622 sign_hint = false;
623 break;
624
625 case AST_CONCAT:
626 for (auto child : children) {
627 sub_width_hint = 0;
628 sub_sign_hint = true;
629 child->detectSignWidthWorker(sub_width_hint, sub_sign_hint);
630 this_width += sub_width_hint;
631 }
632 width_hint = std::max(width_hint, this_width);
633 sign_hint = false;
634 break;
635
636 case AST_REPLICATE:
637 while (children[0]->simplify(true, false, false, 1, -1, false, true) == true) { }
638 if (children[0]->type != AST_CONSTANT)
639 log_error("Left operand of replicate expression is not constant at %s:%d!\n", filename.c_str(), linenum);
640 children[1]->detectSignWidthWorker(sub_width_hint, sub_sign_hint);
641 width_hint = std::max(width_hint, children[0]->bitsAsConst().as_int() * sub_width_hint);
642 sign_hint = false;
643 break;
644
645 case AST_NEG:
646 case AST_BIT_NOT:
647 case AST_POS:
648 children[0]->detectSignWidthWorker(width_hint, sign_hint, found_real);
649 break;
650
651 case AST_BIT_AND:
652 case AST_BIT_OR:
653 case AST_BIT_XOR:
654 case AST_BIT_XNOR:
655 for (auto child : children)
656 child->detectSignWidthWorker(width_hint, sign_hint, found_real);
657 break;
658
659 case AST_REDUCE_AND:
660 case AST_REDUCE_OR:
661 case AST_REDUCE_XOR:
662 case AST_REDUCE_XNOR:
663 case AST_REDUCE_BOOL:
664 width_hint = std::max(width_hint, 1);
665 sign_hint = false;
666 break;
667
668 case AST_SHIFT_LEFT:
669 case AST_SHIFT_RIGHT:
670 case AST_SHIFT_SLEFT:
671 case AST_SHIFT_SRIGHT:
672 case AST_POW:
673 children[0]->detectSignWidthWorker(width_hint, sign_hint, found_real);
674 break;
675
676 case AST_LT:
677 case AST_LE:
678 case AST_EQ:
679 case AST_NE:
680 case AST_EQX:
681 case AST_NEX:
682 case AST_GE:
683 case AST_GT:
684 width_hint = std::max(width_hint, 1);
685 sign_hint = false;
686 break;
687
688 case AST_ADD:
689 case AST_SUB:
690 case AST_MUL:
691 case AST_DIV:
692 case AST_MOD:
693 for (auto child : children)
694 child->detectSignWidthWorker(width_hint, sign_hint, found_real);
695 break;
696
697 case AST_LOGIC_AND:
698 case AST_LOGIC_OR:
699 case AST_LOGIC_NOT:
700 width_hint = std::max(width_hint, 1);
701 sign_hint = false;
702 break;
703
704 case AST_TERNARY:
705 children.at(1)->detectSignWidthWorker(width_hint, sign_hint, found_real);
706 children.at(2)->detectSignWidthWorker(width_hint, sign_hint, found_real);
707 break;
708
709 case AST_MEMRD:
710 if (!id2ast->is_signed)
711 sign_hint = false;
712 if (!id2ast->children[0]->range_valid)
713 log_error("Failed to detect with of memory access `%s' at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
714 this_width = id2ast->children[0]->range_left - id2ast->children[0]->range_right + 1;
715 width_hint = std::max(width_hint, this_width);
716 break;
717
718 // everything should have been handled above -> print error if not.
719 default:
720 for (auto f : log_files)
721 current_ast->dumpAst(f, "verilog-ast> ");
722 log_error("Don't know how to detect sign and width for %s node at %s:%d!\n",
723 type2str(type).c_str(), filename.c_str(), linenum);
724 }
725
726 if (*found_real)
727 sign_hint = true;
728 }
729
730 // detect sign and width of an expression
731 void AstNode::detectSignWidth(int &width_hint, bool &sign_hint, bool *found_real)
732 {
733 width_hint = -1;
734 sign_hint = true;
735 if (found_real)
736 *found_real = false;
737 detectSignWidthWorker(width_hint, sign_hint, found_real);
738 }
739
740 // create RTLIL from an AST node
741 // all generated cells, wires and processes are added to the module pointed to by 'current_module'
742 // when the AST node is an expression (AST_ADD, AST_BIT_XOR, etc.), the result signal is returned.
743 //
744 // note that this function is influenced by a number of global variables that might be set when
745 // called from genWidthRTLIL(). also note that this function recursively calls itself to transform
746 // larger expressions into a netlist of cells.
747 RTLIL::SigSpec AstNode::genRTLIL(int width_hint, bool sign_hint)
748 {
749 // in the following big switch() statement there are some uses of
750 // Clifford's Device (http://www.clifford.at/cfun/cliffdev/). In this
751 // cases this variable is used to hold the type of the cell that should
752 // be instanciated for this type of AST node.
753 std::string type_name;
754
755 current_filename = filename;
756 set_line_num(linenum);
757
758 switch (type)
759 {
760 // simply ignore this nodes.
761 // they are eighter leftovers from simplify() or are referenced by other nodes
762 // and are only accessed here thru this references
763 case AST_TASK:
764 case AST_FUNCTION:
765 case AST_AUTOWIRE:
766 case AST_LOCALPARAM:
767 case AST_DEFPARAM:
768 case AST_GENVAR:
769 case AST_GENFOR:
770 case AST_GENBLOCK:
771 case AST_GENIF:
772 case AST_GENCASE:
773 break;
774
775 // remember the parameter, needed for example in techmap
776 case AST_PARAMETER:
777 current_module->avail_parameters.insert(str);
778 break;
779
780 // create an RTLIL::Wire for an AST_WIRE node
781 case AST_WIRE: {
782 if (current_module->wires_.count(str) != 0)
783 log_error("Re-definition of signal `%s' at %s:%d!\n",
784 str.c_str(), filename.c_str(), linenum);
785 if (!range_valid)
786 log_error("Signal `%s' with non-constant width at %s:%d!\n",
787 str.c_str(), filename.c_str(), linenum);
788
789 log_assert(range_left >= range_right || (range_left == -1 && range_right == 0));
790
791 RTLIL::Wire *wire = current_module->addWire(str, range_left - range_right + 1);
792 wire->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
793 wire->start_offset = range_right;
794 wire->port_id = port_id;
795 wire->port_input = is_input;
796 wire->port_output = is_output;
797 wire->upto = range_swapped;
798
799 for (auto &attr : attributes) {
800 if (attr.second->type != AST_CONSTANT)
801 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
802 attr.first.c_str(), filename.c_str(), linenum);
803 wire->attributes[attr.first] = attr.second->asAttrConst();
804 }
805 }
806 break;
807
808 // create an RTLIL::Memory for an AST_MEMORY node
809 case AST_MEMORY: {
810 if (current_module->memories.count(str) != 0)
811 log_error("Re-definition of memory `%s' at %s:%d!\n",
812 str.c_str(), filename.c_str(), linenum);
813
814 log_assert(children.size() >= 2);
815 log_assert(children[0]->type == AST_RANGE);
816 log_assert(children[1]->type == AST_RANGE);
817
818 if (!children[0]->range_valid || !children[1]->range_valid)
819 log_error("Memory `%s' with non-constant width or size at %s:%d!\n",
820 str.c_str(), filename.c_str(), linenum);
821
822 RTLIL::Memory *memory = new RTLIL::Memory;
823 memory->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
824 memory->name = str;
825 memory->width = children[0]->range_left - children[0]->range_right + 1;
826 memory->start_offset = children[0]->range_right;
827 memory->size = children[1]->range_left - children[1]->range_right;
828 current_module->memories[memory->name] = memory;
829
830 if (memory->size < 0)
831 memory->size *= -1;
832 memory->size += std::min(children[1]->range_left, children[1]->range_right) + 1;
833
834 for (auto &attr : attributes) {
835 if (attr.second->type != AST_CONSTANT)
836 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
837 attr.first.c_str(), filename.c_str(), linenum);
838 memory->attributes[attr.first] = attr.second->asAttrConst();
839 }
840 }
841 break;
842
843 // simply return the corresponding RTLIL::SigSpec for an AST_CONSTANT node
844 case AST_CONSTANT:
845 {
846 if (width_hint < 0)
847 detectSignWidth(width_hint, sign_hint);
848
849 is_signed = sign_hint;
850 return RTLIL::SigSpec(bitsAsConst());
851 }
852
853 case AST_REALVALUE:
854 {
855 RTLIL::SigSpec sig = realAsConst(width_hint);
856 log("Warning: converting real value %e to binary %s at %s:%d.\n",
857 realvalue, log_signal(sig), filename.c_str(), linenum);
858 return sig;
859 }
860
861 // simply return the corresponding RTLIL::SigSpec for an AST_IDENTIFIER node
862 // for identifiers with dynamic bit ranges (e.g. "foo[bar]" or "foo[bar+3:bar]") a
863 // shifter cell is created and the output signal of this cell is returned
864 case AST_IDENTIFIER:
865 {
866 RTLIL::Wire *wire = NULL;
867 RTLIL::SigChunk chunk;
868
869 if (id2ast && id2ast->type == AST_AUTOWIRE && current_module->wires_.count(str) == 0) {
870 RTLIL::Wire *wire = current_module->addWire(str);
871 wire->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
872 wire->name = str;
873 if (flag_autowire)
874 log("Warning: Identifier `%s' is implicitly declared at %s:%d.\n", str.c_str(), filename.c_str(), linenum);
875 else
876 log_error("Identifier `%s' is implicitly declared at %s:%d and `default_nettype is set to none.\n", str.c_str(), filename.c_str(), linenum);
877 }
878 else if (id2ast->type == AST_PARAMETER || id2ast->type == AST_LOCALPARAM) {
879 if (id2ast->children[0]->type != AST_CONSTANT)
880 log_error("Parameter %s does not evaluate to constant value at %s:%d!\n",
881 str.c_str(), filename.c_str(), linenum);
882 chunk = RTLIL::Const(id2ast->children[0]->bits);
883 goto use_const_chunk;
884 }
885 else if (!id2ast || (id2ast->type != AST_WIRE && id2ast->type != AST_AUTOWIRE &&
886 id2ast->type != AST_MEMORY) || current_module->wires_.count(str) == 0)
887 log_error("Identifier `%s' doesn't map to any signal at %s:%d!\n",
888 str.c_str(), filename.c_str(), linenum);
889
890 if (id2ast->type == AST_MEMORY)
891 log_error("Identifier `%s' does map to an unexpanded memory at %s:%d!\n",
892 str.c_str(), filename.c_str(), linenum);
893
894 wire = current_module->wires_[str];
895 chunk.wire = wire;
896 chunk.width = wire->width;
897 chunk.offset = 0;
898
899 use_const_chunk:
900 if (children.size() != 0) {
901 log_assert(children[0]->type == AST_RANGE);
902 if (!children[0]->range_valid) {
903 AstNode *left_at_zero_ast = children[0]->children[0]->clone();
904 AstNode *right_at_zero_ast = children[0]->children.size() >= 2 ? children[0]->children[1]->clone() : left_at_zero_ast->clone();
905 while (left_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
906 while (right_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
907 if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
908 log_error("Unsupported expression on dynamic range select on signal `%s' at %s:%d!\n",
909 str.c_str(), filename.c_str(), linenum);
910 int width = left_at_zero_ast->integer - right_at_zero_ast->integer + 1;
911 AstNode *fake_ast = new AstNode(AST_NONE, clone(), children[0]->children.size() >= 2 ?
912 children[0]->children[1]->clone() : children[0]->children[0]->clone());
913 fake_ast->children[0]->delete_children();
914 RTLIL::SigSpec sig = binop2rtlil(fake_ast, "$shr", width,
915 fake_ast->children[0]->genRTLIL(), !wire->upto ? fake_ast->children[1]->genRTLIL() :
916 current_module->Sub(NEW_ID, RTLIL::SigSpec(wire->width - width), fake_ast->children[1]->genRTLIL()));
917 delete left_at_zero_ast;
918 delete right_at_zero_ast;
919 delete fake_ast;
920 return sig;
921 } else {
922 if (children[0]->range_left > id2ast->range_left || id2ast->range_right > children[0]->range_right)
923 log_error("Range select out of bounds on signal `%s' at %s:%d!\n",
924 str.c_str(), filename.c_str(), linenum);
925 chunk.width = children[0]->range_left - children[0]->range_right + 1;
926 chunk.offset = children[0]->range_right - id2ast->range_right;
927 if (wire->upto)
928 chunk.offset = wire->width - (chunk.offset + chunk.width);
929 }
930 }
931
932 RTLIL::SigSpec sig(chunk);
933
934 if (genRTLIL_subst_from && genRTLIL_subst_to)
935 sig.replace(*genRTLIL_subst_from, *genRTLIL_subst_to);
936
937 is_signed = children.size() > 0 ? false : id2ast->is_signed && sign_hint;
938 return sig;
939 }
940
941 // just pass thru the signal. the parent will evaluate the is_signed property and interpret the SigSpec accordingly
942 case AST_TO_SIGNED:
943 case AST_TO_UNSIGNED: {
944 RTLIL::SigSpec sig = children[0]->genRTLIL();
945 if (sig.size() < width_hint)
946 sig.extend_u0(width_hint, sign_hint);
947 is_signed = sign_hint;
948 return sig;
949 }
950
951 // concatenation of signals can be done directly using RTLIL::SigSpec
952 case AST_CONCAT: {
953 RTLIL::SigSpec sig;
954 for (auto it = children.begin(); it != children.end(); it++)
955 sig.append((*it)->genRTLIL());
956 if (sig.size() < width_hint)
957 sig.extend_u0(width_hint, false);
958 return sig;
959 }
960
961 // replication of signals can be done directly using RTLIL::SigSpec
962 case AST_REPLICATE: {
963 RTLIL::SigSpec left = children[0]->genRTLIL();
964 RTLIL::SigSpec right = children[1]->genRTLIL();
965 if (!left.is_fully_const())
966 log_error("Left operand of replicate expression is not constant at %s:%d!\n", filename.c_str(), linenum);
967 int count = left.as_int();
968 RTLIL::SigSpec sig;
969 for (int i = 0; i < count; i++)
970 sig.append(right);
971 if (sig.size() < width_hint)
972 sig.extend_u0(width_hint, false);
973 is_signed = false;
974 return sig;
975 }
976
977 // generate cells for unary operations: $not, $pos, $neg
978 if (0) { case AST_BIT_NOT: type_name = "$not"; }
979 if (0) { case AST_POS: type_name = "$pos"; }
980 if (0) { case AST_NEG: type_name = "$neg"; }
981 {
982 RTLIL::SigSpec arg = children[0]->genRTLIL(width_hint, sign_hint);
983 is_signed = children[0]->is_signed;
984 int width = arg.size();
985 if (width_hint > 0) {
986 width = width_hint;
987 widthExtend(this, arg, width, is_signed, "$pos");
988 }
989 return uniop2rtlil(this, type_name, width, arg);
990 }
991
992 // generate cells for binary operations: $and, $or, $xor, $xnor
993 if (0) { case AST_BIT_AND: type_name = "$and"; }
994 if (0) { case AST_BIT_OR: type_name = "$or"; }
995 if (0) { case AST_BIT_XOR: type_name = "$xor"; }
996 if (0) { case AST_BIT_XNOR: type_name = "$xnor"; }
997 {
998 if (width_hint < 0)
999 detectSignWidth(width_hint, sign_hint);
1000 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1001 RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint);
1002 int width = std::max(left.size(), right.size());
1003 if (width_hint > 0)
1004 width = width_hint;
1005 is_signed = children[0]->is_signed && children[1]->is_signed;
1006 return binop2rtlil(this, type_name, width, left, right);
1007 }
1008
1009 // generate cells for unary operations: $reduce_and, $reduce_or, $reduce_xor, $reduce_xnor
1010 if (0) { case AST_REDUCE_AND: type_name = "$reduce_and"; }
1011 if (0) { case AST_REDUCE_OR: type_name = "$reduce_or"; }
1012 if (0) { case AST_REDUCE_XOR: type_name = "$reduce_xor"; }
1013 if (0) { case AST_REDUCE_XNOR: type_name = "$reduce_xnor"; }
1014 {
1015 RTLIL::SigSpec arg = children[0]->genRTLIL();
1016 RTLIL::SigSpec sig = uniop2rtlil(this, type_name, std::max(width_hint, 1), arg);
1017 return sig;
1018 }
1019
1020 // generate cells for unary operations: $reduce_bool
1021 // (this is actually just an $reduce_or, but for clearity a different cell type is used)
1022 if (0) { case AST_REDUCE_BOOL: type_name = "$reduce_bool"; }
1023 {
1024 RTLIL::SigSpec arg = children[0]->genRTLIL();
1025 RTLIL::SigSpec sig = arg.size() > 1 ? uniop2rtlil(this, type_name, std::max(width_hint, 1), arg) : arg;
1026 return sig;
1027 }
1028
1029 // generate cells for binary operations: $shl, $shr, $sshl, $sshr
1030 if (0) { case AST_SHIFT_LEFT: type_name = "$shl"; }
1031 if (0) { case AST_SHIFT_RIGHT: type_name = "$shr"; }
1032 if (0) { case AST_SHIFT_SLEFT: type_name = "$sshl"; }
1033 if (0) { case AST_SHIFT_SRIGHT: type_name = "$sshr"; }
1034 {
1035 if (width_hint < 0)
1036 detectSignWidth(width_hint, sign_hint);
1037 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1038 RTLIL::SigSpec right = children[1]->genRTLIL();
1039 int width = width_hint > 0 ? width_hint : left.size();
1040 is_signed = children[0]->is_signed;
1041 return binop2rtlil(this, type_name, width, left, right);
1042 }
1043
1044 // generate cells for binary operations: $pow
1045 case AST_POW:
1046 {
1047 int right_width;
1048 bool right_signed;
1049 children[1]->detectSignWidth(right_width, right_signed);
1050 if (width_hint < 0)
1051 detectSignWidth(width_hint, sign_hint);
1052 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1053 RTLIL::SigSpec right = children[1]->genRTLIL(right_width, right_signed);
1054 int width = width_hint > 0 ? width_hint : left.size();
1055 is_signed = children[0]->is_signed;
1056 if (!flag_noopt && left.is_fully_const() && left.as_int() == 2 && !right_signed)
1057 return binop2rtlil(this, "$shl", width, RTLIL::SigSpec(1, left.size()), right);
1058 return binop2rtlil(this, "$pow", width, left, right);
1059 }
1060
1061 // generate cells for binary operations: $lt, $le, $eq, $ne, $ge, $gt
1062 if (0) { case AST_LT: type_name = "$lt"; }
1063 if (0) { case AST_LE: type_name = "$le"; }
1064 if (0) { case AST_EQ: type_name = "$eq"; }
1065 if (0) { case AST_NE: type_name = "$ne"; }
1066 if (0) { case AST_EQX: type_name = "$eqx"; }
1067 if (0) { case AST_NEX: type_name = "$nex"; }
1068 if (0) { case AST_GE: type_name = "$ge"; }
1069 if (0) { case AST_GT: type_name = "$gt"; }
1070 {
1071 int width = std::max(width_hint, 1);
1072 width_hint = -1, sign_hint = true;
1073 children[0]->detectSignWidthWorker(width_hint, sign_hint);
1074 children[1]->detectSignWidthWorker(width_hint, sign_hint);
1075 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1076 RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint);
1077 RTLIL::SigSpec sig = binop2rtlil(this, type_name, width, left, right);
1078 return sig;
1079 }
1080
1081 // generate cells for binary operations: $add, $sub, $mul, $div, $mod
1082 if (0) { case AST_ADD: type_name = "$add"; }
1083 if (0) { case AST_SUB: type_name = "$sub"; }
1084 if (0) { case AST_MUL: type_name = "$mul"; }
1085 if (0) { case AST_DIV: type_name = "$div"; }
1086 if (0) { case AST_MOD: type_name = "$mod"; }
1087 {
1088 if (width_hint < 0)
1089 detectSignWidth(width_hint, sign_hint);
1090 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1091 RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint);
1092 #if 0
1093 int width = std::max(left.size(), right.size());
1094 if (width > width_hint && width_hint > 0)
1095 width = width_hint;
1096 if (width < width_hint) {
1097 if (type == AST_ADD || type == AST_SUB || type == AST_DIV)
1098 width++;
1099 if (type == AST_SUB && (!children[0]->is_signed || !children[1]->is_signed))
1100 width = width_hint;
1101 if (type == AST_MUL)
1102 width = std::min(left.size() + right.size(), width_hint);
1103 }
1104 #else
1105 int width = std::max(std::max(left.size(), right.size()), width_hint);
1106 #endif
1107 is_signed = children[0]->is_signed && children[1]->is_signed;
1108 return binop2rtlil(this, type_name, width, left, right);
1109 }
1110
1111 // generate cells for binary operations: $logic_and, $logic_or
1112 if (0) { case AST_LOGIC_AND: type_name = "$logic_and"; }
1113 if (0) { case AST_LOGIC_OR: type_name = "$logic_or"; }
1114 {
1115 RTLIL::SigSpec left = children[0]->genRTLIL();
1116 RTLIL::SigSpec right = children[1]->genRTLIL();
1117 return binop2rtlil(this, type_name, std::max(width_hint, 1), left, right);
1118 }
1119
1120 // generate cells for unary operations: $logic_not
1121 case AST_LOGIC_NOT:
1122 {
1123 RTLIL::SigSpec arg = children[0]->genRTLIL();
1124 return uniop2rtlil(this, "$logic_not", std::max(width_hint, 1), arg);
1125 }
1126
1127 // generate multiplexer for ternary operator (aka ?:-operator)
1128 case AST_TERNARY:
1129 {
1130 if (width_hint < 0)
1131 detectSignWidth(width_hint, sign_hint);
1132
1133 RTLIL::SigSpec cond = children[0]->genRTLIL();
1134 RTLIL::SigSpec val1 = children[1]->genRTLIL(width_hint, sign_hint);
1135 RTLIL::SigSpec val2 = children[2]->genRTLIL(width_hint, sign_hint);
1136
1137 if (cond.size() > 1)
1138 cond = uniop2rtlil(this, "$reduce_bool", 1, cond, false);
1139
1140 int width = std::max(val1.size(), val2.size());
1141 is_signed = children[1]->is_signed && children[2]->is_signed;
1142 widthExtend(this, val1, width, is_signed, "$bu0");
1143 widthExtend(this, val2, width, is_signed, "$bu0");
1144
1145 RTLIL::SigSpec sig = mux2rtlil(this, cond, val1, val2);
1146
1147 if (sig.size() < width_hint)
1148 sig.extend_u0(width_hint, sign_hint);
1149 return sig;
1150 }
1151
1152 // generate $memrd cells for memory read ports
1153 case AST_MEMRD:
1154 {
1155 std::stringstream sstr;
1156 sstr << "$memrd$" << str << "$" << filename << ":" << linenum << "$" << (RTLIL::autoidx++);
1157
1158 RTLIL::Cell *cell = current_module->addCell(sstr.str(), "$memrd");
1159 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1160
1161 RTLIL::Wire *wire = current_module->addWire(cell->name + "_DATA", current_module->memories[str]->width);
1162 wire->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1163
1164 int addr_bits = 1;
1165 while ((1 << addr_bits) < current_module->memories[str]->size)
1166 addr_bits++;
1167
1168 cell->set("\\CLK", RTLIL::SigSpec(RTLIL::State::Sx, 1));
1169 cell->set("\\ADDR", children[0]->genWidthRTLIL(addr_bits));
1170 cell->set("\\DATA", RTLIL::SigSpec(wire));
1171
1172 cell->parameters["\\MEMID"] = RTLIL::Const(str);
1173 cell->parameters["\\ABITS"] = RTLIL::Const(addr_bits);
1174 cell->parameters["\\WIDTH"] = RTLIL::Const(wire->width);
1175
1176 cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(0);
1177 cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(0);
1178 cell->parameters["\\TRANSPARENT"] = RTLIL::Const(0);
1179
1180 return RTLIL::SigSpec(wire);
1181 }
1182
1183 // generate $memwr cells for memory write ports
1184 case AST_MEMWR:
1185 {
1186 std::stringstream sstr;
1187 sstr << "$memwr$" << str << "$" << filename << ":" << linenum << "$" << (RTLIL::autoidx++);
1188
1189 RTLIL::Cell *cell = current_module->addCell(sstr.str(), "$memwr");
1190 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1191
1192 int addr_bits = 1;
1193 while ((1 << addr_bits) < current_module->memories[str]->size)
1194 addr_bits++;
1195
1196 cell->set("\\CLK", RTLIL::SigSpec(RTLIL::State::Sx, 1));
1197 cell->set("\\ADDR", children[0]->genWidthRTLIL(addr_bits));
1198 cell->set("\\DATA", children[1]->genWidthRTLIL(current_module->memories[str]->width));
1199 cell->set("\\EN", children[2]->genRTLIL());
1200
1201 cell->parameters["\\MEMID"] = RTLIL::Const(str);
1202 cell->parameters["\\ABITS"] = RTLIL::Const(addr_bits);
1203 cell->parameters["\\WIDTH"] = RTLIL::Const(current_module->memories[str]->width);
1204
1205 cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(0);
1206 cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(0);
1207
1208 cell->parameters["\\PRIORITY"] = RTLIL::Const(RTLIL::autoidx-1);
1209 }
1210 break;
1211
1212 // generate $assert cells
1213 case AST_ASSERT:
1214 {
1215 log_assert(children.size() == 2);
1216
1217 RTLIL::SigSpec check = children[0]->genRTLIL();
1218 log_assert(check.size() == 1);
1219
1220 RTLIL::SigSpec en = children[1]->genRTLIL();
1221 log_assert(en.size() == 1);
1222
1223 std::stringstream sstr;
1224 sstr << "$assert$" << filename << ":" << linenum << "$" << (RTLIL::autoidx++);
1225
1226 RTLIL::Cell *cell = current_module->addCell(sstr.str(), "$assert");
1227 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1228
1229 for (auto &attr : attributes) {
1230 if (attr.second->type != AST_CONSTANT)
1231 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
1232 attr.first.c_str(), filename.c_str(), linenum);
1233 cell->attributes[attr.first] = attr.second->asAttrConst();
1234 }
1235
1236 cell->set("\\A", check);
1237 cell->set("\\EN", en);
1238 }
1239 break;
1240
1241 // add entries to current_module->connections for assignments (outside of always blocks)
1242 case AST_ASSIGN:
1243 {
1244 if (children[0]->type == AST_IDENTIFIER && children[0]->id2ast && children[0]->id2ast->type == AST_AUTOWIRE) {
1245 RTLIL::SigSpec right = children[1]->genRTLIL();
1246 RTLIL::SigSpec left = children[0]->genWidthRTLIL(right.size());
1247 current_module->connect(RTLIL::SigSig(left, right));
1248 } else {
1249 RTLIL::SigSpec left = children[0]->genRTLIL();
1250 RTLIL::SigSpec right = children[1]->genWidthRTLIL(left.size());
1251 current_module->connect(RTLIL::SigSig(left, right));
1252 }
1253 }
1254 break;
1255
1256 // create an RTLIL::Cell for an AST_CELL
1257 case AST_CELL:
1258 {
1259 int port_counter = 0, para_counter = 0;
1260
1261 if (current_module->count_id(str) != 0)
1262 log_error("Re-definition of cell `%s' at %s:%d!\n",
1263 str.c_str(), filename.c_str(), linenum);
1264
1265 RTLIL::Cell *cell = current_module->addCell(str, "");
1266 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1267
1268 for (auto it = children.begin(); it != children.end(); it++) {
1269 AstNode *child = *it;
1270 if (child->type == AST_CELLTYPE) {
1271 cell->type = child->str;
1272 if (flag_icells && cell->type.substr(0, 2) == "\\$")
1273 cell->type = cell->type.substr(1);
1274 continue;
1275 }
1276 if (child->type == AST_PARASET) {
1277 if (child->children[0]->type != AST_CONSTANT)
1278 log_error("Parameter `%s' with non-constant value at %s:%d!\n",
1279 child->str.c_str(), filename.c_str(), linenum);
1280 if (child->str.size() == 0) {
1281 char buf[100];
1282 snprintf(buf, 100, "$%d", ++para_counter);
1283 cell->parameters[buf] = child->children[0]->asParaConst();
1284 } else {
1285 cell->parameters[child->str] = child->children[0]->asParaConst();
1286 }
1287 continue;
1288 }
1289 if (child->type == AST_ARGUMENT) {
1290 RTLIL::SigSpec sig;
1291 if (child->children.size() > 0)
1292 sig = child->children[0]->genRTLIL();
1293 if (child->str.size() == 0) {
1294 char buf[100];
1295 snprintf(buf, 100, "$%d", ++port_counter);
1296 cell->set(buf, sig);
1297 } else {
1298 cell->set(child->str, sig);
1299 }
1300 continue;
1301 }
1302 log_abort();
1303 }
1304 for (auto &attr : attributes) {
1305 if (attr.second->type != AST_CONSTANT)
1306 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
1307 attr.first.c_str(), filename.c_str(), linenum);
1308 cell->attributes[attr.first] = attr.second->asAttrConst();
1309 }
1310 }
1311 break;
1312
1313 // use ProcessGenerator for always blocks
1314 case AST_ALWAYS: {
1315 AstNode *always = this->clone();
1316 ProcessGenerator generator(always);
1317 ignoreThisSignalsInInitial.append(generator.outputSignals);
1318 delete always;
1319 } break;
1320
1321 case AST_INITIAL: {
1322 AstNode *always = this->clone();
1323 ProcessGenerator generator(always, ignoreThisSignalsInInitial);
1324 delete always;
1325 } break;
1326
1327 // everything should have been handled above -> print error if not.
1328 default:
1329 for (auto f : log_files)
1330 current_ast->dumpAst(f, "verilog-ast> ");
1331 type_name = type2str(type);
1332 log_error("Don't know how to generate RTLIL code for %s node at %s:%d!\n",
1333 type_name.c_str(), filename.c_str(), linenum);
1334 }
1335
1336 return RTLIL::SigSpec();
1337 }
1338
1339 // this is a wrapper for AstNode::genRTLIL() when a specific signal width is requested and/or
1340 // signals must be substituted before beeing used as input values (used by ProcessGenerator)
1341 // note that this is using some global variables to communicate this special settings to AstNode::genRTLIL().
1342 RTLIL::SigSpec AstNode::genWidthRTLIL(int width, RTLIL::SigSpec *subst_from, RTLIL::SigSpec *subst_to)
1343 {
1344 RTLIL::SigSpec *backup_subst_from = genRTLIL_subst_from;
1345 RTLIL::SigSpec *backup_subst_to = genRTLIL_subst_to;
1346
1347 if (subst_from)
1348 genRTLIL_subst_from = subst_from;
1349 if (subst_to)
1350 genRTLIL_subst_to = subst_to;
1351
1352 bool sign_hint = true;
1353 int width_hint = width;
1354 detectSignWidthWorker(width_hint, sign_hint);
1355 RTLIL::SigSpec sig = genRTLIL(width_hint, sign_hint);
1356
1357 genRTLIL_subst_from = backup_subst_from;
1358 genRTLIL_subst_to = backup_subst_to;
1359
1360 if (width >= 0)
1361 sig.extend_u0(width, is_signed);
1362
1363 return sig;
1364 }
1365