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