Behavior should be identical now to rev. 0b4a64ac6adbd6 (next: testing before constfo...
[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 if (!id2ast->is_signed)
574 sign_hint = false;
575 break;
576
577 case AST_TO_SIGNED:
578 children.at(0)->detectSignWidthWorker(width_hint, sub_sign_hint);
579 break;
580
581 case AST_TO_UNSIGNED:
582 children.at(0)->detectSignWidthWorker(width_hint, sub_sign_hint);
583 sign_hint = false;
584 break;
585
586 case AST_CONCAT:
587 for (auto child : children) {
588 sub_width_hint = 0;
589 sub_sign_hint = true;
590 child->detectSignWidthWorker(width_hint, sign_hint);
591 this_width += sub_width_hint;
592 }
593 width_hint = std::max(width_hint, this_width);
594 sign_hint = false;
595 break;
596
597 case AST_REPLICATE:
598 if (children[0]->type != AST_CONSTANT)
599 log_error("Left operand of replicate expression is not constant at %s:%d!\n", filename.c_str(), linenum);
600 children[1]->detectSignWidthWorker(sub_width_hint, sub_sign_hint);
601 width_hint = std::max(width_hint, children[0]->bitsAsConst().as_int() * sub_width_hint);
602 sign_hint = false;
603 break;
604
605 case AST_NEG:
606 case AST_BIT_NOT:
607 case AST_POS:
608 children[0]->detectSignWidthWorker(width_hint, sign_hint);
609 break;
610
611 case AST_BIT_AND:
612 case AST_BIT_OR:
613 case AST_BIT_XOR:
614 case AST_BIT_XNOR:
615 for (auto child : children)
616 child->detectSignWidthWorker(width_hint, sign_hint);
617 break;
618
619 case AST_REDUCE_AND:
620 case AST_REDUCE_OR:
621 case AST_REDUCE_XOR:
622 case AST_REDUCE_XNOR:
623 case AST_REDUCE_BOOL:
624 width_hint = std::max(width_hint, 1);
625 sign_hint = false;
626 break;
627
628 case AST_SHIFT_LEFT:
629 case AST_SHIFT_RIGHT:
630 case AST_SHIFT_SLEFT:
631 case AST_SHIFT_SRIGHT:
632 case AST_POW:
633 children[0]->detectSignWidthWorker(width_hint, sign_hint);
634 break;
635
636 case AST_LT:
637 case AST_LE:
638 case AST_EQ:
639 case AST_NE:
640 case AST_GE:
641 case AST_GT:
642 width_hint = std::max(width_hint, 1);
643 sign_hint = false;
644 break;
645
646 case AST_ADD:
647 case AST_SUB:
648 case AST_MUL:
649 case AST_DIV:
650 case AST_MOD:
651 for (auto child : children)
652 child->detectSignWidthWorker(width_hint, sign_hint);
653 break;
654
655 case AST_LOGIC_AND:
656 case AST_LOGIC_OR:
657 case AST_LOGIC_NOT:
658 width_hint = std::max(width_hint, 1);
659 sign_hint = false;
660 break;
661
662 case AST_TERNARY:
663 children.at(1)->detectSignWidthWorker(width_hint, sign_hint);
664 children.at(2)->detectSignWidthWorker(width_hint, sign_hint);
665 break;
666
667 case AST_MEMRD:
668 if (!is_signed)
669 sign_hint = false;
670 width_hint = std::max(width_hint, current_module->memories.at(str)->width);
671 break;
672
673 // everything should have been handled above -> print error if not.
674 default:
675 for (auto f : log_files)
676 current_ast->dumpAst(f, "verilog-ast> ");
677 log_error("Don't know how to detect sign and width for %s node at %s:%d!\n",
678 type2str(type).c_str(), filename.c_str(), linenum);
679 }
680 }
681
682 // detect sign and width of an expression
683 void AstNode::detectSignWidth(int &width_hint, bool &sign_hint)
684 {
685 width_hint = -1, sign_hint = true;
686 detectSignWidthWorker(width_hint, sign_hint);
687 }
688
689 // create RTLIL from an AST node
690 // all generated cells, wires and processes are added to the module pointed to by 'current_module'
691 // when the AST node is an expression (AST_ADD, AST_BIT_XOR, etc.), the result signal is returned.
692 //
693 // note that this function is influenced by a number of global variables that might be set when
694 // called from genWidthRTLIL(). also note that this function recursively calls itself to transform
695 // larger expressions into a netlist of cells.
696 RTLIL::SigSpec AstNode::genRTLIL(int width_hint, bool sign_hint)
697 {
698 // in the following big switch() statement there are some uses of
699 // Clifford's Device (http://www.clifford.at/cfun/cliffdev/). In this
700 // cases this variable is used to hold the type of the cell that should
701 // be instanciated for this type of AST node.
702 std::string type_name;
703
704 current_filename = filename;
705 set_line_num(linenum);
706
707 switch (type)
708 {
709 // simply ignore this nodes.
710 // they are eighter leftovers from simplify() or are referenced by other nodes
711 // and are only accessed here thru this references
712 case AST_TASK:
713 case AST_FUNCTION:
714 case AST_AUTOWIRE:
715 case AST_PARAMETER:
716 case AST_LOCALPARAM:
717 case AST_DEFPARAM:
718 case AST_GENVAR:
719 case AST_GENFOR:
720 case AST_GENBLOCK:
721 case AST_GENIF:
722 break;
723
724 // create an RTLIL::Wire for an AST_WIRE node
725 case AST_WIRE: {
726 if (current_module->wires.count(str) != 0)
727 log_error("Re-definition of signal `%s' at %s:%d!\n",
728 str.c_str(), filename.c_str(), linenum);
729 if (!range_valid)
730 log_error("Signal `%s' with non-constant width at %s:%d!\n",
731 str.c_str(), filename.c_str(), linenum);
732
733 if (range_left < range_right && (range_left != -1 || range_right != 0)) {
734 int tmp = range_left;
735 range_left = range_right;
736 range_right = tmp;
737 }
738
739 RTLIL::Wire *wire = new RTLIL::Wire;
740 wire->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
741 wire->name = str;
742 wire->width = range_left - range_right + 1;
743 wire->start_offset = range_right;
744 wire->port_id = port_id;
745 wire->port_input = is_input;
746 wire->port_output = is_output;
747 current_module->wires[wire->name] = wire;
748
749 for (auto &attr : attributes) {
750 if (attr.second->type != AST_CONSTANT)
751 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
752 attr.first.c_str(), filename.c_str(), linenum);
753 wire->attributes[attr.first].str = attr.second->str;
754 wire->attributes[attr.first].bits = attr.second->bits;
755 }
756 }
757 break;
758
759 // create an RTLIL::Memory for an AST_MEMORY node
760 case AST_MEMORY: {
761 if (current_module->memories.count(str) != 0)
762 log_error("Re-definition of memory `%s' at %s:%d!\n",
763 str.c_str(), filename.c_str(), linenum);
764
765 assert(children.size() >= 2);
766 assert(children[0]->type == AST_RANGE);
767 assert(children[1]->type == AST_RANGE);
768
769 if (!children[0]->range_valid || !children[1]->range_valid)
770 log_error("Memory `%s' with non-constant width or size at %s:%d!\n",
771 str.c_str(), filename.c_str(), linenum);
772
773 RTLIL::Memory *memory = new RTLIL::Memory;
774 memory->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
775 memory->name = str;
776 memory->width = children[0]->range_left - children[0]->range_right + 1;
777 memory->start_offset = children[0]->range_right;
778 memory->size = children[1]->range_left - children[1]->range_right;
779 current_module->memories[memory->name] = memory;
780
781 if (memory->size < 0)
782 memory->size *= -1;
783 memory->size += std::min(children[1]->range_left, children[1]->range_right) + 1;
784
785 for (auto &attr : attributes) {
786 if (attr.second->type != AST_CONSTANT)
787 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
788 attr.first.c_str(), filename.c_str(), linenum);
789 memory->attributes[attr.first].str = attr.second->str;
790 memory->attributes[attr.first].bits = attr.second->bits;
791 }
792 }
793 break;
794
795 // simply return the corresponding RTLIL::SigSpec for an AST_CONSTANT node
796 case AST_CONSTANT:
797 {
798 if (width_hint < 0)
799 detectSignWidth(width_hint, sign_hint);
800
801 RTLIL::SigChunk chunk;
802 chunk.wire = NULL;
803 chunk.data.bits = bits;
804 chunk.width = bits.size();
805 chunk.offset = 0;
806
807 RTLIL::SigSpec sig;
808 sig.chunks.push_back(chunk);
809 sig.width = chunk.width;
810
811 is_signed = sign_hint;
812 return sig;
813 }
814
815 // simply return the corresponding RTLIL::SigSpec for an AST_IDENTIFIER node
816 // for identifiers with dynamic bit ranges (e.g. "foo[bar]" or "foo[bar+3:bar]") a
817 // shifter cell is created and the output signal of this cell is returned
818 case AST_IDENTIFIER:
819 {
820 RTLIL::Wire *wire = NULL;
821 RTLIL::SigChunk chunk;
822
823 if (id2ast && id2ast->type == AST_AUTOWIRE && current_module->wires.count(str) == 0) {
824 RTLIL::Wire *wire = new RTLIL::Wire;
825 wire->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
826 wire->name = str;
827 if (width_hint >= 0) {
828 wire->width = width_hint;
829 log("Warning: Identifier `%s' is implicitly declared with width %d at %s:%d.\n",
830 str.c_str(), width_hint, filename.c_str(), linenum);
831 } else {
832 log("Warning: Identifier `%s' is implicitly declared at %s:%d.\n",
833 str.c_str(), filename.c_str(), linenum);
834 }
835 wire->auto_width = true;
836 current_module->wires[str] = wire;
837 }
838 else if (id2ast->type == AST_PARAMETER || id2ast->type == AST_LOCALPARAM) {
839 chunk = RTLIL::Const(id2ast->children[0]->bits);
840 goto use_const_chunk;
841 }
842 else if (!id2ast || (id2ast->type != AST_WIRE && id2ast->type != AST_AUTOWIRE &&
843 id2ast->type != AST_MEMORY) || current_module->wires.count(str) == 0)
844 log_error("Identifier `%s' doesn't map to any signal at %s:%d!\n",
845 str.c_str(), filename.c_str(), linenum);
846
847 if (id2ast->type == AST_MEMORY)
848 log_error("Identifier `%s' does map to an unexpanded memory at %s:%d!\n",
849 str.c_str(), filename.c_str(), linenum);
850
851 wire = current_module->wires[str];
852 chunk.wire = wire;
853 chunk.width = wire->width;
854 chunk.offset = 0;
855
856 use_const_chunk:
857 if (children.size() != 0) {
858 assert(children[0]->type == AST_RANGE);
859 if (!children[0]->range_valid) {
860 AstNode *left_at_zero_ast = children[0]->children[0]->clone();
861 AstNode *right_at_zero_ast = children[0]->children.size() >= 2 ? children[0]->children[1]->clone() : left_at_zero_ast->clone();
862 while (left_at_zero_ast->simplify(true, true, false, 1, -1, false)) { }
863 while (right_at_zero_ast->simplify(true, true, false, 1, -1, false)) { }
864 if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
865 log_error("Unsupported expression on dynamic range select on signal `%s' at %s:%d!\n",
866 str.c_str(), filename.c_str(), linenum);
867 int width = left_at_zero_ast->integer - right_at_zero_ast->integer + 1;
868 AstNode *fake_ast = new AstNode(AST_NONE, clone(), children[0]->children.size() >= 2 ?
869 children[0]->children[1]->clone() : children[0]->children[0]->clone());
870 fake_ast->children[0]->delete_children();
871 RTLIL::SigSpec sig = binop2rtlil(fake_ast, "$shr", width,
872 fake_ast->children[0]->genRTLIL(), fake_ast->children[1]->genRTLIL());
873 delete left_at_zero_ast;
874 delete right_at_zero_ast;
875 delete fake_ast;
876 return sig;
877 } else {
878 chunk.offset = children[0]->range_right - id2ast->range_right;
879 chunk.width = children[0]->range_left - children[0]->range_right + 1;
880 if (children[0]->range_left > id2ast->range_left || id2ast->range_right > children[0]->range_right)
881 log_error("Range select out of bounds on signal `%s' at %s:%d!\n",
882 str.c_str(), filename.c_str(), linenum);
883 }
884 }
885
886 RTLIL::SigSpec sig;
887 sig.chunks.push_back(chunk);
888 sig.width = chunk.width;
889
890 if (genRTLIL_subst_from && genRTLIL_subst_to)
891 sig.replace(*genRTLIL_subst_from, *genRTLIL_subst_to);
892
893 is_signed = children.size() > 0 ? false : id2ast->is_signed && sign_hint;
894 return sig;
895 }
896
897 // just pass thru the signal. the parent will evaluated the is_signed property and inperpret the SigSpec accordingly
898 case AST_TO_SIGNED:
899 case AST_TO_UNSIGNED: {
900 RTLIL::SigSpec sig = children[0]->genRTLIL();
901 is_signed = sign_hint;
902 return sig;
903 }
904
905 // concatenation of signals can be done directly using RTLIL::SigSpec
906 case AST_CONCAT: {
907 RTLIL::SigSpec sig;
908 sig.width = 0;
909 for (auto it = children.begin(); it != children.end(); it++) {
910 RTLIL::SigSpec s = (*it)->genRTLIL();
911 for (size_t i = 0; i < s.chunks.size(); i++) {
912 sig.chunks.push_back(s.chunks[i]);
913 sig.width += s.chunks[i].width;
914 }
915 }
916 return sig;
917 }
918
919 // replication of signals can be done directly using RTLIL::SigSpec
920 case AST_REPLICATE: {
921 RTLIL::SigSpec left = children[0]->genRTLIL();
922 RTLIL::SigSpec right = children[1]->genRTLIL();
923 if (!left.is_fully_const())
924 log_error("Left operand of replicate expression is not constant at %s:%d!\n", filename.c_str(), linenum);
925 int count = left.as_int();
926 RTLIL::SigSpec sig;
927 for (int i = 0; i < count; i++)
928 sig.append(right);
929 is_signed = false;
930 return sig;
931 }
932
933 // generate cells for unary operations: $not, $pos, $neg
934 if (0) { case AST_BIT_NOT: type_name = "$not"; }
935 if (0) { case AST_POS: type_name = "$pos"; }
936 if (0) { case AST_NEG: type_name = "$neg"; }
937 {
938 RTLIL::SigSpec arg = children[0]->genRTLIL(width_hint, sign_hint);
939 is_signed = children[0]->is_signed;
940 int width = arg.width;
941 if (width_hint > 0) {
942 width = width_hint;
943 arg.extend(width, is_signed);
944 }
945 return uniop2rtlil(this, type_name, width, arg);
946 }
947
948 // generate cells for binary operations: $and, $or, $xor, $xnor
949 if (0) { case AST_BIT_AND: type_name = "$and"; }
950 if (0) { case AST_BIT_OR: type_name = "$or"; }
951 if (0) { case AST_BIT_XOR: type_name = "$xor"; }
952 if (0) { case AST_BIT_XNOR: type_name = "$xnor"; }
953 {
954 if (width_hint < 0)
955 detectSignWidth(width_hint, sign_hint);
956 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
957 RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint);
958 int width = std::max(left.width, right.width);
959 if (width_hint > 0)
960 width = width_hint;
961 is_signed = children[0]->is_signed && children[1]->is_signed;
962 return binop2rtlil(this, type_name, width, left, right);
963 }
964
965 // generate cells for unary operations: $reduce_and, $reduce_or, $reduce_xor, $reduce_xnor
966 if (0) { case AST_REDUCE_AND: type_name = "$reduce_and"; }
967 if (0) { case AST_REDUCE_OR: type_name = "$reduce_or"; }
968 if (0) { case AST_REDUCE_XOR: type_name = "$reduce_xor"; }
969 if (0) { case AST_REDUCE_XNOR: type_name = "$reduce_xnor"; }
970 {
971 RTLIL::SigSpec arg = children[0]->genRTLIL();
972 RTLIL::SigSpec sig = uniop2rtlil(this, type_name, 1, arg);
973 return sig;
974 }
975
976 // generate cells for unary operations: $reduce_bool
977 // (this is actually just an $reduce_or, but for clearity a different cell type is used)
978 if (0) { case AST_REDUCE_BOOL: type_name = "$reduce_bool"; }
979 {
980 RTLIL::SigSpec arg = children[0]->genRTLIL();
981 RTLIL::SigSpec sig = arg.width > 1 ? uniop2rtlil(this, type_name, 1, arg) : arg;
982 return sig;
983 }
984
985 // generate cells for binary operations: $shl, $shr, $sshl, $sshr
986 if (0) { case AST_SHIFT_LEFT: type_name = "$shl"; }
987 if (0) { case AST_SHIFT_RIGHT: type_name = "$shr"; }
988 if (0) { case AST_SHIFT_SLEFT: type_name = "$sshl"; }
989 if (0) { case AST_SHIFT_SRIGHT: type_name = "$sshr"; }
990 {
991 if (width_hint < 0)
992 detectSignWidth(width_hint, sign_hint);
993 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
994 RTLIL::SigSpec right = children[1]->genRTLIL();
995 int width = width_hint > 0 ? width_hint : left.width;
996 is_signed = children[0]->is_signed;
997 return binop2rtlil(this, type_name, width, left, right);
998 }
999
1000 // generate cells for binary operations: $lt, $le, $eq, $ne, $ge, $gt
1001 if (0) { case AST_LT: type_name = "$lt"; }
1002 if (0) { case AST_LE: type_name = "$le"; }
1003 if (0) { case AST_EQ: type_name = "$eq"; }
1004 if (0) { case AST_NE: type_name = "$ne"; }
1005 if (0) { case AST_GE: type_name = "$ge"; }
1006 if (0) { case AST_GT: type_name = "$gt"; }
1007 {
1008 width_hint = -1, sign_hint = true;
1009 children[0]->detectSignWidthWorker(width_hint, sign_hint);
1010 children[1]->detectSignWidthWorker(width_hint, sign_hint);
1011 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1012 RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint);
1013 RTLIL::SigSpec sig = binop2rtlil(this, type_name, 1, left, right);
1014 return sig;
1015 }
1016
1017 // generate cells for binary operations: $add, $sub, $mul, $div, $mod, $pow
1018 if (0) { case AST_ADD: type_name = "$add"; }
1019 if (0) { case AST_SUB: type_name = "$sub"; }
1020 if (0) { case AST_MUL: type_name = "$mul"; }
1021 if (0) { case AST_DIV: type_name = "$div"; }
1022 if (0) { case AST_MOD: type_name = "$mod"; }
1023 if (0) { case AST_POW: type_name = "$pow"; }
1024 {
1025 if (width_hint < 0)
1026 detectSignWidth(width_hint, sign_hint);
1027 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1028 RTLIL::SigSpec right = type == AST_POW ? children[1]->genRTLIL() : children[1]->genRTLIL(width_hint, sign_hint);
1029 int width = type == AST_POW ? left.width : std::max(left.width, right.width);
1030 if (width > width_hint && width_hint > 0)
1031 width = width_hint;
1032 if (width < width_hint) {
1033 if (type == AST_ADD || type == AST_SUB || type == AST_DIV)
1034 width++;
1035 if (type == AST_SUB && (!children[0]->is_signed || !children[1]->is_signed))
1036 width = width_hint;
1037 if (type == AST_MUL)
1038 width = std::min(left.width + right.width, width_hint);
1039 if (type == AST_POW)
1040 width = width_hint;
1041 }
1042 is_signed = children[0]->is_signed && children[1]->is_signed;
1043 if (!flag_noopt && type == AST_POW && left.is_fully_const() && left.as_int() == 2)
1044 return binop2rtlil(this, "$shl", width, RTLIL::SigSpec(1, left.width), right);
1045 return binop2rtlil(this, type_name, width, left, right);
1046 }
1047
1048 // generate cells for binary operations: $logic_and, $logic_or
1049 if (0) { case AST_LOGIC_AND: type_name = "$logic_and"; }
1050 if (0) { case AST_LOGIC_OR: type_name = "$logic_or"; }
1051 {
1052 RTLIL::SigSpec left = children[0]->genRTLIL();
1053 RTLIL::SigSpec right = children[1]->genRTLIL();
1054 return binop2rtlil(this, type_name, 1, left, right);
1055 }
1056
1057 // generate cells for unary operations: $logic_not
1058 case AST_LOGIC_NOT:
1059 {
1060 RTLIL::SigSpec arg = children[0]->genRTLIL();
1061 return uniop2rtlil(this, "$logic_not", 1, arg);
1062 }
1063
1064 // generate multiplexer for ternary operator (aka ?:-operator)
1065 case AST_TERNARY:
1066 {
1067 if (width_hint < 0)
1068 detectSignWidth(width_hint, sign_hint);
1069
1070 RTLIL::SigSpec cond = children[0]->genRTLIL();
1071 RTLIL::SigSpec val1 = children[1]->genRTLIL(width_hint, sign_hint);
1072 RTLIL::SigSpec val2 = children[2]->genRTLIL(width_hint, sign_hint);
1073
1074 if (cond.width > 1)
1075 cond = uniop2rtlil(this, "$reduce_bool", 1, cond, false);
1076
1077 int width = std::max(val1.width, val2.width);
1078 is_signed = children[1]->is_signed && children[2]->is_signed;
1079 val1.extend(width, is_signed);
1080 val2.extend(width, is_signed);
1081
1082 return mux2rtlil(this, cond, val1, val2);
1083 }
1084
1085 // generate $memrd cells for memory read ports
1086 case AST_MEMRD:
1087 {
1088 std::stringstream sstr;
1089 sstr << "$memrd$" << str << "$" << filename << ":" << linenum << "$" << (RTLIL::autoidx++);
1090
1091 RTLIL::Cell *cell = new RTLIL::Cell;
1092 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1093 cell->name = sstr.str();
1094 cell->type = "$memrd";
1095 current_module->cells[cell->name] = cell;
1096
1097 RTLIL::Wire *wire = new RTLIL::Wire;
1098 wire->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1099 wire->name = cell->name + "_DATA";
1100 wire->width = current_module->memories[str]->width;
1101 current_module->wires[wire->name] = wire;
1102
1103 int addr_bits = 1;
1104 while ((1 << addr_bits) < current_module->memories[str]->size)
1105 addr_bits++;
1106
1107 cell->connections["\\CLK"] = RTLIL::SigSpec(RTLIL::State::Sx, 1);
1108 cell->connections["\\ADDR"] = children[0]->genRTLIL();
1109 cell->connections["\\DATA"] = RTLIL::SigSpec(wire);
1110
1111 cell->parameters["\\MEMID"] = RTLIL::Const(str);
1112 cell->parameters["\\ABITS"] = RTLIL::Const(addr_bits);
1113 cell->parameters["\\WIDTH"] = RTLIL::Const(wire->width);
1114
1115 cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(0);
1116 cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(0);
1117
1118 return RTLIL::SigSpec(wire);
1119 }
1120
1121 // generate $memwr cells for memory write ports
1122 case AST_MEMWR:
1123 {
1124 std::stringstream sstr;
1125 sstr << "$memwr$" << str << "$" << filename << ":" << linenum << "$" << (RTLIL::autoidx++);
1126
1127 RTLIL::Cell *cell = new RTLIL::Cell;
1128 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1129 cell->name = sstr.str();
1130 cell->type = "$memwr";
1131 current_module->cells[cell->name] = cell;
1132
1133 int addr_bits = 1;
1134 while ((1 << addr_bits) < current_module->memories[str]->size)
1135 addr_bits++;
1136
1137 cell->connections["\\CLK"] = RTLIL::SigSpec(RTLIL::State::Sx, 1);
1138 cell->connections["\\ADDR"] = children[0]->genRTLIL();
1139 cell->connections["\\DATA"] = children[1]->genRTLIL();
1140 cell->connections["\\EN"] = children[2]->genRTLIL();
1141
1142 cell->parameters["\\MEMID"] = RTLIL::Const(str);
1143 cell->parameters["\\ABITS"] = RTLIL::Const(addr_bits);
1144 cell->parameters["\\WIDTH"] = RTLIL::Const(current_module->memories[str]->width);
1145
1146 cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(0);
1147 cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(0);
1148 }
1149 break;
1150
1151 // add entries to current_module->connections for assignments (outside of always blocks)
1152 case AST_ASSIGN:
1153 {
1154 if (children[0]->type == AST_IDENTIFIER && children[0]->id2ast && children[0]->id2ast->type == AST_AUTOWIRE) {
1155 RTLIL::SigSpec right = children[1]->genRTLIL();
1156 RTLIL::SigSpec left = children[0]->genWidthRTLIL(right.width);
1157 current_module->connections.push_back(RTLIL::SigSig(left, right));
1158 } else {
1159 RTLIL::SigSpec left = children[0]->genRTLIL();
1160 RTLIL::SigSpec right = children[1]->genWidthRTLIL(left.width);
1161 current_module->connections.push_back(RTLIL::SigSig(left, right));
1162 }
1163 }
1164 break;
1165
1166 // create an RTLIL::Cell for an AST_CELL
1167 case AST_CELL:
1168 {
1169 int port_counter = 0, para_counter = 0;
1170 RTLIL::Cell *cell = new RTLIL::Cell;
1171 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1172 cell->name = str;
1173 for (auto it = children.begin(); it != children.end(); it++) {
1174 AstNode *child = *it;
1175 if (child->type == AST_CELLTYPE) {
1176 cell->type = child->str;
1177 continue;
1178 }
1179 if (child->type == AST_PARASET) {
1180 if (child->children[0]->type != AST_CONSTANT)
1181 log_error("Parameter `%s' with non-constant value at %s:%d!\n",
1182 child->str.c_str(), filename.c_str(), linenum);
1183 if (child->str.size() == 0) {
1184 char buf[100];
1185 snprintf(buf, 100, "$%d", ++para_counter);
1186 cell->parameters[buf].str = child->children[0]->str;
1187 cell->parameters[buf].bits = child->children[0]->bits;
1188 } else {
1189 cell->parameters[child->str].str = child->children[0]->str;
1190 cell->parameters[child->str].bits = child->children[0]->bits;
1191 }
1192 continue;
1193 }
1194 if (child->type == AST_ARGUMENT) {
1195 RTLIL::SigSpec sig;
1196 if (child->children.size() > 0)
1197 sig = child->children[0]->genRTLIL();
1198 if (child->str.size() == 0) {
1199 char buf[100];
1200 snprintf(buf, 100, "$%d", ++port_counter);
1201 cell->connections[buf] = sig;
1202 } else {
1203 cell->connections[child->str] = sig;
1204 }
1205 continue;
1206 }
1207 assert(0);
1208 }
1209 for (auto &attr : attributes) {
1210 if (attr.second->type != AST_CONSTANT)
1211 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
1212 attr.first.c_str(), filename.c_str(), linenum);
1213 cell->attributes[attr.first].str = attr.second->str;
1214 cell->attributes[attr.first].bits = attr.second->bits;
1215 }
1216 if (current_module->cells.count(cell->name) != 0)
1217 log_error("Re-definition of cell `%s' at %s:%d!\n",
1218 str.c_str(), filename.c_str(), linenum);
1219 current_module->cells[str] = cell;
1220 }
1221 break;
1222
1223 // use ProcessGenerator for always blocks
1224 case AST_ALWAYS: {
1225 AstNode *always = this->clone();
1226 ProcessGenerator generator(always);
1227 ignoreThisSignalsInInitial.append(generator.outputSignals);
1228 delete always;
1229 } break;
1230
1231 case AST_INITIAL: {
1232 AstNode *always = this->clone();
1233 ProcessGenerator generator(always, ignoreThisSignalsInInitial);
1234 delete always;
1235 } break;
1236
1237 // everything should have been handled above -> print error if not.
1238 default:
1239 for (auto f : log_files)
1240 current_ast->dumpAst(f, "verilog-ast> ");
1241 type_name = type2str(type);
1242 log_error("Don't know how to generate RTLIL code for %s node at %s:%d!\n",
1243 type_name.c_str(), filename.c_str(), linenum);
1244 }
1245
1246 return RTLIL::SigSpec();
1247 }
1248
1249 // this is a wrapper for AstNode::genRTLIL() when a specific signal width is requested and/or
1250 // signals must be substituted before beeing used as input values (used by ProcessGenerator)
1251 // note that this is using some global variables to communicate this special settings to AstNode::genRTLIL().
1252 RTLIL::SigSpec AstNode::genWidthRTLIL(int width, RTLIL::SigSpec *subst_from, RTLIL::SigSpec *subst_to)
1253 {
1254 RTLIL::SigSpec *backup_subst_from = genRTLIL_subst_from;
1255 RTLIL::SigSpec *backup_subst_to = genRTLIL_subst_to;
1256
1257 if (subst_from)
1258 genRTLIL_subst_from = subst_from;
1259 if (subst_to)
1260 genRTLIL_subst_to = subst_to;
1261
1262 bool sign_hint = true;
1263 int width_hint = width;
1264 detectSignWidthWorker(width_hint, sign_hint);
1265 RTLIL::SigSpec sig = genRTLIL(width_hint, sign_hint);
1266
1267 genRTLIL_subst_from = backup_subst_from;
1268 genRTLIL_subst_to = backup_subst_to;
1269
1270 if (width >= 0)
1271 sig.extend(width, is_signed);
1272
1273 return sig;
1274 }
1275