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