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