Merge pull request #1922 from whitequark/write_cxxrtl-disconnected-outputs
[yosys.git] / frontends / ast / simplify.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 "frontends/verilog/verilog_frontend.h"
32 #include "ast.h"
33
34 #include <sstream>
35 #include <stdarg.h>
36 #include <stdlib.h>
37 #include <math.h>
38
39 YOSYS_NAMESPACE_BEGIN
40
41 using namespace AST;
42 using namespace AST_INTERNAL;
43
44 // Process a format string and arguments for $display, $write, $sprintf, etc
45
46 std::string AstNode::process_format_str(const std::string &sformat, int next_arg, int stage, int width_hint, bool sign_hint) {
47 // Other arguments are placeholders. Process the string as we go through it
48 std::string sout;
49 for (size_t i = 0; i < sformat.length(); i++)
50 {
51 // format specifier
52 if (sformat[i] == '%')
53 {
54 // If there's no next character, that's a problem
55 if (i+1 >= sformat.length())
56 log_file_error(filename, location.first_line, "System task `%s' called with `%%' at end of string.\n", str.c_str());
57
58 char cformat = sformat[++i];
59
60 // %% is special, does not need a matching argument
61 if (cformat == '%')
62 {
63 sout += '%';
64 continue;
65 }
66
67 // Simplify the argument
68 AstNode *node_arg = nullptr;
69
70 // Everything from here on depends on the format specifier
71 switch (cformat)
72 {
73 case 's':
74 case 'S':
75 case 'd':
76 case 'D':
77 case 'x':
78 case 'X':
79 if (next_arg >= GetSize(children))
80 log_file_error(filename, location.first_line, "Missing argument for %%%c format specifier in system task `%s'.\n",
81 cformat, str.c_str());
82
83 node_arg = children[next_arg++];
84 while (node_arg->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
85 if (node_arg->type != AST_CONSTANT)
86 log_file_error(filename, location.first_line, "Failed to evaluate system task `%s' with non-constant argument.\n", str.c_str());
87 break;
88
89 case 'm':
90 case 'M':
91 break;
92
93 default:
94 log_file_error(filename, location.first_line, "System task `%s' called with invalid/unsupported format specifier.\n", str.c_str());
95 break;
96 }
97
98 switch (cformat)
99 {
100 case 's':
101 case 'S':
102 sout += node_arg->bitsAsConst().decode_string();
103 break;
104
105 case 'd':
106 case 'D':
107 {
108 char tmp[128];
109 snprintf(tmp, sizeof(tmp), "%d", node_arg->bitsAsConst().as_int());
110 sout += tmp;
111 }
112 break;
113
114 case 'x':
115 case 'X':
116 {
117 char tmp[128];
118 snprintf(tmp, sizeof(tmp), "%x", node_arg->bitsAsConst().as_int());
119 sout += tmp;
120 }
121 break;
122
123 case 'm':
124 case 'M':
125 sout += log_id(current_module->name);
126 break;
127
128 default:
129 log_abort();
130 }
131 }
132
133 // not a format specifier
134 else
135 sout += sformat[i];
136 }
137 return sout;
138 }
139
140
141 // convert the AST into a simpler AST that has all parameters substituted by their
142 // values, unrolled for-loops, expanded generate blocks, etc. when this function
143 // is done with an AST it can be converted into RTLIL using genRTLIL().
144 //
145 // this function also does all name resolving and sets the id2ast member of all
146 // nodes that link to a different node using names and lexical scoping.
147 bool AstNode::simplify(bool const_fold, bool at_zero, bool in_lvalue, int stage, int width_hint, bool sign_hint, bool in_param)
148 {
149 static int recursion_counter = 0;
150 static bool deep_recursion_warning = false;
151
152 if (recursion_counter++ == 1000 && deep_recursion_warning) {
153 log_warning("Deep recursion in AST simplifier.\nDoes this design contain insanely long expressions?\n");
154 deep_recursion_warning = false;
155 }
156
157 AstNode *newNode = NULL;
158 bool did_something = false;
159
160 #if 0
161 log("-------------\n");
162 log("AST simplify[%d] depth %d at %s:%d on %s %p:\n", stage, recursion_counter, filename.c_str(), location.first_line, type2str(type).c_str(), this);
163 log("const_fold=%d, at_zero=%d, in_lvalue=%d, stage=%d, width_hint=%d, sign_hint=%d, in_param=%d\n",
164 int(const_fold), int(at_zero), int(in_lvalue), int(stage), int(width_hint), int(sign_hint), int(in_param));
165 // dumpAst(NULL, "> ");
166 #endif
167
168 if (stage == 0)
169 {
170 log_assert(type == AST_MODULE || type == AST_INTERFACE);
171
172 deep_recursion_warning = true;
173 while (simplify(const_fold, at_zero, in_lvalue, 1, width_hint, sign_hint, in_param)) { }
174
175 if (!flag_nomem2reg && !get_bool_attribute(ID::nomem2reg))
176 {
177 dict<AstNode*, pool<std::string>> mem2reg_places;
178 dict<AstNode*, uint32_t> mem2reg_candidates, dummy_proc_flags;
179 uint32_t flags = flag_mem2reg ? AstNode::MEM2REG_FL_ALL : 0;
180 mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, dummy_proc_flags, flags);
181
182 pool<AstNode*> mem2reg_set;
183 for (auto &it : mem2reg_candidates)
184 {
185 AstNode *mem = it.first;
186 uint32_t memflags = it.second;
187 bool this_nomeminit = flag_nomeminit;
188 log_assert((memflags & ~0x00ffff00) == 0);
189
190 if (mem->get_bool_attribute(ID::nomem2reg))
191 continue;
192
193 if (mem->get_bool_attribute(ID::nomeminit) || get_bool_attribute(ID::nomeminit))
194 this_nomeminit = true;
195
196 if (memflags & AstNode::MEM2REG_FL_FORCED)
197 goto silent_activate;
198
199 if (memflags & AstNode::MEM2REG_FL_EQ2)
200 goto verbose_activate;
201
202 if (memflags & AstNode::MEM2REG_FL_SET_ASYNC)
203 goto verbose_activate;
204
205 if ((memflags & AstNode::MEM2REG_FL_SET_INIT) && (memflags & AstNode::MEM2REG_FL_SET_ELSE) && this_nomeminit)
206 goto verbose_activate;
207
208 if (memflags & AstNode::MEM2REG_FL_CMPLX_LHS)
209 goto verbose_activate;
210
211 if ((memflags & AstNode::MEM2REG_FL_CONST_LHS) && !(memflags & AstNode::MEM2REG_FL_VAR_LHS))
212 goto verbose_activate;
213
214 // log("Note: Not replacing memory %s with list of registers (flags=0x%08lx).\n", mem->str.c_str(), long(memflags));
215 continue;
216
217 verbose_activate:
218 if (mem2reg_set.count(mem) == 0) {
219 std::string message = stringf("Replacing memory %s with list of registers.", mem->str.c_str());
220 bool first_element = true;
221 for (auto &place : mem2reg_places[it.first]) {
222 message += stringf("%s%s", first_element ? " See " : ", ", place.c_str());
223 first_element = false;
224 }
225 log_warning("%s\n", message.c_str());
226 }
227
228 silent_activate:
229 // log("Note: Replacing memory %s with list of registers (flags=0x%08lx).\n", mem->str.c_str(), long(memflags));
230 mem2reg_set.insert(mem);
231 }
232
233 for (auto node : mem2reg_set)
234 {
235 int mem_width, mem_size, addr_bits;
236 node->meminfo(mem_width, mem_size, addr_bits);
237
238 int data_range_left = node->children[0]->range_left;
239 int data_range_right = node->children[0]->range_right;
240
241 if (node->children[0]->range_swapped)
242 std::swap(data_range_left, data_range_right);
243
244 for (int i = 0; i < mem_size; i++) {
245 AstNode *reg = new AstNode(AST_WIRE, new AstNode(AST_RANGE,
246 mkconst_int(data_range_left, true), mkconst_int(data_range_right, true)));
247 reg->str = stringf("%s[%d]", node->str.c_str(), i);
248 reg->is_reg = true;
249 reg->is_signed = node->is_signed;
250 for (auto &it : node->attributes)
251 if (it.first != ID::mem2reg)
252 reg->attributes.emplace(it.first, it.second->clone());
253 reg->filename = node->filename;
254 reg->location = node->location;
255 children.push_back(reg);
256 while (reg->simplify(true, false, false, 1, -1, false, false)) { }
257 }
258 }
259
260 AstNode *async_block = NULL;
261 while (mem2reg_as_needed_pass2(mem2reg_set, this, NULL, async_block)) { }
262
263 vector<AstNode*> delnodes;
264 mem2reg_remove(mem2reg_set, delnodes);
265
266 for (auto node : delnodes)
267 delete node;
268 }
269
270 while (simplify(const_fold, at_zero, in_lvalue, 2, width_hint, sign_hint, in_param)) { }
271 recursion_counter--;
272 return false;
273 }
274
275 current_filename = filename;
276
277 // we do not look inside a task or function
278 // (but as soon as a task or function is instantiated we process the generated AST as usual)
279 if (type == AST_FUNCTION || type == AST_TASK) {
280 recursion_counter--;
281 return false;
282 }
283
284 // deactivate all calls to non-synthesis system tasks
285 // note that $display, $finish, and $stop are used for synthesis-time DRC so they're not in this list
286 if ((type == AST_FCALL || type == AST_TCALL) && (str == "$strobe" || str == "$monitor" || str == "$time" ||
287 str == "$dumpfile" || str == "$dumpvars" || str == "$dumpon" || str == "$dumpoff" || str == "$dumpall")) {
288 log_file_warning(filename, location.first_line, "Ignoring call to system %s %s.\n", type == AST_FCALL ? "function" : "task", str.c_str());
289 delete_children();
290 str = std::string();
291 }
292
293 if ((type == AST_TCALL) && (str == "$display" || str == "$write") && (!current_always || current_always->type != AST_INITIAL)) {
294 log_file_warning(filename, location.first_line, "System task `%s' outside initial block is unsupported.\n", str.c_str());
295 delete_children();
296 str = std::string();
297 }
298
299 // print messages if this a call to $display() or $write()
300 // This code implements only a small subset of Verilog-2005 $display() format specifiers,
301 // but should be good enough for most uses
302 if ((type == AST_TCALL) && ((str == "$display") || (str == "$write")))
303 {
304 int nargs = GetSize(children);
305 if (nargs < 1)
306 log_file_error(filename, location.first_line, "System task `%s' got %d arguments, expected >= 1.\n",
307 str.c_str(), int(children.size()));
308
309 // First argument is the format string
310 AstNode *node_string = children[0];
311 while (node_string->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
312 if (node_string->type != AST_CONSTANT)
313 log_file_error(filename, location.first_line, "Failed to evaluate system task `%s' with non-constant 1st argument.\n", str.c_str());
314 std::string sformat = node_string->bitsAsConst().decode_string();
315 std::string sout = process_format_str(sformat, 1, stage, width_hint, sign_hint);
316 // Finally, print the message (only include a \n for $display, not for $write)
317 log("%s", sout.c_str());
318 if (str == "$display")
319 log("\n");
320 delete_children();
321 str = std::string();
322 }
323
324 // activate const folding if this is anything that must be evaluated statically (ranges, parameters, attributes, etc.)
325 if (type == AST_WIRE || type == AST_PARAMETER || type == AST_LOCALPARAM || type == AST_ENUM_ITEM || type == AST_DEFPARAM || type == AST_PARASET || type == AST_RANGE || type == AST_PREFIX || type == AST_TYPEDEF)
326 const_fold = true;
327 if (type == AST_IDENTIFIER && current_scope.count(str) > 0 && (current_scope[str]->type == AST_PARAMETER || current_scope[str]->type == AST_LOCALPARAM || current_scope[str]->type == AST_ENUM_ITEM))
328 const_fold = true;
329
330 // in certain cases a function must be evaluated constant. this is what in_param controls.
331 if (type == AST_PARAMETER || type == AST_LOCALPARAM || type == AST_DEFPARAM || type == AST_PARASET || type == AST_PREFIX)
332 in_param = true;
333
334 std::map<std::string, AstNode*> backup_scope;
335
336 // create name resolution entries for all objects with names
337 // also merge multiple declarations for the same wire (e.g. "output foobar; reg foobar;")
338 if (type == AST_MODULE) {
339 current_scope.clear();
340 std::map<std::string, AstNode*> this_wire_scope;
341 for (size_t i = 0; i < children.size(); i++) {
342 AstNode *node = children[i];
343
344 if (node->type == AST_WIRE) {
345 if (node->children.size() == 1 && node->children[0]->type == AST_RANGE) {
346 for (auto c : node->children[0]->children) {
347 if (!c->is_simple_const_expr()) {
348 if (attributes.count(ID::dynports))
349 delete attributes.at(ID::dynports);
350 attributes[ID::dynports] = AstNode::mkconst_int(1, true);
351 }
352 }
353 }
354 if (this_wire_scope.count(node->str) > 0) {
355 AstNode *first_node = this_wire_scope[node->str];
356 if (first_node->is_input && node->is_reg)
357 goto wires_are_incompatible;
358 if (!node->is_input && !node->is_output && node->is_reg && node->children.size() == 0)
359 goto wires_are_compatible;
360 if (first_node->children.size() == 0 && node->children.size() == 1 && node->children[0]->type == AST_RANGE) {
361 AstNode *r = node->children[0];
362 if (r->range_valid && r->range_left == 0 && r->range_right == 0) {
363 delete r;
364 node->children.pop_back();
365 }
366 }
367 if (first_node->children.size() != node->children.size())
368 goto wires_are_incompatible;
369 for (size_t j = 0; j < node->children.size(); j++) {
370 AstNode *n1 = first_node->children[j], *n2 = node->children[j];
371 if (n1->type == AST_RANGE && n2->type == AST_RANGE && n1->range_valid && n2->range_valid) {
372 if (n1->range_left != n2->range_left)
373 goto wires_are_incompatible;
374 if (n1->range_right != n2->range_right)
375 goto wires_are_incompatible;
376 } else if (*n1 != *n2)
377 goto wires_are_incompatible;
378 }
379 if (first_node->range_left != node->range_left)
380 goto wires_are_incompatible;
381 if (first_node->range_right != node->range_right)
382 goto wires_are_incompatible;
383 if (first_node->port_id == 0 && (node->is_input || node->is_output))
384 goto wires_are_incompatible;
385 wires_are_compatible:
386 if (node->is_input)
387 first_node->is_input = true;
388 if (node->is_output)
389 first_node->is_output = true;
390 if (node->is_reg)
391 first_node->is_reg = true;
392 if (node->is_logic)
393 first_node->is_logic = true;
394 if (node->is_signed)
395 first_node->is_signed = true;
396 for (auto &it : node->attributes) {
397 if (first_node->attributes.count(it.first) > 0)
398 delete first_node->attributes[it.first];
399 first_node->attributes[it.first] = it.second->clone();
400 }
401 children.erase(children.begin()+(i--));
402 did_something = true;
403 delete node;
404 continue;
405 wires_are_incompatible:
406 if (stage > 1)
407 log_file_error(filename, location.first_line, "Incompatible re-declaration of wire %s.\n", node->str.c_str());
408 continue;
409 }
410 this_wire_scope[node->str] = node;
411 }
412 // these nodes appear at the top level in a module and can define names
413 if (node->type == AST_PARAMETER || node->type == AST_LOCALPARAM || node->type == AST_WIRE || node->type == AST_AUTOWIRE || node->type == AST_GENVAR ||
414 node->type == AST_MEMORY || node->type == AST_FUNCTION || node->type == AST_TASK || node->type == AST_DPI_FUNCTION || node->type == AST_CELL ||
415 node->type == AST_TYPEDEF) {
416 backup_scope[node->str] = current_scope[node->str];
417 current_scope[node->str] = node;
418 }
419 if (node->type == AST_ENUM) {
420 current_scope[node->str] = node;
421 for (auto enode : node->children) {
422 log_assert(enode->type==AST_ENUM_ITEM);
423 if (current_scope.count(enode->str) == 0)
424 current_scope[enode->str] = enode;
425 else
426 log_file_error(filename, location.first_line, "enum item %s already exists\n", enode->str.c_str());
427 }
428 }
429 }
430 for (size_t i = 0; i < children.size(); i++) {
431 AstNode *node = children[i];
432 if (node->type == AST_PARAMETER || node->type == AST_LOCALPARAM || node->type == AST_WIRE || node->type == AST_AUTOWIRE || node->type == AST_MEMORY || node->type == AST_TYPEDEF)
433 while (node->simplify(true, false, false, 1, -1, false, node->type == AST_PARAMETER || node->type == AST_LOCALPARAM))
434 did_something = true;
435 if (node->type == AST_ENUM) {
436 for (auto enode YS_ATTRIBUTE(unused) : node->children){
437 log_assert(enode->type==AST_ENUM_ITEM);
438 while (node->simplify(true, false, false, 1, -1, false, in_param))
439 did_something = true;
440 }
441 }
442 }
443 }
444
445 // create name resolution entries for all objects with names
446 if (type == AST_PACKAGE) {
447 //add names to package scope
448 for (size_t i = 0; i < children.size(); i++) {
449 AstNode *node = children[i];
450 // these nodes appear at the top level in a package and can define names
451 if (node->type == AST_PARAMETER || node->type == AST_LOCALPARAM || node->type == AST_TYPEDEF) {
452 current_scope[node->str] = node;
453 }
454 if (node->type == AST_ENUM) {
455 current_scope[node->str] = node;
456 for (auto enode : node->children) {
457 log_assert(enode->type==AST_ENUM_ITEM);
458 if (current_scope.count(enode->str) == 0)
459 current_scope[enode->str] = enode;
460 else
461 log_file_error(filename, location.first_line, "enum item %s already exists in package\n", enode->str.c_str());
462 }
463 }
464 }
465 }
466
467
468 auto backup_current_block = current_block;
469 auto backup_current_block_child = current_block_child;
470 auto backup_current_top_block = current_top_block;
471 auto backup_current_always = current_always;
472 auto backup_current_always_clocked = current_always_clocked;
473
474 if (type == AST_ALWAYS || type == AST_INITIAL)
475 {
476 if (current_always != nullptr)
477 log_file_error(filename, location.first_line, "Invalid nesting of always blocks and/or initializations.\n");
478
479 current_always = this;
480 current_always_clocked = false;
481
482 if (type == AST_ALWAYS)
483 for (auto child : children) {
484 if (child->type == AST_POSEDGE || child->type == AST_NEGEDGE)
485 current_always_clocked = true;
486 if (child->type == AST_EDGE && GetSize(child->children) == 1 &&
487 child->children[0]->type == AST_IDENTIFIER && child->children[0]->str == "\\$global_clock")
488 current_always_clocked = true;
489 }
490 }
491
492 int backup_width_hint = width_hint;
493 bool backup_sign_hint = sign_hint;
494
495 bool detect_width_simple = false;
496 bool child_0_is_self_determined = false;
497 bool child_1_is_self_determined = false;
498 bool child_2_is_self_determined = false;
499 bool children_are_self_determined = false;
500 bool reset_width_after_children = false;
501
502 switch (type)
503 {
504 case AST_ASSIGN_EQ:
505 case AST_ASSIGN_LE:
506 case AST_ASSIGN:
507 while (!children[0]->basic_prep && children[0]->simplify(false, false, true, stage, -1, false, in_param) == true)
508 did_something = true;
509 while (!children[1]->basic_prep && children[1]->simplify(false, false, false, stage, -1, false, in_param) == true)
510 did_something = true;
511 children[0]->detectSignWidth(backup_width_hint, backup_sign_hint);
512 children[1]->detectSignWidth(width_hint, sign_hint);
513 width_hint = max(width_hint, backup_width_hint);
514 child_0_is_self_determined = true;
515 // test only once, before optimizations and memory mappings but after assignment LHS was mapped to an identifier
516 if (children[0]->id2ast && !children[0]->was_checked) {
517 if ((type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ) && children[0]->id2ast->is_logic)
518 children[0]->id2ast->is_reg = true; // if logic type is used in a block asignment
519 if ((type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ) && !children[0]->id2ast->is_reg)
520 log_warning("wire '%s' is assigned in a block at %s:%d.%d-%d.%d.\n", children[0]->str.c_str(), filename.c_str(), location.first_line, location.first_column, location.last_line, location.last_column);
521 if (type == AST_ASSIGN && children[0]->id2ast->is_reg) {
522 bool is_rand_reg = false;
523 if (children[1]->type == AST_FCALL) {
524 if (children[1]->str == "\\$anyconst")
525 is_rand_reg = true;
526 if (children[1]->str == "\\$anyseq")
527 is_rand_reg = true;
528 if (children[1]->str == "\\$allconst")
529 is_rand_reg = true;
530 if (children[1]->str == "\\$allseq")
531 is_rand_reg = true;
532 }
533 if (!is_rand_reg)
534 log_warning("reg '%s' is assigned in a continuous assignment at %s:%d.%d-%d.%d.\n", children[0]->str.c_str(), filename.c_str(), location.first_line, location.first_column, location.last_line, location.last_column);
535 }
536 children[0]->was_checked = true;
537 }
538 break;
539
540 case AST_ENUM:
541 //log("\nENUM %s: %d child %d\n", str.c_str(), basic_prep, children[0]->basic_prep);
542 if (!basic_prep) {
543 for (auto item_node : children) {
544 while (!item_node->basic_prep && item_node->simplify(false, false, false, stage, -1, false, in_param))
545 did_something = true;
546 }
547 // allocate values (called more than once)
548 allocateDefaultEnumValues();
549 }
550 break;
551
552 case AST_PARAMETER:
553 case AST_LOCALPARAM:
554 while (!children[0]->basic_prep && children[0]->simplify(false, false, false, stage, -1, false, true) == true)
555 did_something = true;
556 children[0]->detectSignWidth(width_hint, sign_hint);
557 if (children.size() > 1 && children[1]->type == AST_RANGE) {
558 while (!children[1]->basic_prep && children[1]->simplify(false, false, false, stage, -1, false, true) == true)
559 did_something = true;
560 if (!children[1]->range_valid)
561 log_file_error(filename, location.first_line, "Non-constant width range on parameter decl.\n");
562 width_hint = max(width_hint, children[1]->range_left - children[1]->range_right + 1);
563 }
564 break;
565 case AST_ENUM_ITEM:
566 while (!children[0]->basic_prep && children[0]->simplify(false, false, false, stage, -1, false, in_param))
567 did_something = true;
568 children[0]->detectSignWidth(width_hint, sign_hint);
569 if (children.size() > 1 && children[1]->type == AST_RANGE) {
570 while (!children[1]->basic_prep && children[1]->simplify(false, false, false, stage, -1, false, in_param))
571 did_something = true;
572 if (!children[1]->range_valid)
573 log_file_error(filename, location.first_line, "Non-constant width range on enum item decl.\n");
574 width_hint = max(width_hint, children[1]->range_left - children[1]->range_right + 1);
575 }
576 break;
577
578 case AST_TO_BITS:
579 case AST_TO_SIGNED:
580 case AST_TO_UNSIGNED:
581 case AST_CONCAT:
582 case AST_REPLICATE:
583 case AST_REDUCE_AND:
584 case AST_REDUCE_OR:
585 case AST_REDUCE_XOR:
586 case AST_REDUCE_XNOR:
587 case AST_REDUCE_BOOL:
588 detect_width_simple = true;
589 children_are_self_determined = true;
590 break;
591
592 case AST_NEG:
593 case AST_BIT_NOT:
594 case AST_POS:
595 case AST_BIT_AND:
596 case AST_BIT_OR:
597 case AST_BIT_XOR:
598 case AST_BIT_XNOR:
599 case AST_ADD:
600 case AST_SUB:
601 case AST_MUL:
602 case AST_DIV:
603 case AST_MOD:
604 detect_width_simple = true;
605 break;
606
607 case AST_SHIFT_LEFT:
608 case AST_SHIFT_RIGHT:
609 case AST_SHIFT_SLEFT:
610 case AST_SHIFT_SRIGHT:
611 case AST_POW:
612 detect_width_simple = true;
613 child_1_is_self_determined = true;
614 break;
615
616 case AST_LT:
617 case AST_LE:
618 case AST_EQ:
619 case AST_NE:
620 case AST_EQX:
621 case AST_NEX:
622 case AST_GE:
623 case AST_GT:
624 width_hint = -1;
625 sign_hint = true;
626 for (auto child : children) {
627 while (!child->basic_prep && child->simplify(false, false, in_lvalue, stage, -1, false, in_param) == true)
628 did_something = true;
629 child->detectSignWidthWorker(width_hint, sign_hint);
630 }
631 reset_width_after_children = true;
632 break;
633
634 case AST_LOGIC_AND:
635 case AST_LOGIC_OR:
636 case AST_LOGIC_NOT:
637 detect_width_simple = true;
638 children_are_self_determined = true;
639 break;
640
641 case AST_TERNARY:
642 detect_width_simple = true;
643 child_0_is_self_determined = true;
644 break;
645
646 case AST_MEMRD:
647 detect_width_simple = true;
648 children_are_self_determined = true;
649 break;
650
651 case AST_FCALL:
652 case AST_TCALL:
653 children_are_self_determined = true;
654 break;
655
656 default:
657 width_hint = -1;
658 sign_hint = false;
659 }
660
661 if (detect_width_simple && width_hint < 0) {
662 if (type == AST_REPLICATE)
663 while (children[0]->simplify(true, false, in_lvalue, stage, -1, false, true) == true)
664 did_something = true;
665 for (auto child : children)
666 while (!child->basic_prep && child->simplify(false, false, in_lvalue, stage, -1, false, in_param) == true)
667 did_something = true;
668 detectSignWidth(width_hint, sign_hint);
669 }
670
671 if (type == AST_FCALL && str == "\\$past")
672 detectSignWidth(width_hint, sign_hint);
673
674 if (type == AST_TERNARY) {
675 int width_hint_left, width_hint_right;
676 bool sign_hint_left, sign_hint_right;
677 bool found_real_left, found_real_right;
678 children[1]->detectSignWidth(width_hint_left, sign_hint_left, &found_real_left);
679 children[2]->detectSignWidth(width_hint_right, sign_hint_right, &found_real_right);
680 if (found_real_left || found_real_right) {
681 child_1_is_self_determined = true;
682 child_2_is_self_determined = true;
683 }
684 }
685
686 if (type == AST_CONDX && children.size() > 0 && children.at(0)->type == AST_CONSTANT) {
687 for (auto &bit : children.at(0)->bits)
688 if (bit == State::Sz || bit == State::Sx)
689 bit = State::Sa;
690 }
691
692 if (type == AST_CONDZ && children.size() > 0 && children.at(0)->type == AST_CONSTANT) {
693 for (auto &bit : children.at(0)->bits)
694 if (bit == State::Sz)
695 bit = State::Sa;
696 }
697
698 if (const_fold && type == AST_CASE)
699 {
700 while (children[0]->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param)) { }
701 if (children[0]->type == AST_CONSTANT && children[0]->bits_only_01()) {
702 std::vector<AstNode*> new_children;
703 new_children.push_back(children[0]);
704 for (int i = 1; i < GetSize(children); i++) {
705 AstNode *child = children[i];
706 log_assert(child->type == AST_COND || child->type == AST_CONDX || child->type == AST_CONDZ);
707 for (auto v : child->children) {
708 if (v->type == AST_DEFAULT)
709 goto keep_const_cond;
710 if (v->type == AST_BLOCK)
711 continue;
712 while (v->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param)) { }
713 if (v->type == AST_CONSTANT && v->bits_only_01()) {
714 if (v->bits == children[0]->bits) {
715 while (i+1 < GetSize(children))
716 delete children[++i];
717 goto keep_const_cond;
718 }
719 continue;
720 }
721 goto keep_const_cond;
722 }
723 if (0)
724 keep_const_cond:
725 new_children.push_back(child);
726 else
727 delete child;
728 }
729 new_children.swap(children);
730 }
731 }
732
733 // simplify all children first
734 // (iterate by index as e.g. auto wires can add new children in the process)
735 for (size_t i = 0; i < children.size(); i++) {
736 bool did_something_here = true;
737 bool backup_flag_autowire = flag_autowire;
738 if ((type == AST_GENFOR || type == AST_FOR) && i >= 3)
739 break;
740 if ((type == AST_GENIF || type == AST_GENCASE) && i >= 1)
741 break;
742 if (type == AST_GENBLOCK)
743 break;
744 if (type == AST_BLOCK && !str.empty())
745 break;
746 if (type == AST_PREFIX && i >= 1)
747 break;
748 if (type == AST_DEFPARAM && i == 0)
749 flag_autowire = true;
750 while (did_something_here && i < children.size()) {
751 bool const_fold_here = const_fold, in_lvalue_here = in_lvalue;
752 int width_hint_here = width_hint;
753 bool sign_hint_here = sign_hint;
754 bool in_param_here = in_param;
755 if (i == 0 && (type == AST_REPLICATE || type == AST_WIRE))
756 const_fold_here = true, in_param_here = true;
757 if (type == AST_PARAMETER || type == AST_LOCALPARAM)
758 const_fold_here = true;
759 if (i == 0 && (type == AST_ASSIGN || type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE))
760 in_lvalue_here = true;
761 if (type == AST_BLOCK) {
762 current_block = this;
763 current_block_child = children[i];
764 }
765 if ((type == AST_ALWAYS || type == AST_INITIAL) && children[i]->type == AST_BLOCK)
766 current_top_block = children[i];
767 if (i == 0 && child_0_is_self_determined)
768 width_hint_here = -1, sign_hint_here = false;
769 if (i == 1 && child_1_is_self_determined)
770 width_hint_here = -1, sign_hint_here = false;
771 if (i == 2 && child_2_is_self_determined)
772 width_hint_here = -1, sign_hint_here = false;
773 if (children_are_self_determined)
774 width_hint_here = -1, sign_hint_here = false;
775 did_something_here = children[i]->simplify(const_fold_here, at_zero, in_lvalue_here, stage, width_hint_here, sign_hint_here, in_param_here);
776 if (did_something_here)
777 did_something = true;
778 }
779 if (stage == 2 && children[i]->type == AST_INITIAL && current_ast_mod != this) {
780 current_ast_mod->children.push_back(children[i]);
781 children.erase(children.begin() + (i--));
782 did_something = true;
783 }
784 flag_autowire = backup_flag_autowire;
785 }
786 for (auto &attr : attributes) {
787 while (attr.second->simplify(true, false, false, stage, -1, false, true))
788 did_something = true;
789 }
790
791 if (reset_width_after_children) {
792 width_hint = backup_width_hint;
793 sign_hint = backup_sign_hint;
794 if (width_hint < 0)
795 detectSignWidth(width_hint, sign_hint);
796 }
797
798 current_block = backup_current_block;
799 current_block_child = backup_current_block_child;
800 current_top_block = backup_current_top_block;
801 current_always = backup_current_always;
802 current_always_clocked = backup_current_always_clocked;
803
804 for (auto it = backup_scope.begin(); it != backup_scope.end(); it++) {
805 if (it->second == NULL)
806 current_scope.erase(it->first);
807 else
808 current_scope[it->first] = it->second;
809 }
810
811 current_filename = filename;
812
813 if (type == AST_MODULE)
814 current_scope.clear();
815
816 // convert defparam nodes to cell parameters
817 if (type == AST_DEFPARAM && !children.empty())
818 {
819 if (children[0]->type != AST_IDENTIFIER)
820 log_file_error(filename, location.first_line, "Module name in defparam contains non-constant expressions!\n");
821
822 string modname, paramname = children[0]->str;
823
824 size_t pos = paramname.rfind('.');
825
826 while (pos != 0 && pos != std::string::npos)
827 {
828 modname = paramname.substr(0, pos);
829
830 if (current_scope.count(modname))
831 break;
832
833 pos = paramname.rfind('.', pos - 1);
834 }
835
836 if (pos == std::string::npos)
837 log_file_error(filename, location.first_line, "Can't find object for defparam `%s`!\n", RTLIL::unescape_id(paramname).c_str());
838
839 paramname = "\\" + paramname.substr(pos+1);
840
841 if (current_scope.at(modname)->type != AST_CELL)
842 log_file_error(filename, location.first_line, "Defparam argument `%s . %s` does not match a cell!\n",
843 RTLIL::unescape_id(modname).c_str(), RTLIL::unescape_id(paramname).c_str());
844
845 AstNode *paraset = new AstNode(AST_PARASET, children[1]->clone(), GetSize(children) > 2 ? children[2]->clone() : NULL);
846 paraset->str = paramname;
847
848 AstNode *cell = current_scope.at(modname);
849 cell->children.insert(cell->children.begin() + 1, paraset);
850 delete_children();
851 }
852
853 // resolve typedefs
854 if (type == AST_TYPEDEF) {
855 log_assert(children.size() == 1);
856 log_assert(children[0]->type == AST_WIRE || children[0]->type == AST_MEMORY);
857 while(children[0]->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param))
858 did_something = true;
859 log_assert(!children[0]->is_custom_type);
860 }
861
862 // resolve types of wires
863 if (type == AST_WIRE || type == AST_MEMORY) {
864 if (is_custom_type) {
865 log_assert(children.size() >= 1);
866 log_assert(children[0]->type == AST_WIRETYPE);
867 if (!current_scope.count(children[0]->str))
868 log_file_error(filename, location.first_line, "Unknown identifier `%s' used as type name\n", children[0]->str.c_str());
869 AstNode *resolved_type = current_scope.at(children[0]->str);
870 if (resolved_type->type != AST_TYPEDEF)
871 log_file_error(filename, location.first_line, "`%s' does not name a type\n", children[0]->str.c_str());
872 log_assert(resolved_type->children.size() == 1);
873 AstNode *templ = resolved_type->children[0];
874 // Remove type reference
875 delete children[0];
876 children.erase(children.begin());
877
878 // Ensure typedef itself is fully simplified
879 while(templ->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param)) {};
880
881 if (type == AST_WIRE)
882 type = templ->type;
883 is_reg = templ->is_reg;
884 is_logic = templ->is_logic;
885 is_signed = templ->is_signed;
886 is_string = templ->is_string;
887 is_custom_type = templ->is_custom_type;
888
889 range_valid = templ->range_valid;
890 range_swapped = templ->range_swapped;
891 range_left = templ->range_left;
892 range_right = templ->range_right;
893 attributes["\\wiretype"] = mkconst_str(resolved_type->str);
894 //check if enum
895 if (templ->attributes.count("\\enum_type")){
896 //get reference to enum node:
897 std::string enum_type = templ->attributes["\\enum_type"]->str.c_str();
898 // log("enum_type=%s (count=%lu)\n", enum_type.c_str(), current_scope.count(enum_type));
899 // log("current scope:\n");
900 // for (auto &it : current_scope)
901 // log(" %s\n", it.first.c_str());
902 log_assert(current_scope.count(enum_type) == 1);
903 AstNode *enum_node = current_scope.at(enum_type);
904 log_assert(enum_node->type == AST_ENUM);
905 //get width from 1st enum item:
906 log_assert(enum_node->children.size() >= 1);
907 AstNode *enum_item0 = enum_node->children[0];
908 log_assert(enum_item0->type == AST_ENUM_ITEM);
909 int width;
910 if (!enum_item0->range_valid)
911 width = 1;
912 else if (enum_item0->range_swapped)
913 width = enum_item0->range_right - enum_item0->range_left + 1;
914 else
915 width = enum_item0->range_left - enum_item0->range_right + 1;
916 log_assert(width > 0);
917 //add declared enum items:
918 for (auto enum_item : enum_node->children){
919 log_assert(enum_item->type == AST_ENUM_ITEM);
920 //get is_signed
921 bool is_signed;
922 if (enum_item->children.size() == 1){
923 is_signed = false;
924 } else if (enum_item->children.size() == 2){
925 log_assert(enum_item->children[1]->type == AST_RANGE);
926 is_signed = enum_item->children[1]->is_signed;
927 } else {
928 log_error("enum_item children size==%lu, expected 1 or 2 for %s (%s)\n",
929 enum_item->children.size(),
930 enum_item->str.c_str(), enum_node->str.c_str()
931 );
932 }
933 //start building attribute string
934 std::string enum_item_str = "\\enum_";
935 enum_item_str.append(std::to_string(width));
936 enum_item_str.append("_");
937 //get enum item value
938 if(enum_item->children[0]->type != AST_CONSTANT){
939 log_error("expected const, got %s for %s (%s)\n",
940 type2str(enum_item->children[0]->type).c_str(),
941 enum_item->str.c_str(), enum_node->str.c_str()
942 );
943 }
944 int val = enum_item->children[0]->asInt(is_signed);
945 enum_item_str.append(std::to_string(val));
946 //set attribute for available val to enum item name mappings
947 attributes[enum_item_str.c_str()] = mkconst_str(enum_item->str);
948 }
949 }
950
951 // Insert clones children from template at beginning
952 for (int i = 0; i < GetSize(templ->children); i++)
953 children.insert(children.begin() + i, templ->children[i]->clone());
954
955 if (type == AST_MEMORY && GetSize(children) == 1) {
956 // Single-bit memories must have [0:0] range
957 AstNode *rng = new AstNode(AST_RANGE);
958 rng->children.push_back(AstNode::mkconst_int(0, true));
959 rng->children.push_back(AstNode::mkconst_int(0, true));
960 children.insert(children.begin(), rng);
961 }
962
963 did_something = true;
964 }
965 log_assert(!is_custom_type);
966 }
967
968 // resolve types of parameters
969 if (type == AST_LOCALPARAM || type == AST_PARAMETER) {
970 if (is_custom_type) {
971 log_assert(children.size() == 2);
972 log_assert(children[1]->type == AST_WIRETYPE);
973 if (!current_scope.count(children[1]->str))
974 log_file_error(filename, location.first_line, "Unknown identifier `%s' used as type name\n", children[1]->str.c_str());
975 AstNode *resolved_type = current_scope.at(children[1]->str);
976 if (resolved_type->type != AST_TYPEDEF)
977 log_file_error(filename, location.first_line, "`%s' does not name a type\n", children[1]->str.c_str());
978 log_assert(resolved_type->children.size() == 1);
979 AstNode *templ = resolved_type->children[0];
980 delete children[1];
981 children.pop_back();
982
983 // Ensure typedef itself is fully simplified
984 while(templ->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param)) {};
985
986 if (templ->type == AST_MEMORY)
987 log_file_error(filename, location.first_line, "unpacked array type `%s' cannot be used for a parameter\n", children[1]->str.c_str());
988 is_signed = templ->is_signed;
989 is_string = templ->is_string;
990 is_custom_type = templ->is_custom_type;
991
992 range_valid = templ->range_valid;
993 range_swapped = templ->range_swapped;
994 range_left = templ->range_left;
995 range_right = templ->range_right;
996 attributes["\\wiretype"] = mkconst_str(resolved_type->str);
997 for (auto template_child : templ->children)
998 children.push_back(template_child->clone());
999 did_something = true;
1000 }
1001 log_assert(!is_custom_type);
1002 }
1003
1004 // resolve constant prefixes
1005 if (type == AST_PREFIX) {
1006 if (children[0]->type != AST_CONSTANT) {
1007 // dumpAst(NULL, "> ");
1008 log_file_error(filename, location.first_line, "Index in generate block prefix syntax is not constant!\n");
1009 }
1010 if (children[1]->type == AST_PREFIX)
1011 children[1]->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param);
1012 log_assert(children[1]->type == AST_IDENTIFIER);
1013 newNode = children[1]->clone();
1014 const char *second_part = children[1]->str.c_str();
1015 if (second_part[0] == '\\')
1016 second_part++;
1017 newNode->str = stringf("%s[%d].%s", str.c_str(), children[0]->integer, second_part);
1018 goto apply_newNode;
1019 }
1020
1021 // evaluate TO_BITS nodes
1022 if (type == AST_TO_BITS) {
1023 if (children[0]->type != AST_CONSTANT)
1024 log_file_error(filename, location.first_line, "Left operand of to_bits expression is not constant!\n");
1025 if (children[1]->type != AST_CONSTANT)
1026 log_file_error(filename, location.first_line, "Right operand of to_bits expression is not constant!\n");
1027 RTLIL::Const new_value = children[1]->bitsAsConst(children[0]->bitsAsConst().as_int(), children[1]->is_signed);
1028 newNode = mkconst_bits(new_value.bits, children[1]->is_signed);
1029 goto apply_newNode;
1030 }
1031
1032 // annotate constant ranges
1033 if (type == AST_RANGE) {
1034 bool old_range_valid = range_valid;
1035 range_valid = false;
1036 range_swapped = false;
1037 range_left = -1;
1038 range_right = 0;
1039 log_assert(children.size() >= 1);
1040 if (children[0]->type == AST_CONSTANT) {
1041 range_valid = true;
1042 range_left = children[0]->integer;
1043 if (children.size() == 1)
1044 range_right = range_left;
1045 }
1046 if (children.size() >= 2) {
1047 if (children[1]->type == AST_CONSTANT)
1048 range_right = children[1]->integer;
1049 else
1050 range_valid = false;
1051 }
1052 if (old_range_valid != range_valid)
1053 did_something = true;
1054 if (range_valid && range_left >= 0 && range_right > range_left) {
1055 int tmp = range_right;
1056 range_right = range_left;
1057 range_left = tmp;
1058 range_swapped = true;
1059 }
1060 }
1061
1062 // annotate wires with their ranges
1063 if (type == AST_WIRE) {
1064 if (children.size() > 0) {
1065 if (children[0]->range_valid) {
1066 if (!range_valid)
1067 did_something = true;
1068 range_valid = true;
1069 range_swapped = children[0]->range_swapped;
1070 range_left = children[0]->range_left;
1071 range_right = children[0]->range_right;
1072 }
1073 } else {
1074 if (!range_valid)
1075 did_something = true;
1076 range_valid = true;
1077 range_swapped = false;
1078 range_left = 0;
1079 range_right = 0;
1080 }
1081 }
1082
1083 // resolve multiranges on memory decl
1084 if (type == AST_MEMORY && children.size() > 1 && children[1]->type == AST_MULTIRANGE)
1085 {
1086 int total_size = 1;
1087 multirange_dimensions.clear();
1088 for (auto range : children[1]->children) {
1089 if (!range->range_valid)
1090 log_file_error(filename, location.first_line, "Non-constant range on memory decl.\n");
1091 multirange_dimensions.push_back(min(range->range_left, range->range_right));
1092 multirange_dimensions.push_back(max(range->range_left, range->range_right) - min(range->range_left, range->range_right) + 1);
1093 total_size *= multirange_dimensions.back();
1094 }
1095 delete children[1];
1096 children[1] = new AstNode(AST_RANGE, AstNode::mkconst_int(0, true), AstNode::mkconst_int(total_size-1, true));
1097 did_something = true;
1098 }
1099
1100 // resolve multiranges on memory access
1101 if (type == AST_IDENTIFIER && id2ast && id2ast->type == AST_MEMORY && children.size() > 0 && children[0]->type == AST_MULTIRANGE)
1102 {
1103 AstNode *index_expr = nullptr;
1104
1105 for (int i = 0; 2*i < GetSize(id2ast->multirange_dimensions); i++)
1106 {
1107 if (GetSize(children[0]->children) < i)
1108 log_file_error(filename, location.first_line, "Insufficient number of array indices for %s.\n", log_id(str));
1109
1110 AstNode *new_index_expr = children[0]->children[i]->children.at(0)->clone();
1111
1112 if (id2ast->multirange_dimensions[2*i])
1113 new_index_expr = new AstNode(AST_SUB, new_index_expr, AstNode::mkconst_int(id2ast->multirange_dimensions[2*i], true));
1114
1115 if (i == 0)
1116 index_expr = new_index_expr;
1117 else
1118 index_expr = new AstNode(AST_ADD, new AstNode(AST_MUL, index_expr, AstNode::mkconst_int(id2ast->multirange_dimensions[2*i+1], true)), new_index_expr);
1119 }
1120
1121 for (int i = GetSize(id2ast->multirange_dimensions)/2; i < GetSize(children[0]->children); i++)
1122 children.push_back(children[0]->children[i]->clone());
1123
1124 delete children[0];
1125 if (index_expr == nullptr)
1126 children.erase(children.begin());
1127 else
1128 children[0] = new AstNode(AST_RANGE, index_expr);
1129
1130 did_something = true;
1131 }
1132
1133 // trim/extend parameters
1134 if (type == AST_PARAMETER || type == AST_LOCALPARAM || type == AST_ENUM_ITEM) {
1135 if (children.size() > 1 && children[1]->type == AST_RANGE) {
1136 if (!children[1]->range_valid)
1137 log_file_error(filename, location.first_line, "Non-constant width range on parameter decl.\n");
1138 int width = std::abs(children[1]->range_left - children[1]->range_right) + 1;
1139 if (children[0]->type == AST_REALVALUE) {
1140 RTLIL::Const constvalue = children[0]->realAsConst(width);
1141 log_file_warning(filename, location.first_line, "converting real value %e to binary %s.\n",
1142 children[0]->realvalue, log_signal(constvalue));
1143 delete children[0];
1144 children[0] = mkconst_bits(constvalue.bits, sign_hint);
1145 did_something = true;
1146 }
1147 if (children[0]->type == AST_CONSTANT) {
1148 if (width != int(children[0]->bits.size())) {
1149 RTLIL::SigSpec sig(children[0]->bits);
1150 sig.extend_u0(width, children[0]->is_signed);
1151 AstNode *old_child_0 = children[0];
1152 children[0] = mkconst_bits(sig.as_const().bits, is_signed);
1153 delete old_child_0;
1154 }
1155 children[0]->is_signed = is_signed;
1156 }
1157 range_valid = true;
1158 range_swapped = children[1]->range_swapped;
1159 range_left = children[1]->range_left;
1160 range_right = children[1]->range_right;
1161 } else
1162 if (children.size() > 1 && children[1]->type == AST_REALVALUE && children[0]->type == AST_CONSTANT) {
1163 double as_realvalue = children[0]->asReal(sign_hint);
1164 delete children[0];
1165 children[0] = new AstNode(AST_REALVALUE);
1166 children[0]->realvalue = as_realvalue;
1167 did_something = true;
1168 }
1169 }
1170
1171 // annotate identifiers using scope resolution and create auto-wires as needed
1172 if (type == AST_IDENTIFIER) {
1173 if (current_scope.count(str) == 0) {
1174 for (auto node : current_ast_mod->children) {
1175 //log("looking at mod scope child %s\n", type2str(node->type).c_str());
1176 switch (node->type) {
1177 case AST_PARAMETER:
1178 case AST_LOCALPARAM:
1179 case AST_WIRE:
1180 case AST_AUTOWIRE:
1181 case AST_GENVAR:
1182 case AST_MEMORY:
1183 case AST_FUNCTION:
1184 case AST_TASK:
1185 case AST_DPI_FUNCTION:
1186 //log("found child %s, %s\n", type2str(node->type).c_str(), node->str.c_str());
1187 if (str == node->str) {
1188 //log("add %s, type %s to scope\n", str.c_str(), type2str(node->type).c_str());
1189 current_scope[node->str] = node;
1190 }
1191 break;
1192 case AST_ENUM:
1193 current_scope[node->str] = node;
1194 for (auto enum_node : node->children) {
1195 log_assert(enum_node->type==AST_ENUM_ITEM);
1196 if (str == enum_node->str) {
1197 //log("\nadding enum item %s to scope\n", str.c_str());
1198 current_scope[str] = enum_node;
1199 }
1200 }
1201 break;
1202 default:
1203 break;
1204 }
1205 }
1206 }
1207 if (current_scope.count(str) == 0) {
1208 if (flag_autowire || str == "\\$global_clock") {
1209 AstNode *auto_wire = new AstNode(AST_AUTOWIRE);
1210 auto_wire->str = str;
1211 current_ast_mod->children.push_back(auto_wire);
1212 current_scope[str] = auto_wire;
1213 did_something = true;
1214 } else {
1215 log_file_error(filename, location.first_line, "Identifier `%s' is implicitly declared and `default_nettype is set to none.\n", str.c_str());
1216 }
1217 }
1218 if (id2ast != current_scope[str]) {
1219 id2ast = current_scope[str];
1220 did_something = true;
1221 }
1222 }
1223
1224 // split memory access with bit select to individual statements
1225 if (type == AST_IDENTIFIER && children.size() == 2 && children[0]->type == AST_RANGE && children[1]->type == AST_RANGE && !in_lvalue)
1226 {
1227 if (id2ast == NULL || id2ast->type != AST_MEMORY || children[0]->children.size() != 1)
1228 log_file_error(filename, location.first_line, "Invalid bit-select on memory access!\n");
1229
1230 int mem_width, mem_size, addr_bits;
1231 id2ast->meminfo(mem_width, mem_size, addr_bits);
1232
1233 int data_range_left = id2ast->children[0]->range_left;
1234 int data_range_right = id2ast->children[0]->range_right;
1235
1236 if (id2ast->children[0]->range_swapped)
1237 std::swap(data_range_left, data_range_right);
1238
1239 std::stringstream sstr;
1240 sstr << "$mem2bits$" << str << "$" << filename << ":" << location.first_line << "$" << (autoidx++);
1241 std::string wire_id = sstr.str();
1242
1243 AstNode *wire = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(data_range_left, true), mkconst_int(data_range_right, true)));
1244 wire->str = wire_id;
1245 if (current_block)
1246 wire->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
1247 current_ast_mod->children.push_back(wire);
1248 while (wire->simplify(true, false, false, 1, -1, false, false)) { }
1249
1250 AstNode *data = clone();
1251 delete data->children[1];
1252 data->children.pop_back();
1253
1254 AstNode *assign = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), data);
1255 assign->children[0]->str = wire_id;
1256 assign->children[0]->was_checked = true;
1257
1258 if (current_block)
1259 {
1260 size_t assign_idx = 0;
1261 while (assign_idx < current_block->children.size() && current_block->children[assign_idx] != current_block_child)
1262 assign_idx++;
1263 log_assert(assign_idx < current_block->children.size());
1264 current_block->children.insert(current_block->children.begin()+assign_idx, assign);
1265 wire->is_reg = true;
1266 }
1267 else
1268 {
1269 AstNode *proc = new AstNode(AST_ALWAYS, new AstNode(AST_BLOCK));
1270 proc->children[0]->children.push_back(assign);
1271 current_ast_mod->children.push_back(proc);
1272 }
1273
1274 newNode = new AstNode(AST_IDENTIFIER, children[1]->clone());
1275 newNode->str = wire_id;
1276 newNode->id2ast = wire;
1277 goto apply_newNode;
1278 }
1279
1280 if (type == AST_WHILE)
1281 log_file_error(filename, location.first_line, "While loops are only allowed in constant functions!\n");
1282
1283 if (type == AST_REPEAT)
1284 {
1285 AstNode *count = children[0];
1286 AstNode *body = children[1];
1287
1288 // eval count expression
1289 while (count->simplify(true, false, false, stage, 32, true, false)) { }
1290
1291 if (count->type != AST_CONSTANT)
1292 log_file_error(filename, location.first_line, "Repeat loops outside must have constant repeat counts!\n");
1293
1294 // convert to a block with the body repeated n times
1295 type = AST_BLOCK;
1296 children.clear();
1297 for (int i = 0; i < count->bitsAsConst().as_int(); i++)
1298 children.insert(children.begin(), body->clone());
1299
1300 delete count;
1301 delete body;
1302 did_something = true;
1303 }
1304
1305 // unroll for loops and generate-for blocks
1306 if ((type == AST_GENFOR || type == AST_FOR) && children.size() != 0)
1307 {
1308 AstNode *init_ast = children[0];
1309 AstNode *while_ast = children[1];
1310 AstNode *next_ast = children[2];
1311 AstNode *body_ast = children[3];
1312
1313 while (body_ast->type == AST_GENBLOCK && body_ast->str.empty() &&
1314 body_ast->children.size() == 1 && body_ast->children.at(0)->type == AST_GENBLOCK)
1315 body_ast = body_ast->children.at(0);
1316
1317 if (init_ast->type != AST_ASSIGN_EQ)
1318 log_file_error(filename, location.first_line, "Unsupported 1st expression of generate for-loop!\n");
1319 if (next_ast->type != AST_ASSIGN_EQ)
1320 log_file_error(filename, location.first_line, "Unsupported 3rd expression of generate for-loop!\n");
1321
1322 if (type == AST_GENFOR) {
1323 if (init_ast->children[0]->id2ast == NULL || init_ast->children[0]->id2ast->type != AST_GENVAR)
1324 log_file_error(filename, location.first_line, "Left hand side of 1st expression of generate for-loop is not a gen var!\n");
1325 if (next_ast->children[0]->id2ast == NULL || next_ast->children[0]->id2ast->type != AST_GENVAR)
1326 log_file_error(filename, location.first_line, "Left hand side of 3rd expression of generate for-loop is not a gen var!\n");
1327 } else {
1328 if (init_ast->children[0]->id2ast == NULL || init_ast->children[0]->id2ast->type != AST_WIRE)
1329 log_file_error(filename, location.first_line, "Left hand side of 1st expression of generate for-loop is not a register!\n");
1330 if (next_ast->children[0]->id2ast == NULL || next_ast->children[0]->id2ast->type != AST_WIRE)
1331 log_file_error(filename, location.first_line, "Left hand side of 3rd expression of generate for-loop is not a register!\n");
1332 }
1333
1334 if (init_ast->children[0]->id2ast != next_ast->children[0]->id2ast)
1335 log_file_error(filename, location.first_line, "Incompatible left-hand sides in 1st and 3rd expression of generate for-loop!\n");
1336
1337 // eval 1st expression
1338 AstNode *varbuf = init_ast->children[1]->clone();
1339 {
1340 int expr_width_hint = -1;
1341 bool expr_sign_hint = true;
1342 varbuf->detectSignWidth(expr_width_hint, expr_sign_hint);
1343 while (varbuf->simplify(true, false, false, stage, 32, true, false)) { }
1344 }
1345
1346 if (varbuf->type != AST_CONSTANT)
1347 log_file_error(filename, location.first_line, "Right hand side of 1st expression of generate for-loop is not constant!\n");
1348
1349 auto resolved = current_scope.at(init_ast->children[0]->str);
1350 if (resolved->range_valid) {
1351 int const_size = varbuf->range_left - varbuf->range_right;
1352 int resolved_size = resolved->range_left - resolved->range_right;
1353 if (const_size < resolved_size) {
1354 for (int i = const_size; i < resolved_size; i++)
1355 varbuf->bits.push_back(resolved->is_signed ? varbuf->bits.back() : State::S0);
1356 varbuf->range_left = resolved->range_left;
1357 varbuf->range_right = resolved->range_right;
1358 varbuf->range_swapped = resolved->range_swapped;
1359 varbuf->range_valid = resolved->range_valid;
1360 }
1361 }
1362
1363 varbuf = new AstNode(AST_LOCALPARAM, varbuf);
1364 varbuf->str = init_ast->children[0]->str;
1365
1366 AstNode *backup_scope_varbuf = current_scope[varbuf->str];
1367 current_scope[varbuf->str] = varbuf;
1368
1369 size_t current_block_idx = 0;
1370 if (type == AST_FOR) {
1371 while (current_block_idx < current_block->children.size() &&
1372 current_block->children[current_block_idx] != current_block_child)
1373 current_block_idx++;
1374 }
1375
1376 while (1)
1377 {
1378 // eval 2nd expression
1379 AstNode *buf = while_ast->clone();
1380 {
1381 int expr_width_hint = -1;
1382 bool expr_sign_hint = true;
1383 buf->detectSignWidth(expr_width_hint, expr_sign_hint);
1384 while (buf->simplify(true, false, false, stage, expr_width_hint, expr_sign_hint, false)) { }
1385 }
1386
1387 if (buf->type != AST_CONSTANT)
1388 log_file_error(filename, location.first_line, "2nd expression of generate for-loop is not constant!\n");
1389
1390 if (buf->integer == 0) {
1391 delete buf;
1392 break;
1393 }
1394 delete buf;
1395
1396 // expand body
1397 int index = varbuf->children[0]->integer;
1398 if (body_ast->type == AST_GENBLOCK)
1399 buf = body_ast->clone();
1400 else
1401 buf = new AstNode(AST_GENBLOCK, body_ast->clone());
1402 if (buf->str.empty()) {
1403 std::stringstream sstr;
1404 sstr << "$genblock$" << filename << ":" << location.first_line << "$" << (autoidx++);
1405 buf->str = sstr.str();
1406 }
1407 std::map<std::string, std::string> name_map;
1408 std::stringstream sstr;
1409 sstr << buf->str << "[" << index << "].";
1410 buf->expand_genblock(varbuf->str, sstr.str(), name_map);
1411
1412 if (type == AST_GENFOR) {
1413 for (size_t i = 0; i < buf->children.size(); i++) {
1414 buf->children[i]->simplify(false, false, false, stage, -1, false, false);
1415 current_ast_mod->children.push_back(buf->children[i]);
1416 }
1417 } else {
1418 for (size_t i = 0; i < buf->children.size(); i++)
1419 current_block->children.insert(current_block->children.begin() + current_block_idx++, buf->children[i]);
1420 }
1421 buf->children.clear();
1422 delete buf;
1423
1424 // eval 3rd expression
1425 buf = next_ast->children[1]->clone();
1426 {
1427 int expr_width_hint = -1;
1428 bool expr_sign_hint = true;
1429 buf->detectSignWidth(expr_width_hint, expr_sign_hint);
1430 while (buf->simplify(true, false, false, stage, expr_width_hint, expr_sign_hint, true)) { }
1431 }
1432
1433 if (buf->type != AST_CONSTANT)
1434 log_file_error(filename, location.first_line, "Right hand side of 3rd expression of generate for-loop is not constant (%s)!\n", type2str(buf->type).c_str());
1435
1436 delete varbuf->children[0];
1437 varbuf->children[0] = buf;
1438 }
1439
1440 if (type == AST_FOR) {
1441 AstNode *buf = next_ast->clone();
1442 delete buf->children[1];
1443 buf->children[1] = varbuf->children[0]->clone();
1444 current_block->children.insert(current_block->children.begin() + current_block_idx++, buf);
1445 }
1446
1447 current_scope[varbuf->str] = backup_scope_varbuf;
1448 delete varbuf;
1449 delete_children();
1450 did_something = true;
1451 }
1452
1453 // check for local objects in unnamed block
1454 if (type == AST_BLOCK && str.empty())
1455 {
1456 for (size_t i = 0; i < children.size(); i++)
1457 if (children[i]->type == AST_WIRE || children[i]->type == AST_MEMORY || children[i]->type == AST_PARAMETER || children[i]->type == AST_LOCALPARAM || children[i]->type == AST_TYPEDEF)
1458 log_file_error(children[i]->filename, children[i]->location.first_line, "Local declaration in unnamed block is an unsupported SystemVerilog feature!\n");
1459 }
1460
1461 // transform block with name
1462 if (type == AST_BLOCK && !str.empty())
1463 {
1464 std::map<std::string, std::string> name_map;
1465 expand_genblock(std::string(), str + ".", name_map);
1466
1467 std::vector<AstNode*> new_children;
1468 for (size_t i = 0; i < children.size(); i++)
1469 if (children[i]->type == AST_WIRE || children[i]->type == AST_MEMORY || children[i]->type == AST_PARAMETER || children[i]->type == AST_LOCALPARAM || children[i]->type == AST_TYPEDEF) {
1470 children[i]->simplify(false, false, false, stage, -1, false, false);
1471 current_ast_mod->children.push_back(children[i]);
1472 current_scope[children[i]->str] = children[i];
1473 } else
1474 new_children.push_back(children[i]);
1475
1476 children.swap(new_children);
1477 did_something = true;
1478 str.clear();
1479 }
1480
1481 // simplify unconditional generate block
1482 if (type == AST_GENBLOCK && children.size() != 0)
1483 {
1484 if (!str.empty()) {
1485 std::map<std::string, std::string> name_map;
1486 expand_genblock(std::string(), str + ".", name_map);
1487 }
1488
1489 for (size_t i = 0; i < children.size(); i++) {
1490 children[i]->simplify(false, false, false, stage, -1, false, false);
1491 current_ast_mod->children.push_back(children[i]);
1492 }
1493
1494 children.clear();
1495 did_something = true;
1496 }
1497
1498 // simplify generate-if blocks
1499 if (type == AST_GENIF && children.size() != 0)
1500 {
1501 AstNode *buf = children[0]->clone();
1502 while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
1503 if (buf->type != AST_CONSTANT) {
1504 // for (auto f : log_files)
1505 // dumpAst(f, "verilog-ast> ");
1506 log_file_error(filename, location.first_line, "Condition for generate if is not constant!\n");
1507 }
1508 if (buf->asBool() != 0) {
1509 delete buf;
1510 buf = children[1]->clone();
1511 } else {
1512 delete buf;
1513 buf = children.size() > 2 ? children[2]->clone() : NULL;
1514 }
1515
1516 if (buf)
1517 {
1518 if (buf->type != AST_GENBLOCK)
1519 buf = new AstNode(AST_GENBLOCK, buf);
1520
1521 if (!buf->str.empty()) {
1522 std::map<std::string, std::string> name_map;
1523 buf->expand_genblock(std::string(), buf->str + ".", name_map);
1524 }
1525
1526 for (size_t i = 0; i < buf->children.size(); i++) {
1527 buf->children[i]->simplify(false, false, false, stage, -1, false, false);
1528 current_ast_mod->children.push_back(buf->children[i]);
1529 }
1530
1531 buf->children.clear();
1532 delete buf;
1533 }
1534
1535 delete_children();
1536 did_something = true;
1537 }
1538
1539 // simplify generate-case blocks
1540 if (type == AST_GENCASE && children.size() != 0)
1541 {
1542 AstNode *buf = children[0]->clone();
1543 while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
1544 if (buf->type != AST_CONSTANT) {
1545 // for (auto f : log_files)
1546 // dumpAst(f, "verilog-ast> ");
1547 log_file_error(filename, location.first_line, "Condition for generate case is not constant!\n");
1548 }
1549
1550 bool ref_signed = buf->is_signed;
1551 RTLIL::Const ref_value = buf->bitsAsConst();
1552 delete buf;
1553
1554 AstNode *selected_case = NULL;
1555 for (size_t i = 1; i < children.size(); i++)
1556 {
1557 log_assert(children.at(i)->type == AST_COND || children.at(i)->type == AST_CONDX || children.at(i)->type == AST_CONDZ);
1558
1559 AstNode *this_genblock = NULL;
1560 for (auto child : children.at(i)->children) {
1561 log_assert(this_genblock == NULL);
1562 if (child->type == AST_GENBLOCK)
1563 this_genblock = child;
1564 }
1565
1566 for (auto child : children.at(i)->children)
1567 {
1568 if (child->type == AST_DEFAULT) {
1569 if (selected_case == NULL)
1570 selected_case = this_genblock;
1571 continue;
1572 }
1573 if (child->type == AST_GENBLOCK)
1574 continue;
1575
1576 buf = child->clone();
1577 while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
1578 if (buf->type != AST_CONSTANT) {
1579 // for (auto f : log_files)
1580 // dumpAst(f, "verilog-ast> ");
1581 log_file_error(filename, location.first_line, "Expression in generate case is not constant!\n");
1582 }
1583
1584 bool is_selected = RTLIL::const_eq(ref_value, buf->bitsAsConst(), ref_signed && buf->is_signed, ref_signed && buf->is_signed, 1).as_bool();
1585 delete buf;
1586
1587 if (is_selected) {
1588 selected_case = this_genblock;
1589 i = children.size();
1590 break;
1591 }
1592 }
1593 }
1594
1595 if (selected_case != NULL)
1596 {
1597 log_assert(selected_case->type == AST_GENBLOCK);
1598 buf = selected_case->clone();
1599
1600 if (!buf->str.empty()) {
1601 std::map<std::string, std::string> name_map;
1602 buf->expand_genblock(std::string(), buf->str + ".", name_map);
1603 }
1604
1605 for (size_t i = 0; i < buf->children.size(); i++) {
1606 buf->children[i]->simplify(false, false, false, stage, -1, false, false);
1607 current_ast_mod->children.push_back(buf->children[i]);
1608 }
1609
1610 buf->children.clear();
1611 delete buf;
1612 }
1613
1614 delete_children();
1615 did_something = true;
1616 }
1617
1618 // unroll cell arrays
1619 if (type == AST_CELLARRAY)
1620 {
1621 if (!children.at(0)->range_valid)
1622 log_file_error(filename, location.first_line, "Non-constant array range on cell array.\n");
1623
1624 newNode = new AstNode(AST_GENBLOCK);
1625 int num = max(children.at(0)->range_left, children.at(0)->range_right) - min(children.at(0)->range_left, children.at(0)->range_right) + 1;
1626
1627 for (int i = 0; i < num; i++) {
1628 int idx = children.at(0)->range_left > children.at(0)->range_right ? children.at(0)->range_right + i : children.at(0)->range_right - i;
1629 AstNode *new_cell = children.at(1)->clone();
1630 newNode->children.push_back(new_cell);
1631 new_cell->str += stringf("[%d]", idx);
1632 if (new_cell->type == AST_PRIMITIVE) {
1633 log_file_error(filename, location.first_line, "Cell arrays of primitives are currently not supported.\n");
1634 } else {
1635 log_assert(new_cell->children.at(0)->type == AST_CELLTYPE);
1636 new_cell->children.at(0)->str = stringf("$array:%d:%d:%s", i, num, new_cell->children.at(0)->str.c_str());
1637 }
1638 }
1639
1640 goto apply_newNode;
1641 }
1642
1643 // replace primitives with assignments
1644 if (type == AST_PRIMITIVE)
1645 {
1646 if (children.size() < 2)
1647 log_file_error(filename, location.first_line, "Insufficient number of arguments for primitive `%s'!\n", str.c_str());
1648
1649 std::vector<AstNode*> children_list;
1650 for (auto child : children) {
1651 log_assert(child->type == AST_ARGUMENT);
1652 log_assert(child->children.size() == 1);
1653 children_list.push_back(child->children[0]);
1654 child->children.clear();
1655 delete child;
1656 }
1657 children.clear();
1658
1659 if (str == "bufif0" || str == "bufif1" || str == "notif0" || str == "notif1")
1660 {
1661 if (children_list.size() != 3)
1662 log_file_error(filename, location.first_line, "Invalid number of arguments for primitive `%s'!\n", str.c_str());
1663
1664 std::vector<RTLIL::State> z_const(1, RTLIL::State::Sz);
1665
1666 AstNode *mux_input = children_list.at(1);
1667 if (str == "notif0" || str == "notif1") {
1668 mux_input = new AstNode(AST_BIT_NOT, mux_input);
1669 }
1670 AstNode *node = new AstNode(AST_TERNARY, children_list.at(2));
1671 if (str == "bufif0") {
1672 node->children.push_back(AstNode::mkconst_bits(z_const, false));
1673 node->children.push_back(mux_input);
1674 } else {
1675 node->children.push_back(mux_input);
1676 node->children.push_back(AstNode::mkconst_bits(z_const, false));
1677 }
1678
1679 str.clear();
1680 type = AST_ASSIGN;
1681 children.push_back(children_list.at(0));
1682 children.back()->was_checked = true;
1683 children.push_back(node);
1684 did_something = true;
1685 }
1686 else
1687 {
1688 AstNodeType op_type = AST_NONE;
1689 bool invert_results = false;
1690
1691 if (str == "and")
1692 op_type = AST_BIT_AND;
1693 if (str == "nand")
1694 op_type = AST_BIT_AND, invert_results = true;
1695 if (str == "or")
1696 op_type = AST_BIT_OR;
1697 if (str == "nor")
1698 op_type = AST_BIT_OR, invert_results = true;
1699 if (str == "xor")
1700 op_type = AST_BIT_XOR;
1701 if (str == "xnor")
1702 op_type = AST_BIT_XOR, invert_results = true;
1703 if (str == "buf")
1704 op_type = AST_POS;
1705 if (str == "not")
1706 op_type = AST_POS, invert_results = true;
1707 log_assert(op_type != AST_NONE);
1708
1709 AstNode *node = children_list[1];
1710 if (op_type != AST_POS)
1711 for (size_t i = 2; i < children_list.size(); i++)
1712 node = new AstNode(op_type, node, children_list[i]);
1713 if (invert_results)
1714 node = new AstNode(AST_BIT_NOT, node);
1715
1716 str.clear();
1717 type = AST_ASSIGN;
1718 children.push_back(children_list[0]);
1719 children.back()->was_checked = true;
1720 children.push_back(node);
1721 did_something = true;
1722 }
1723 }
1724
1725 // replace dynamic ranges in left-hand side expressions (e.g. "foo[bar] <= 1'b1;") with
1726 // a big case block that selects the correct single-bit assignment.
1727 if (type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE) {
1728 if (children[0]->type != AST_IDENTIFIER || children[0]->children.size() == 0)
1729 goto skip_dynamic_range_lvalue_expansion;
1730 if (children[0]->children[0]->range_valid || did_something)
1731 goto skip_dynamic_range_lvalue_expansion;
1732 if (children[0]->id2ast == NULL || children[0]->id2ast->type != AST_WIRE)
1733 goto skip_dynamic_range_lvalue_expansion;
1734 if (!children[0]->id2ast->range_valid)
1735 goto skip_dynamic_range_lvalue_expansion;
1736 int source_width = children[0]->id2ast->range_left - children[0]->id2ast->range_right + 1;
1737 int result_width = 1;
1738 AstNode *shift_expr = NULL;
1739 AstNode *range = children[0]->children[0];
1740 if (range->children.size() == 1) {
1741 shift_expr = range->children[0]->clone();
1742 } else {
1743 shift_expr = range->children[1]->clone();
1744 AstNode *left_at_zero_ast = range->children[0]->clone();
1745 AstNode *right_at_zero_ast = range->children[1]->clone();
1746 while (left_at_zero_ast->simplify(true, true, false, stage, -1, false, false)) { }
1747 while (right_at_zero_ast->simplify(true, true, false, stage, -1, false, false)) { }
1748 if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
1749 log_file_error(filename, location.first_line, "Unsupported expression on dynamic range select on signal `%s'!\n", str.c_str());
1750 result_width = abs(int(left_at_zero_ast->integer - right_at_zero_ast->integer)) + 1;
1751 }
1752 did_something = true;
1753 newNode = new AstNode(AST_CASE, shift_expr);
1754 for (int i = 0; i < source_width; i++) {
1755 int start_bit = children[0]->id2ast->range_right + i;
1756 AstNode *cond = new AstNode(AST_COND, mkconst_int(start_bit, true));
1757 AstNode *lvalue = children[0]->clone();
1758 lvalue->delete_children();
1759 int end_bit = std::min(start_bit+result_width,source_width) - 1;
1760 lvalue->children.push_back(new AstNode(AST_RANGE,
1761 mkconst_int(end_bit, true), mkconst_int(start_bit, true)));
1762 cond->children.push_back(new AstNode(AST_BLOCK, new AstNode(type, lvalue, children[1]->clone())));
1763 newNode->children.push_back(cond);
1764 }
1765 goto apply_newNode;
1766 }
1767 skip_dynamic_range_lvalue_expansion:;
1768
1769 if (stage > 1 && (type == AST_ASSERT || type == AST_ASSUME || type == AST_LIVE || type == AST_FAIR || type == AST_COVER) && current_block != NULL)
1770 {
1771 std::stringstream sstr;
1772 sstr << "$formal$" << filename << ":" << location.first_line << "$" << (autoidx++);
1773 std::string id_check = sstr.str() + "_CHECK", id_en = sstr.str() + "_EN";
1774
1775 AstNode *wire_check = new AstNode(AST_WIRE);
1776 wire_check->str = id_check;
1777 wire_check->was_checked = true;
1778 current_ast_mod->children.push_back(wire_check);
1779 current_scope[wire_check->str] = wire_check;
1780 while (wire_check->simplify(true, false, false, 1, -1, false, false)) { }
1781
1782 AstNode *wire_en = new AstNode(AST_WIRE);
1783 wire_en->str = id_en;
1784 wire_en->was_checked = true;
1785 current_ast_mod->children.push_back(wire_en);
1786 if (current_always_clocked) {
1787 current_ast_mod->children.push_back(new AstNode(AST_INITIAL, new AstNode(AST_BLOCK, new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), AstNode::mkconst_int(0, false, 1)))));
1788 current_ast_mod->children.back()->children[0]->children[0]->children[0]->str = id_en;
1789 current_ast_mod->children.back()->children[0]->children[0]->children[0]->was_checked = true;
1790 }
1791 current_scope[wire_en->str] = wire_en;
1792 while (wire_en->simplify(true, false, false, 1, -1, false, false)) { }
1793
1794 AstNode *check_defval;
1795 if (type == AST_LIVE || type == AST_FAIR) {
1796 check_defval = new AstNode(AST_REDUCE_BOOL, children[0]->clone());
1797 } else {
1798 std::vector<RTLIL::State> x_bit;
1799 x_bit.push_back(RTLIL::State::Sx);
1800 check_defval = mkconst_bits(x_bit, false);
1801 }
1802
1803 AstNode *assign_check = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), check_defval);
1804 assign_check->children[0]->str = id_check;
1805 assign_check->children[0]->was_checked = true;
1806
1807 AstNode *assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_int(0, false, 1));
1808 assign_en->children[0]->str = id_en;
1809 assign_en->children[0]->was_checked = true;
1810
1811 AstNode *default_signals = new AstNode(AST_BLOCK);
1812 default_signals->children.push_back(assign_check);
1813 default_signals->children.push_back(assign_en);
1814 current_top_block->children.insert(current_top_block->children.begin(), default_signals);
1815
1816 if (type == AST_LIVE || type == AST_FAIR) {
1817 assign_check = nullptr;
1818 } else {
1819 assign_check = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), new AstNode(AST_REDUCE_BOOL, children[0]->clone()));
1820 assign_check->children[0]->str = id_check;
1821 assign_check->children[0]->was_checked = true;
1822 }
1823
1824 if (current_always == nullptr || current_always->type != AST_INITIAL) {
1825 assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_int(1, false, 1));
1826 } else {
1827 assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), new AstNode(AST_FCALL));
1828 assign_en->children[1]->str = "\\$initstate";
1829 }
1830 assign_en->children[0]->str = id_en;
1831 assign_en->children[0]->was_checked = true;
1832
1833 newNode = new AstNode(AST_BLOCK);
1834 if (assign_check != nullptr)
1835 newNode->children.push_back(assign_check);
1836 newNode->children.push_back(assign_en);
1837
1838 AstNode *assertnode = new AstNode(type);
1839 assertnode->location = location;
1840 assertnode->str = str;
1841 assertnode->children.push_back(new AstNode(AST_IDENTIFIER));
1842 assertnode->children.push_back(new AstNode(AST_IDENTIFIER));
1843 assertnode->children[0]->str = id_check;
1844 assertnode->children[1]->str = id_en;
1845 assertnode->attributes.swap(attributes);
1846 current_ast_mod->children.push_back(assertnode);
1847
1848 goto apply_newNode;
1849 }
1850
1851 if (stage > 1 && (type == AST_ASSERT || type == AST_ASSUME || type == AST_LIVE || type == AST_FAIR || type == AST_COVER) && children.size() == 1)
1852 {
1853 children.push_back(mkconst_int(1, false, 1));
1854 did_something = true;
1855 }
1856
1857 // found right-hand side identifier for memory -> replace with memory read port
1858 if (stage > 1 && type == AST_IDENTIFIER && id2ast != NULL && id2ast->type == AST_MEMORY && !in_lvalue &&
1859 children.size() == 1 && children[0]->type == AST_RANGE && children[0]->children.size() == 1) {
1860 newNode = new AstNode(AST_MEMRD, children[0]->children[0]->clone());
1861 newNode->str = str;
1862 newNode->id2ast = id2ast;
1863 goto apply_newNode;
1864 }
1865
1866 // assignment with nontrivial member in left-hand concat expression -> split assignment
1867 if ((type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE) && children[0]->type == AST_CONCAT && width_hint > 0)
1868 {
1869 bool found_nontrivial_member = false;
1870
1871 for (auto child : children[0]->children) {
1872 if (child->type == AST_IDENTIFIER && child->id2ast != NULL && child->id2ast->type == AST_MEMORY)
1873 found_nontrivial_member = true;
1874 }
1875
1876 if (found_nontrivial_member)
1877 {
1878 newNode = new AstNode(AST_BLOCK);
1879
1880 AstNode *wire_tmp = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(width_hint-1, true), mkconst_int(0, true)));
1881 wire_tmp->str = stringf("$splitcmplxassign$%s:%d$%d", filename.c_str(), location.first_line, autoidx++);
1882 current_ast_mod->children.push_back(wire_tmp);
1883 current_scope[wire_tmp->str] = wire_tmp;
1884 wire_tmp->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
1885 while (wire_tmp->simplify(true, false, false, 1, -1, false, false)) { }
1886 wire_tmp->is_logic = true;
1887
1888 AstNode *wire_tmp_id = new AstNode(AST_IDENTIFIER);
1889 wire_tmp_id->str = wire_tmp->str;
1890
1891 newNode->children.push_back(new AstNode(AST_ASSIGN_EQ, wire_tmp_id, children[1]->clone()));
1892 newNode->children.back()->was_checked = true;
1893
1894 int cursor = 0;
1895 for (auto child : children[0]->children)
1896 {
1897 int child_width_hint = -1;
1898 bool child_sign_hint = true;
1899 child->detectSignWidth(child_width_hint, child_sign_hint);
1900
1901 AstNode *rhs = wire_tmp_id->clone();
1902 rhs->children.push_back(new AstNode(AST_RANGE, AstNode::mkconst_int(cursor+child_width_hint-1, true), AstNode::mkconst_int(cursor, true)));
1903 newNode->children.push_back(new AstNode(type, child->clone(), rhs));
1904
1905 cursor += child_width_hint;
1906 }
1907
1908 goto apply_newNode;
1909 }
1910 }
1911
1912 // assignment with memory in left-hand side expression -> replace with memory write port
1913 if (stage > 1 && (type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE) && children[0]->type == AST_IDENTIFIER &&
1914 children[0]->id2ast && children[0]->id2ast->type == AST_MEMORY && children[0]->id2ast->children.size() >= 2 &&
1915 children[0]->id2ast->children[0]->range_valid && children[0]->id2ast->children[1]->range_valid &&
1916 (children[0]->children.size() == 1 || children[0]->children.size() == 2) && children[0]->children[0]->type == AST_RANGE)
1917 {
1918 std::stringstream sstr;
1919 sstr << "$memwr$" << children[0]->str << "$" << filename << ":" << location.first_line << "$" << (autoidx++);
1920 std::string id_addr = sstr.str() + "_ADDR", id_data = sstr.str() + "_DATA", id_en = sstr.str() + "_EN";
1921
1922 int mem_width, mem_size, addr_bits;
1923 bool mem_signed = children[0]->id2ast->is_signed;
1924 children[0]->id2ast->meminfo(mem_width, mem_size, addr_bits);
1925
1926 newNode = new AstNode(AST_BLOCK);
1927 AstNode *defNode = new AstNode(AST_BLOCK);
1928
1929 int data_range_left = children[0]->id2ast->children[0]->range_left;
1930 int data_range_right = children[0]->id2ast->children[0]->range_right;
1931 int mem_data_range_offset = std::min(data_range_left, data_range_right);
1932
1933 int addr_width_hint = -1;
1934 bool addr_sign_hint = true;
1935 children[0]->children[0]->children[0]->detectSignWidthWorker(addr_width_hint, addr_sign_hint);
1936 addr_bits = std::max(addr_bits, addr_width_hint);
1937
1938 std::vector<RTLIL::State> x_bits_addr, x_bits_data, set_bits_en;
1939 for (int i = 0; i < addr_bits; i++)
1940 x_bits_addr.push_back(RTLIL::State::Sx);
1941 for (int i = 0; i < mem_width; i++)
1942 x_bits_data.push_back(RTLIL::State::Sx);
1943 for (int i = 0; i < mem_width; i++)
1944 set_bits_en.push_back(RTLIL::State::S1);
1945
1946 AstNode *node_addr = nullptr;
1947 if (children[0]->children[0]->children[0]->isConst()) {
1948 node_addr = children[0]->children[0]->children[0]->clone();
1949 } else {
1950 AstNode *wire_addr = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(addr_bits-1, true), mkconst_int(0, true)));
1951 wire_addr->str = id_addr;
1952 wire_addr->was_checked = true;
1953 current_ast_mod->children.push_back(wire_addr);
1954 current_scope[wire_addr->str] = wire_addr;
1955 while (wire_addr->simplify(true, false, false, 1, -1, false, false)) { }
1956
1957 AstNode *assign_addr = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_bits(x_bits_addr, false));
1958 assign_addr->children[0]->str = id_addr;
1959 assign_addr->children[0]->was_checked = true;
1960 defNode->children.push_back(assign_addr);
1961
1962 assign_addr = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), children[0]->children[0]->children[0]->clone());
1963 assign_addr->children[0]->str = id_addr;
1964 assign_addr->children[0]->was_checked = true;
1965 newNode->children.push_back(assign_addr);
1966
1967 node_addr = new AstNode(AST_IDENTIFIER);
1968 node_addr->str = id_addr;
1969 }
1970
1971 AstNode *node_data = nullptr;
1972 if (children[0]->children.size() == 1 && children[1]->isConst()) {
1973 node_data = children[1]->clone();
1974 } else {
1975 AstNode *wire_data = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(mem_width-1, true), mkconst_int(0, true)));
1976 wire_data->str = id_data;
1977 wire_data->was_checked = true;
1978 wire_data->is_signed = mem_signed;
1979 current_ast_mod->children.push_back(wire_data);
1980 current_scope[wire_data->str] = wire_data;
1981 while (wire_data->simplify(true, false, false, 1, -1, false, false)) { }
1982
1983 AstNode *assign_data = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_bits(x_bits_data, false));
1984 assign_data->children[0]->str = id_data;
1985 assign_data->children[0]->was_checked = true;
1986 defNode->children.push_back(assign_data);
1987
1988 node_data = new AstNode(AST_IDENTIFIER);
1989 node_data->str = id_data;
1990 }
1991
1992 AstNode *node_en = nullptr;
1993 if (current_always->type == AST_INITIAL) {
1994 node_en = AstNode::mkconst_int(1, false);
1995 } else {
1996 AstNode *wire_en = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(mem_width-1, true), mkconst_int(0, true)));
1997 wire_en->str = id_en;
1998 wire_en->was_checked = true;
1999 current_ast_mod->children.push_back(wire_en);
2000 current_scope[wire_en->str] = wire_en;
2001 while (wire_en->simplify(true, false, false, 1, -1, false, false)) { }
2002
2003 AstNode *assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_int(0, false, mem_width));
2004 assign_en->children[0]->str = id_en;
2005 assign_en->children[0]->was_checked = true;
2006 defNode->children.push_back(assign_en);
2007
2008 node_en = new AstNode(AST_IDENTIFIER);
2009 node_en->str = id_en;
2010 }
2011
2012 if (!defNode->children.empty())
2013 current_top_block->children.insert(current_top_block->children.begin(), defNode);
2014 else
2015 delete defNode;
2016
2017 AstNode *assign_data = nullptr;
2018 AstNode *assign_en = nullptr;
2019 if (children[0]->children.size() == 2)
2020 {
2021 if (children[0]->children[1]->range_valid)
2022 {
2023 int offset = children[0]->children[1]->range_right;
2024 int width = children[0]->children[1]->range_left - offset + 1;
2025 offset -= mem_data_range_offset;
2026
2027 std::vector<RTLIL::State> padding_x(offset, RTLIL::State::Sx);
2028
2029 assign_data = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER),
2030 new AstNode(AST_CONCAT, mkconst_bits(padding_x, false), children[1]->clone()));
2031 assign_data->children[0]->str = id_data;
2032 assign_data->children[0]->was_checked = true;
2033
2034 if (current_always->type != AST_INITIAL) {
2035 for (int i = 0; i < mem_width; i++)
2036 set_bits_en[i] = offset <= i && i < offset+width ? RTLIL::State::S1 : RTLIL::State::S0;
2037 assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_bits(set_bits_en, false));
2038 assign_en->children[0]->str = id_en;
2039 assign_en->children[0]->was_checked = true;
2040 }
2041 }
2042 else
2043 {
2044 AstNode *the_range = children[0]->children[1];
2045 AstNode *left_at_zero_ast = the_range->children[0]->clone();
2046 AstNode *right_at_zero_ast = the_range->children.size() >= 2 ? the_range->children[1]->clone() : left_at_zero_ast->clone();
2047 AstNode *offset_ast = right_at_zero_ast->clone();
2048
2049 if (mem_data_range_offset)
2050 offset_ast = new AstNode(AST_SUB, offset_ast, mkconst_int(mem_data_range_offset, true));
2051
2052 while (left_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
2053 while (right_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
2054 if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
2055 log_file_error(filename, location.first_line, "Unsupported expression on dynamic range select on signal `%s'!\n", str.c_str());
2056 int width = abs(int(left_at_zero_ast->integer - right_at_zero_ast->integer)) + 1;
2057
2058 assign_data = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER),
2059 new AstNode(AST_SHIFT_LEFT, children[1]->clone(), offset_ast->clone()));
2060 assign_data->children[0]->str = id_data;
2061 assign_data->children[0]->was_checked = true;
2062
2063 if (current_always->type != AST_INITIAL) {
2064 for (int i = 0; i < mem_width; i++)
2065 set_bits_en[i] = i < width ? RTLIL::State::S1 : RTLIL::State::S0;
2066 assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER),
2067 new AstNode(AST_SHIFT_LEFT, mkconst_bits(set_bits_en, false), offset_ast->clone()));
2068 assign_en->children[0]->str = id_en;
2069 assign_en->children[0]->was_checked = true;
2070 }
2071
2072 delete left_at_zero_ast;
2073 delete right_at_zero_ast;
2074 delete offset_ast;
2075 }
2076 }
2077 else
2078 {
2079 if (!(children[0]->children.size() == 1 && children[1]->isConst())) {
2080 assign_data = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), children[1]->clone());
2081 assign_data->children[0]->str = id_data;
2082 assign_data->children[0]->was_checked = true;
2083 }
2084
2085 if (current_always->type != AST_INITIAL) {
2086 assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_bits(set_bits_en, false));
2087 assign_en->children[0]->str = id_en;
2088 assign_en->children[0]->was_checked = true;
2089 }
2090 }
2091 if (assign_data)
2092 newNode->children.push_back(assign_data);
2093 if (assign_en)
2094 newNode->children.push_back(assign_en);
2095
2096 AstNode *wrnode = new AstNode(current_always->type == AST_INITIAL ? AST_MEMINIT : AST_MEMWR, node_addr, node_data, node_en);
2097 wrnode->str = children[0]->str;
2098 wrnode->id2ast = children[0]->id2ast;
2099 current_ast_mod->children.push_back(wrnode);
2100
2101 if (newNode->children.empty()) {
2102 delete newNode;
2103 newNode = new AstNode();
2104 }
2105 goto apply_newNode;
2106 }
2107
2108 // replace function and task calls with the code from the function or task
2109 if ((type == AST_FCALL || type == AST_TCALL) && !str.empty())
2110 {
2111 if (type == AST_FCALL)
2112 {
2113 if (str == "\\$initstate")
2114 {
2115 int myidx = autoidx++;
2116
2117 AstNode *wire = new AstNode(AST_WIRE);
2118 wire->str = stringf("$initstate$%d_wire", myidx);
2119 current_ast_mod->children.push_back(wire);
2120 while (wire->simplify(true, false, false, 1, -1, false, false)) { }
2121
2122 AstNode *cell = new AstNode(AST_CELL, new AstNode(AST_CELLTYPE), new AstNode(AST_ARGUMENT, new AstNode(AST_IDENTIFIER)));
2123 cell->str = stringf("$initstate$%d", myidx);
2124 cell->children[0]->str = "$initstate";
2125 cell->children[1]->str = "\\Y";
2126 cell->children[1]->children[0]->str = wire->str;
2127 cell->children[1]->children[0]->id2ast = wire;
2128 current_ast_mod->children.push_back(cell);
2129 while (cell->simplify(true, false, false, 1, -1, false, false)) { }
2130
2131 newNode = new AstNode(AST_IDENTIFIER);
2132 newNode->str = wire->str;
2133 newNode->id2ast = wire;
2134 goto apply_newNode;
2135 }
2136
2137 if (str == "\\$past")
2138 {
2139 if (width_hint < 0)
2140 goto replace_fcall_later;
2141
2142 int num_steps = 1;
2143
2144 if (GetSize(children) != 1 && GetSize(children) != 2)
2145 log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 1 or 2.\n",
2146 RTLIL::unescape_id(str).c_str(), int(children.size()));
2147
2148 if (!current_always_clocked)
2149 log_file_error(filename, location.first_line, "System function %s is only allowed in clocked blocks.\n",
2150 RTLIL::unescape_id(str).c_str());
2151
2152 if (GetSize(children) == 2)
2153 {
2154 AstNode *buf = children[1]->clone();
2155 while (buf->simplify(true, false, false, stage, -1, false, false)) { }
2156 if (buf->type != AST_CONSTANT)
2157 log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant value.\n", str.c_str());
2158
2159 num_steps = buf->asInt(true);
2160 delete buf;
2161 }
2162
2163 AstNode *block = nullptr;
2164
2165 for (auto child : current_always->children)
2166 if (child->type == AST_BLOCK)
2167 block = child;
2168
2169 log_assert(block != nullptr);
2170
2171 if (num_steps == 0) {
2172 newNode = children[0]->clone();
2173 goto apply_newNode;
2174 }
2175
2176 int myidx = autoidx++;
2177 AstNode *outreg = nullptr;
2178
2179 for (int i = 0; i < num_steps; i++)
2180 {
2181 AstNode *reg = new AstNode(AST_WIRE, new AstNode(AST_RANGE,
2182 mkconst_int(width_hint-1, true), mkconst_int(0, true)));
2183
2184 reg->str = stringf("$past$%s:%d$%d$%d", filename.c_str(), location.first_line, myidx, i);
2185 reg->is_reg = true;
2186
2187 current_ast_mod->children.push_back(reg);
2188
2189 while (reg->simplify(true, false, false, 1, -1, false, false)) { }
2190
2191 AstNode *regid = new AstNode(AST_IDENTIFIER);
2192 regid->str = reg->str;
2193 regid->id2ast = reg;
2194 regid->was_checked = true;
2195
2196 AstNode *rhs = nullptr;
2197
2198 if (outreg == nullptr) {
2199 rhs = children.at(0)->clone();
2200 } else {
2201 rhs = new AstNode(AST_IDENTIFIER);
2202 rhs->str = outreg->str;
2203 rhs->id2ast = outreg;
2204 }
2205
2206 block->children.push_back(new AstNode(AST_ASSIGN_LE, regid, rhs));
2207 outreg = reg;
2208 }
2209
2210 newNode = new AstNode(AST_IDENTIFIER);
2211 newNode->str = outreg->str;
2212 newNode->id2ast = outreg;
2213 goto apply_newNode;
2214 }
2215
2216 if (str == "\\$stable" || str == "\\$rose" || str == "\\$fell" || str == "\\$changed")
2217 {
2218 if (GetSize(children) != 1)
2219 log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 1.\n",
2220 RTLIL::unescape_id(str).c_str(), int(children.size()));
2221
2222 if (!current_always_clocked)
2223 log_file_error(filename, location.first_line, "System function %s is only allowed in clocked blocks.\n",
2224 RTLIL::unescape_id(str).c_str());
2225
2226 AstNode *present = children.at(0)->clone();
2227 AstNode *past = clone();
2228 past->str = "\\$past";
2229
2230 if (str == "\\$stable")
2231 newNode = new AstNode(AST_EQ, past, present);
2232
2233 else if (str == "\\$changed")
2234 newNode = new AstNode(AST_NE, past, present);
2235
2236 else if (str == "\\$rose")
2237 newNode = new AstNode(AST_LOGIC_AND,
2238 new AstNode(AST_LOGIC_NOT, new AstNode(AST_BIT_AND, past, mkconst_int(1,false))),
2239 new AstNode(AST_BIT_AND, present, mkconst_int(1,false)));
2240
2241 else if (str == "\\$fell")
2242 newNode = new AstNode(AST_LOGIC_AND,
2243 new AstNode(AST_BIT_AND, past, mkconst_int(1,false)),
2244 new AstNode(AST_LOGIC_NOT, new AstNode(AST_BIT_AND, present, mkconst_int(1,false))));
2245
2246 else
2247 log_abort();
2248
2249 goto apply_newNode;
2250 }
2251
2252 // $anyconst and $anyseq are mapped in AstNode::genRTLIL()
2253 if (str == "\\$anyconst" || str == "\\$anyseq" || str == "\\$allconst" || str == "\\$allseq") {
2254 recursion_counter--;
2255 return false;
2256 }
2257
2258 if (str == "\\$clog2")
2259 {
2260 if (children.size() != 1)
2261 log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 1.\n",
2262 RTLIL::unescape_id(str).c_str(), int(children.size()));
2263
2264 AstNode *buf = children[0]->clone();
2265 while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2266 if (buf->type != AST_CONSTANT)
2267 log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant value.\n", str.c_str());
2268
2269 RTLIL::Const arg_value = buf->bitsAsConst();
2270 if (arg_value.as_bool())
2271 arg_value = const_sub(arg_value, 1, false, false, GetSize(arg_value));
2272 delete buf;
2273
2274 uint32_t result = 0;
2275 for (size_t i = 0; i < arg_value.bits.size(); i++)
2276 if (arg_value.bits.at(i) == RTLIL::State::S1)
2277 result = i + 1;
2278
2279 newNode = mkconst_int(result, true);
2280 goto apply_newNode;
2281 }
2282
2283 if (str == "\\$size" || str == "\\$bits")
2284 {
2285 if (str == "\\$bits" && children.size() != 1)
2286 log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 1.\n",
2287 RTLIL::unescape_id(str).c_str(), int(children.size()));
2288
2289 if (str == "\\$size" && children.size() != 1 && children.size() != 2)
2290 log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 1 or 2.\n",
2291 RTLIL::unescape_id(str).c_str(), int(children.size()));
2292
2293 int dim = 1;
2294 if (str == "\\$size" && children.size() == 2) {
2295 AstNode *buf = children[1]->clone();
2296 // Evaluate constant expression
2297 while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2298 dim = buf->asInt(false);
2299 delete buf;
2300 }
2301 AstNode *buf = children[0]->clone();
2302 int mem_depth = 1;
2303 AstNode *id_ast = NULL;
2304
2305 // Is this needed?
2306 //while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2307 buf->detectSignWidth(width_hint, sign_hint);
2308
2309 if (buf->type == AST_IDENTIFIER) {
2310 id_ast = buf->id2ast;
2311 if (id_ast == NULL && current_scope.count(buf->str))
2312 id_ast = current_scope.at(buf->str);
2313 if (!id_ast)
2314 log_file_error(filename, location.first_line, "Failed to resolve identifier %s for width detection!\n", buf->str.c_str());
2315 if (id_ast->type == AST_MEMORY) {
2316 // We got here only if the argument is a memory
2317 // Otherwise $size() and $bits() return the expression width
2318 AstNode *mem_range = id_ast->children[1];
2319 if (str == "\\$bits") {
2320 if (mem_range->type == AST_RANGE) {
2321 if (!mem_range->range_valid)
2322 log_file_error(filename, location.first_line, "Failed to detect width of memory access `%s'!\n", buf->str.c_str());
2323 mem_depth = mem_range->range_left - mem_range->range_right + 1;
2324 } else
2325 log_file_error(filename, location.first_line, "Unknown memory depth AST type in `%s'!\n", buf->str.c_str());
2326 } else {
2327 // $size()
2328 if (mem_range->type == AST_RANGE) {
2329 if (!mem_range->range_valid)
2330 log_file_error(filename, location.first_line, "Failed to detect width of memory access `%s'!\n", buf->str.c_str());
2331 int dims;
2332 if (id_ast->multirange_dimensions.empty())
2333 dims = 1;
2334 else
2335 dims = GetSize(id_ast->multirange_dimensions)/2;
2336 if (dim == 1)
2337 width_hint = (dims > 1) ? id_ast->multirange_dimensions[1] : (mem_range->range_left - mem_range->range_right + 1);
2338 else if (dim <= dims) {
2339 width_hint = id_ast->multirange_dimensions[2*dim-1];
2340 } else if ((dim > dims+1) || (dim < 0))
2341 log_file_error(filename, location.first_line, "Dimension %d out of range in `%s', as it only has dimensions 1..%d!\n", dim, buf->str.c_str(), dims+1);
2342 } else
2343 log_file_error(filename, location.first_line, "Unknown memory depth AST type in `%s'!\n", buf->str.c_str());
2344 }
2345 }
2346 }
2347 delete buf;
2348
2349 newNode = mkconst_int(width_hint * mem_depth, false);
2350 goto apply_newNode;
2351 }
2352
2353 if (str == "\\$ln" || str == "\\$log10" || str == "\\$exp" || str == "\\$sqrt" || str == "\\$pow" ||
2354 str == "\\$floor" || str == "\\$ceil" || str == "\\$sin" || str == "\\$cos" || str == "\\$tan" ||
2355 str == "\\$asin" || str == "\\$acos" || str == "\\$atan" || str == "\\$atan2" || str == "\\$hypot" ||
2356 str == "\\$sinh" || str == "\\$cosh" || str == "\\$tanh" || str == "\\$asinh" || str == "\\$acosh" || str == "\\$atanh" ||
2357 str == "\\$rtoi" || str == "\\$itor")
2358 {
2359 bool func_with_two_arguments = str == "\\$pow" || str == "\\$atan2" || str == "\\$hypot";
2360 double x = 0, y = 0;
2361
2362 if (func_with_two_arguments) {
2363 if (children.size() != 2)
2364 log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 2.\n",
2365 RTLIL::unescape_id(str).c_str(), int(children.size()));
2366 } else {
2367 if (children.size() != 1)
2368 log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 1.\n",
2369 RTLIL::unescape_id(str).c_str(), int(children.size()));
2370 }
2371
2372 if (children.size() >= 1) {
2373 while (children[0]->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2374 if (!children[0]->isConst())
2375 log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant argument.\n",
2376 RTLIL::unescape_id(str).c_str());
2377 int child_width_hint = width_hint;
2378 bool child_sign_hint = sign_hint;
2379 children[0]->detectSignWidth(child_width_hint, child_sign_hint);
2380 x = children[0]->asReal(child_sign_hint);
2381 }
2382
2383 if (children.size() >= 2) {
2384 while (children[1]->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2385 if (!children[1]->isConst())
2386 log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant argument.\n",
2387 RTLIL::unescape_id(str).c_str());
2388 int child_width_hint = width_hint;
2389 bool child_sign_hint = sign_hint;
2390 children[1]->detectSignWidth(child_width_hint, child_sign_hint);
2391 y = children[1]->asReal(child_sign_hint);
2392 }
2393
2394 if (str == "\\$rtoi") {
2395 newNode = AstNode::mkconst_int(x, true);
2396 } else {
2397 newNode = new AstNode(AST_REALVALUE);
2398 if (str == "\\$ln") newNode->realvalue = ::log(x);
2399 else if (str == "\\$log10") newNode->realvalue = ::log10(x);
2400 else if (str == "\\$exp") newNode->realvalue = ::exp(x);
2401 else if (str == "\\$sqrt") newNode->realvalue = ::sqrt(x);
2402 else if (str == "\\$pow") newNode->realvalue = ::pow(x, y);
2403 else if (str == "\\$floor") newNode->realvalue = ::floor(x);
2404 else if (str == "\\$ceil") newNode->realvalue = ::ceil(x);
2405 else if (str == "\\$sin") newNode->realvalue = ::sin(x);
2406 else if (str == "\\$cos") newNode->realvalue = ::cos(x);
2407 else if (str == "\\$tan") newNode->realvalue = ::tan(x);
2408 else if (str == "\\$asin") newNode->realvalue = ::asin(x);
2409 else if (str == "\\$acos") newNode->realvalue = ::acos(x);
2410 else if (str == "\\$atan") newNode->realvalue = ::atan(x);
2411 else if (str == "\\$atan2") newNode->realvalue = ::atan2(x, y);
2412 else if (str == "\\$hypot") newNode->realvalue = ::hypot(x, y);
2413 else if (str == "\\$sinh") newNode->realvalue = ::sinh(x);
2414 else if (str == "\\$cosh") newNode->realvalue = ::cosh(x);
2415 else if (str == "\\$tanh") newNode->realvalue = ::tanh(x);
2416 else if (str == "\\$asinh") newNode->realvalue = ::asinh(x);
2417 else if (str == "\\$acosh") newNode->realvalue = ::acosh(x);
2418 else if (str == "\\$atanh") newNode->realvalue = ::atanh(x);
2419 else if (str == "\\$itor") newNode->realvalue = x;
2420 else log_abort();
2421 }
2422 goto apply_newNode;
2423 }
2424
2425 if (str == "\\$sformatf") {
2426 AstNode *node_string = children[0];
2427 while (node_string->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2428 if (node_string->type != AST_CONSTANT)
2429 log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant 1st argument.\n", str.c_str());
2430 std::string sformat = node_string->bitsAsConst().decode_string();
2431 std::string sout = process_format_str(sformat, 1, stage, width_hint, sign_hint);
2432 newNode = AstNode::mkconst_str(sout);
2433 goto apply_newNode;
2434 }
2435
2436 if (current_scope.count(str) != 0 && current_scope[str]->type == AST_DPI_FUNCTION)
2437 {
2438 AstNode *dpi_decl = current_scope[str];
2439
2440 std::string rtype, fname;
2441 std::vector<std::string> argtypes;
2442 std::vector<AstNode*> args;
2443
2444 rtype = RTLIL::unescape_id(dpi_decl->children.at(0)->str);
2445 fname = RTLIL::unescape_id(dpi_decl->children.at(1)->str);
2446
2447 for (int i = 2; i < GetSize(dpi_decl->children); i++)
2448 {
2449 if (i-2 >= GetSize(children))
2450 log_file_error(filename, location.first_line, "Insufficient number of arguments in DPI function call.\n");
2451
2452 argtypes.push_back(RTLIL::unescape_id(dpi_decl->children.at(i)->str));
2453 args.push_back(children.at(i-2)->clone());
2454 while (args.back()->simplify(true, false, false, stage, -1, false, true)) { }
2455
2456 if (args.back()->type != AST_CONSTANT && args.back()->type != AST_REALVALUE)
2457 log_file_error(filename, location.first_line, "Failed to evaluate DPI function with non-constant argument.\n");
2458 }
2459
2460 newNode = dpi_call(rtype, fname, argtypes, args);
2461
2462 for (auto arg : args)
2463 delete arg;
2464
2465 goto apply_newNode;
2466 }
2467
2468 if (current_scope.count(str) == 0 || current_scope[str]->type != AST_FUNCTION)
2469 log_file_error(filename, location.first_line, "Can't resolve function name `%s'.\n", str.c_str());
2470 }
2471
2472 if (type == AST_TCALL)
2473 {
2474 if (str == "$finish" || str == "$stop")
2475 {
2476 if (!current_always || current_always->type != AST_INITIAL)
2477 log_file_error(filename, location.first_line, "System task `%s' outside initial block is unsupported.\n", str.c_str());
2478
2479 log_file_error(filename, location.first_line, "System task `%s' executed.\n", str.c_str());
2480 }
2481
2482 if (str == "\\$readmemh" || str == "\\$readmemb")
2483 {
2484 if (GetSize(children) < 2 || GetSize(children) > 4)
2485 log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 2-4.\n",
2486 RTLIL::unescape_id(str).c_str(), int(children.size()));
2487
2488 AstNode *node_filename = children[0]->clone();
2489 while (node_filename->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2490 if (node_filename->type != AST_CONSTANT)
2491 log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant 1st argument.\n", str.c_str());
2492
2493 AstNode *node_memory = children[1]->clone();
2494 while (node_memory->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2495 if (node_memory->type != AST_IDENTIFIER || node_memory->id2ast == nullptr || node_memory->id2ast->type != AST_MEMORY)
2496 log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-memory 2nd argument.\n", str.c_str());
2497
2498 int start_addr = -1, finish_addr = -1;
2499
2500 if (GetSize(children) > 2) {
2501 AstNode *node_addr = children[2]->clone();
2502 while (node_addr->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2503 if (node_addr->type != AST_CONSTANT)
2504 log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant 3rd argument.\n", str.c_str());
2505 start_addr = int(node_addr->asInt(false));
2506 }
2507
2508 if (GetSize(children) > 3) {
2509 AstNode *node_addr = children[3]->clone();
2510 while (node_addr->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2511 if (node_addr->type != AST_CONSTANT)
2512 log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant 4th argument.\n", str.c_str());
2513 finish_addr = int(node_addr->asInt(false));
2514 }
2515
2516 bool unconditional_init = false;
2517 if (current_always->type == AST_INITIAL) {
2518 pool<AstNode*> queue;
2519 log_assert(current_always->children[0]->type == AST_BLOCK);
2520 queue.insert(current_always->children[0]);
2521 while (!unconditional_init && !queue.empty()) {
2522 pool<AstNode*> next_queue;
2523 for (auto n : queue)
2524 for (auto c : n->children) {
2525 if (c == this)
2526 unconditional_init = true;
2527 next_queue.insert(c);
2528 }
2529 next_queue.swap(queue);
2530 }
2531 }
2532
2533 newNode = readmem(str == "\\$readmemh", node_filename->bitsAsConst().decode_string(), node_memory->id2ast, start_addr, finish_addr, unconditional_init);
2534 delete node_filename;
2535 delete node_memory;
2536 goto apply_newNode;
2537 }
2538
2539 if (current_scope.count(str) == 0 || current_scope[str]->type != AST_TASK)
2540 log_file_error(filename, location.first_line, "Can't resolve task name `%s'.\n", str.c_str());
2541 }
2542
2543 AstNode *decl = current_scope[str];
2544
2545 std::stringstream sstr;
2546 sstr << "$func$" << str << "$" << filename << ":" << location.first_line << "$" << (autoidx++) << "$";
2547 std::string prefix = sstr.str();
2548
2549 bool recommend_const_eval = false;
2550 bool require_const_eval = in_param ? false : has_const_only_constructs(recommend_const_eval);
2551 if ((in_param || recommend_const_eval || require_const_eval) && !decl->attributes.count("\\via_celltype"))
2552 {
2553 bool all_args_const = true;
2554 for (auto child : children) {
2555 while (child->simplify(true, false, false, 1, -1, false, true)) { }
2556 if (child->type != AST_CONSTANT)
2557 all_args_const = false;
2558 }
2559
2560 if (all_args_const) {
2561 AstNode *func_workspace = current_scope[str]->clone();
2562 newNode = func_workspace->eval_const_function(this);
2563 delete func_workspace;
2564 goto apply_newNode;
2565 }
2566
2567 if (in_param)
2568 log_file_error(filename, location.first_line, "Non-constant function call in constant expression.\n");
2569 if (require_const_eval)
2570 log_file_error(filename, location.first_line, "Function %s can only be called with constant arguments.\n", str.c_str());
2571 }
2572
2573 size_t arg_count = 0;
2574 std::map<std::string, std::string> replace_rules;
2575 vector<AstNode*> added_mod_children;
2576 dict<std::string, AstNode*> wire_cache;
2577 vector<AstNode*> new_stmts;
2578 vector<AstNode*> output_assignments;
2579
2580 if (current_block == NULL)
2581 {
2582 log_assert(type == AST_FCALL);
2583
2584 AstNode *wire = NULL;
2585 for (auto child : decl->children)
2586 if (child->type == AST_WIRE && child->str == str)
2587 wire = child->clone();
2588 log_assert(wire != NULL);
2589
2590 wire->str = prefix + str;
2591 wire->port_id = 0;
2592 wire->is_input = false;
2593 wire->is_output = false;
2594
2595 current_ast_mod->children.push_back(wire);
2596 while (wire->simplify(true, false, false, 1, -1, false, false)) { }
2597
2598 AstNode *lvalue = new AstNode(AST_IDENTIFIER);
2599 lvalue->str = wire->str;
2600
2601 AstNode *always = new AstNode(AST_ALWAYS, new AstNode(AST_BLOCK,
2602 new AstNode(AST_ASSIGN_EQ, lvalue, clone())));
2603 always->children[0]->children[0]->was_checked = true;
2604
2605 current_ast_mod->children.push_back(always);
2606
2607 goto replace_fcall_with_id;
2608 }
2609
2610 if (decl->attributes.count("\\via_celltype"))
2611 {
2612 std::string celltype = decl->attributes.at("\\via_celltype")->asAttrConst().decode_string();
2613 std::string outport = str;
2614
2615 if (celltype.find(' ') != std::string::npos) {
2616 int pos = celltype.find(' ');
2617 outport = RTLIL::escape_id(celltype.substr(pos+1));
2618 celltype = RTLIL::escape_id(celltype.substr(0, pos));
2619 } else
2620 celltype = RTLIL::escape_id(celltype);
2621
2622 AstNode *cell = new AstNode(AST_CELL, new AstNode(AST_CELLTYPE));
2623 cell->str = prefix.substr(0, GetSize(prefix)-1);
2624 cell->children[0]->str = celltype;
2625
2626 for (auto attr : decl->attributes)
2627 if (attr.first.str().rfind("\\via_celltype_defparam_", 0) == 0)
2628 {
2629 AstNode *cell_arg = new AstNode(AST_PARASET, attr.second->clone());
2630 cell_arg->str = RTLIL::escape_id(attr.first.substr(strlen("\\via_celltype_defparam_")));
2631 cell->children.push_back(cell_arg);
2632 }
2633
2634 for (auto child : decl->children)
2635 if (child->type == AST_WIRE && (child->is_input || child->is_output || (type == AST_FCALL && child->str == str)))
2636 {
2637 AstNode *wire = child->clone();
2638 wire->str = prefix + wire->str;
2639 wire->port_id = 0;
2640 wire->is_input = false;
2641 wire->is_output = false;
2642 current_ast_mod->children.push_back(wire);
2643 while (wire->simplify(true, false, false, 1, -1, false, false)) { }
2644
2645 AstNode *wire_id = new AstNode(AST_IDENTIFIER);
2646 wire_id->str = wire->str;
2647
2648 if ((child->is_input || child->is_output) && arg_count < children.size())
2649 {
2650 AstNode *arg = children[arg_count++]->clone();
2651 AstNode *assign = child->is_input ?
2652 new AstNode(AST_ASSIGN_EQ, wire_id->clone(), arg) :
2653 new AstNode(AST_ASSIGN_EQ, arg, wire_id->clone());
2654 assign->children[0]->was_checked = true;
2655
2656 for (auto it = current_block->children.begin(); it != current_block->children.end(); it++) {
2657 if (*it != current_block_child)
2658 continue;
2659 current_block->children.insert(it, assign);
2660 break;
2661 }
2662 }
2663
2664 AstNode *cell_arg = new AstNode(AST_ARGUMENT, wire_id);
2665 cell_arg->str = child->str == str ? outport : child->str;
2666 cell->children.push_back(cell_arg);
2667 }
2668
2669 current_ast_mod->children.push_back(cell);
2670 goto replace_fcall_with_id;
2671 }
2672
2673 for (auto child : decl->children)
2674 if (child->type == AST_WIRE || child->type == AST_MEMORY || child->type == AST_PARAMETER || child->type == AST_LOCALPARAM || child->type == AST_ENUM_ITEM)
2675 {
2676 AstNode *wire = nullptr;
2677
2678 if (wire_cache.count(child->str))
2679 {
2680 wire = wire_cache.at(child->str);
2681 if (wire->children.empty()) {
2682 for (auto c : child->children)
2683 wire->children.push_back(c->clone());
2684 } else if (!child->children.empty()) {
2685 while (child->simplify(true, false, false, stage, -1, false, false)) { }
2686 if (GetSize(child->children) == GetSize(wire->children)) {
2687 for (int i = 0; i < GetSize(child->children); i++)
2688 if (*child->children.at(i) != *wire->children.at(i))
2689 goto tcall_incompatible_wires;
2690 } else {
2691 tcall_incompatible_wires:
2692 log_file_error(filename, location.first_line, "Incompatible re-declaration of wire %s.\n", child->str.c_str());
2693 }
2694 }
2695 }
2696 else
2697 {
2698 wire = child->clone();
2699 wire->str = prefix + wire->str;
2700 wire->port_id = 0;
2701 wire->is_input = false;
2702 wire->is_output = false;
2703 wire->is_reg = true;
2704 wire->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
2705 if (child->type == AST_ENUM_ITEM)
2706 wire->attributes["\\enum_base_type"] = child->attributes["\\enum_base_type"];
2707
2708 wire_cache[child->str] = wire;
2709
2710 current_ast_mod->children.push_back(wire);
2711 added_mod_children.push_back(wire);
2712 }
2713
2714 if (child->type == AST_WIRE)
2715 while (wire->simplify(true, false, false, 1, -1, false, false)) { }
2716
2717 replace_rules[child->str] = wire->str;
2718 current_scope[wire->str] = wire;
2719
2720 if ((child->is_input || child->is_output) && arg_count < children.size())
2721 {
2722 AstNode *arg = children[arg_count++]->clone();
2723 AstNode *wire_id = new AstNode(AST_IDENTIFIER);
2724 wire_id->str = wire->str;
2725 AstNode *assign = child->is_input ?
2726 new AstNode(AST_ASSIGN_EQ, wire_id, arg) :
2727 new AstNode(AST_ASSIGN_EQ, arg, wire_id);
2728 assign->children[0]->was_checked = true;
2729 if (child->is_input)
2730 new_stmts.push_back(assign);
2731 else
2732 output_assignments.push_back(assign);
2733 }
2734 }
2735
2736 for (auto child : added_mod_children) {
2737 child->replace_ids(prefix, replace_rules);
2738 while (child->simplify(true, false, false, 1, -1, false, false)) { }
2739 }
2740
2741 for (auto child : decl->children)
2742 if (child->type != AST_WIRE && child->type != AST_MEMORY && child->type != AST_PARAMETER && child->type != AST_LOCALPARAM)
2743 {
2744 AstNode *stmt = child->clone();
2745 stmt->replace_ids(prefix, replace_rules);
2746 new_stmts.push_back(stmt);
2747 }
2748
2749 new_stmts.insert(new_stmts.end(), output_assignments.begin(), output_assignments.end());
2750
2751 for (auto it = current_block->children.begin(); ; it++) {
2752 log_assert(it != current_block->children.end());
2753 if (*it == current_block_child) {
2754 current_block->children.insert(it, new_stmts.begin(), new_stmts.end());
2755 break;
2756 }
2757 }
2758
2759 replace_fcall_with_id:
2760 if (type == AST_FCALL) {
2761 delete_children();
2762 type = AST_IDENTIFIER;
2763 str = prefix + str;
2764 }
2765 if (type == AST_TCALL)
2766 str = "";
2767 did_something = true;
2768 }
2769
2770 replace_fcall_later:;
2771
2772 // perform const folding when activated
2773 if (const_fold)
2774 {
2775 bool string_op;
2776 std::vector<RTLIL::State> tmp_bits;
2777 RTLIL::Const (*const_func)(const RTLIL::Const&, const RTLIL::Const&, bool, bool, int);
2778 RTLIL::Const dummy_arg;
2779
2780 switch (type)
2781 {
2782 case AST_IDENTIFIER:
2783 if (current_scope.count(str) > 0 && (current_scope[str]->type == AST_PARAMETER || current_scope[str]->type == AST_LOCALPARAM || current_scope[str]->type == AST_ENUM_ITEM)) {
2784 if (current_scope[str]->children[0]->type == AST_CONSTANT) {
2785 if (children.size() != 0 && children[0]->type == AST_RANGE && children[0]->range_valid) {
2786 std::vector<RTLIL::State> data;
2787 bool param_upto = current_scope[str]->range_valid && current_scope[str]->range_swapped;
2788 int param_offset = current_scope[str]->range_valid ? current_scope[str]->range_right : 0;
2789 int param_width = current_scope[str]->range_valid ? current_scope[str]->range_left - current_scope[str]->range_right + 1 :
2790 GetSize(current_scope[str]->children[0]->bits);
2791 int tmp_range_left = children[0]->range_left, tmp_range_right = children[0]->range_right;
2792 if (param_upto) {
2793 tmp_range_left = (param_width + 2*param_offset) - children[0]->range_right - 1;
2794 tmp_range_right = (param_width + 2*param_offset) - children[0]->range_left - 1;
2795 }
2796 for (int i = tmp_range_right; i <= tmp_range_left; i++) {
2797 int index = i - param_offset;
2798 if (0 <= index && index < param_width)
2799 data.push_back(current_scope[str]->children[0]->bits[index]);
2800 else
2801 data.push_back(RTLIL::State::Sx);
2802 }
2803 newNode = mkconst_bits(data, false);
2804 } else
2805 if (children.size() == 0)
2806 newNode = current_scope[str]->children[0]->clone();
2807 } else
2808 if (current_scope[str]->children[0]->isConst())
2809 newNode = current_scope[str]->children[0]->clone();
2810 }
2811 else if (at_zero && current_scope.count(str) > 0 && (current_scope[str]->type == AST_WIRE || current_scope[str]->type == AST_AUTOWIRE)) {
2812 newNode = mkconst_int(0, sign_hint, width_hint);
2813 }
2814 break;
2815 case AST_BIT_NOT:
2816 if (children[0]->type == AST_CONSTANT) {
2817 RTLIL::Const y = RTLIL::const_not(children[0]->bitsAsConst(width_hint, sign_hint), dummy_arg, sign_hint, false, width_hint);
2818 newNode = mkconst_bits(y.bits, sign_hint);
2819 }
2820 break;
2821 case AST_TO_SIGNED:
2822 case AST_TO_UNSIGNED:
2823 if (children[0]->type == AST_CONSTANT) {
2824 RTLIL::Const y = children[0]->bitsAsConst(width_hint, sign_hint);
2825 newNode = mkconst_bits(y.bits, type == AST_TO_SIGNED);
2826 }
2827 break;
2828 if (0) { case AST_BIT_AND: const_func = RTLIL::const_and; }
2829 if (0) { case AST_BIT_OR: const_func = RTLIL::const_or; }
2830 if (0) { case AST_BIT_XOR: const_func = RTLIL::const_xor; }
2831 if (0) { case AST_BIT_XNOR: const_func = RTLIL::const_xnor; }
2832 if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
2833 RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint),
2834 children[1]->bitsAsConst(width_hint, sign_hint), sign_hint, sign_hint, width_hint);
2835 newNode = mkconst_bits(y.bits, sign_hint);
2836 }
2837 break;
2838 if (0) { case AST_REDUCE_AND: const_func = RTLIL::const_reduce_and; }
2839 if (0) { case AST_REDUCE_OR: const_func = RTLIL::const_reduce_or; }
2840 if (0) { case AST_REDUCE_XOR: const_func = RTLIL::const_reduce_xor; }
2841 if (0) { case AST_REDUCE_XNOR: const_func = RTLIL::const_reduce_xnor; }
2842 if (0) { case AST_REDUCE_BOOL: const_func = RTLIL::const_reduce_bool; }
2843 if (children[0]->type == AST_CONSTANT) {
2844 RTLIL::Const y = const_func(RTLIL::Const(children[0]->bits), dummy_arg, false, false, -1);
2845 newNode = mkconst_bits(y.bits, false);
2846 }
2847 break;
2848 case AST_LOGIC_NOT:
2849 if (children[0]->type == AST_CONSTANT) {
2850 RTLIL::Const y = RTLIL::const_logic_not(RTLIL::Const(children[0]->bits), dummy_arg, children[0]->is_signed, false, -1);
2851 newNode = mkconst_bits(y.bits, false);
2852 } else
2853 if (children[0]->isConst()) {
2854 newNode = mkconst_int(children[0]->asReal(sign_hint) == 0, false, 1);
2855 }
2856 break;
2857 if (0) { case AST_LOGIC_AND: const_func = RTLIL::const_logic_and; }
2858 if (0) { case AST_LOGIC_OR: const_func = RTLIL::const_logic_or; }
2859 if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
2860 RTLIL::Const y = const_func(RTLIL::Const(children[0]->bits), RTLIL::Const(children[1]->bits),
2861 children[0]->is_signed, children[1]->is_signed, -1);
2862 newNode = mkconst_bits(y.bits, false);
2863 } else
2864 if (children[0]->isConst() && children[1]->isConst()) {
2865 if (type == AST_LOGIC_AND)
2866 newNode = mkconst_int((children[0]->asReal(sign_hint) != 0) && (children[1]->asReal(sign_hint) != 0), false, 1);
2867 else
2868 newNode = mkconst_int((children[0]->asReal(sign_hint) != 0) || (children[1]->asReal(sign_hint) != 0), false, 1);
2869 }
2870 break;
2871 if (0) { case AST_SHIFT_LEFT: const_func = RTLIL::const_shl; }
2872 if (0) { case AST_SHIFT_RIGHT: const_func = RTLIL::const_shr; }
2873 if (0) { case AST_SHIFT_SLEFT: const_func = RTLIL::const_sshl; }
2874 if (0) { case AST_SHIFT_SRIGHT: const_func = RTLIL::const_sshr; }
2875 if (0) { case AST_POW: const_func = RTLIL::const_pow; }
2876 if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
2877 RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint),
2878 RTLIL::Const(children[1]->bits), sign_hint, type == AST_POW ? children[1]->is_signed : false, width_hint);
2879 newNode = mkconst_bits(y.bits, sign_hint);
2880 } else
2881 if (type == AST_POW && children[0]->isConst() && children[1]->isConst()) {
2882 newNode = new AstNode(AST_REALVALUE);
2883 newNode->realvalue = pow(children[0]->asReal(sign_hint), children[1]->asReal(sign_hint));
2884 }
2885 break;
2886 if (0) { case AST_LT: const_func = RTLIL::const_lt; }
2887 if (0) { case AST_LE: const_func = RTLIL::const_le; }
2888 if (0) { case AST_EQ: const_func = RTLIL::const_eq; }
2889 if (0) { case AST_NE: const_func = RTLIL::const_ne; }
2890 if (0) { case AST_EQX: const_func = RTLIL::const_eqx; }
2891 if (0) { case AST_NEX: const_func = RTLIL::const_nex; }
2892 if (0) { case AST_GE: const_func = RTLIL::const_ge; }
2893 if (0) { case AST_GT: const_func = RTLIL::const_gt; }
2894 if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
2895 int cmp_width = max(children[0]->bits.size(), children[1]->bits.size());
2896 bool cmp_signed = children[0]->is_signed && children[1]->is_signed;
2897 RTLIL::Const y = const_func(children[0]->bitsAsConst(cmp_width, cmp_signed),
2898 children[1]->bitsAsConst(cmp_width, cmp_signed), cmp_signed, cmp_signed, 1);
2899 newNode = mkconst_bits(y.bits, false);
2900 } else
2901 if (children[0]->isConst() && children[1]->isConst()) {
2902 bool cmp_signed = (children[0]->type == AST_REALVALUE || children[0]->is_signed) && (children[1]->type == AST_REALVALUE || children[1]->is_signed);
2903 switch (type) {
2904 case AST_LT: newNode = mkconst_int(children[0]->asReal(cmp_signed) < children[1]->asReal(cmp_signed), false, 1); break;
2905 case AST_LE: newNode = mkconst_int(children[0]->asReal(cmp_signed) <= children[1]->asReal(cmp_signed), false, 1); break;
2906 case AST_EQ: newNode = mkconst_int(children[0]->asReal(cmp_signed) == children[1]->asReal(cmp_signed), false, 1); break;
2907 case AST_NE: newNode = mkconst_int(children[0]->asReal(cmp_signed) != children[1]->asReal(cmp_signed), false, 1); break;
2908 case AST_EQX: newNode = mkconst_int(children[0]->asReal(cmp_signed) == children[1]->asReal(cmp_signed), false, 1); break;
2909 case AST_NEX: newNode = mkconst_int(children[0]->asReal(cmp_signed) != children[1]->asReal(cmp_signed), false, 1); break;
2910 case AST_GE: newNode = mkconst_int(children[0]->asReal(cmp_signed) >= children[1]->asReal(cmp_signed), false, 1); break;
2911 case AST_GT: newNode = mkconst_int(children[0]->asReal(cmp_signed) > children[1]->asReal(cmp_signed), false, 1); break;
2912 default: log_abort();
2913 }
2914 }
2915 break;
2916 if (0) { case AST_ADD: const_func = RTLIL::const_add; }
2917 if (0) { case AST_SUB: const_func = RTLIL::const_sub; }
2918 if (0) { case AST_MUL: const_func = RTLIL::const_mul; }
2919 if (0) { case AST_DIV: const_func = RTLIL::const_div; }
2920 if (0) { case AST_MOD: const_func = RTLIL::const_mod; }
2921 if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
2922 RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint),
2923 children[1]->bitsAsConst(width_hint, sign_hint), sign_hint, sign_hint, width_hint);
2924 newNode = mkconst_bits(y.bits, sign_hint);
2925 } else
2926 if (children[0]->isConst() && children[1]->isConst()) {
2927 newNode = new AstNode(AST_REALVALUE);
2928 switch (type) {
2929 case AST_ADD: newNode->realvalue = children[0]->asReal(sign_hint) + children[1]->asReal(sign_hint); break;
2930 case AST_SUB: newNode->realvalue = children[0]->asReal(sign_hint) - children[1]->asReal(sign_hint); break;
2931 case AST_MUL: newNode->realvalue = children[0]->asReal(sign_hint) * children[1]->asReal(sign_hint); break;
2932 case AST_DIV: newNode->realvalue = children[0]->asReal(sign_hint) / children[1]->asReal(sign_hint); break;
2933 case AST_MOD: newNode->realvalue = fmod(children[0]->asReal(sign_hint), children[1]->asReal(sign_hint)); break;
2934 default: log_abort();
2935 }
2936 }
2937 break;
2938 if (0) { case AST_POS: const_func = RTLIL::const_pos; }
2939 if (0) { case AST_NEG: const_func = RTLIL::const_neg; }
2940 if (children[0]->type == AST_CONSTANT) {
2941 RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint), dummy_arg, sign_hint, false, width_hint);
2942 newNode = mkconst_bits(y.bits, sign_hint);
2943 } else
2944 if (children[0]->isConst()) {
2945 newNode = new AstNode(AST_REALVALUE);
2946 if (type == AST_POS)
2947 newNode->realvalue = +children[0]->asReal(sign_hint);
2948 else
2949 newNode->realvalue = -children[0]->asReal(sign_hint);
2950 }
2951 break;
2952 case AST_TERNARY:
2953 if (children[0]->isConst())
2954 {
2955 bool found_sure_true = false;
2956 bool found_maybe_true = false;
2957
2958 if (children[0]->type == AST_CONSTANT)
2959 for (auto &bit : children[0]->bits) {
2960 if (bit == RTLIL::State::S1)
2961 found_sure_true = true;
2962 if (bit > RTLIL::State::S1)
2963 found_maybe_true = true;
2964 }
2965 else
2966 found_sure_true = children[0]->asReal(sign_hint) != 0;
2967
2968 AstNode *choice = NULL, *not_choice = NULL;
2969 if (found_sure_true)
2970 choice = children[1], not_choice = children[2];
2971 else if (!found_maybe_true)
2972 choice = children[2], not_choice = children[1];
2973
2974 if (choice != NULL) {
2975 if (choice->type == AST_CONSTANT) {
2976 int other_width_hint = width_hint;
2977 bool other_sign_hint = sign_hint, other_real = false;
2978 not_choice->detectSignWidth(other_width_hint, other_sign_hint, &other_real);
2979 if (other_real) {
2980 newNode = new AstNode(AST_REALVALUE);
2981 choice->detectSignWidth(width_hint, sign_hint);
2982 newNode->realvalue = choice->asReal(sign_hint);
2983 } else {
2984 RTLIL::Const y = choice->bitsAsConst(width_hint, sign_hint);
2985 if (choice->is_string && y.bits.size() % 8 == 0 && sign_hint == false)
2986 newNode = mkconst_str(y.bits);
2987 else
2988 newNode = mkconst_bits(y.bits, sign_hint);
2989 }
2990 } else
2991 if (choice->isConst()) {
2992 newNode = choice->clone();
2993 }
2994 } else if (children[1]->type == AST_CONSTANT && children[2]->type == AST_CONSTANT) {
2995 RTLIL::Const a = children[1]->bitsAsConst(width_hint, sign_hint);
2996 RTLIL::Const b = children[2]->bitsAsConst(width_hint, sign_hint);
2997 log_assert(a.bits.size() == b.bits.size());
2998 for (size_t i = 0; i < a.bits.size(); i++)
2999 if (a.bits[i] != b.bits[i])
3000 a.bits[i] = RTLIL::State::Sx;
3001 newNode = mkconst_bits(a.bits, sign_hint);
3002 } else if (children[1]->isConst() && children[2]->isConst()) {
3003 newNode = new AstNode(AST_REALVALUE);
3004 if (children[1]->asReal(sign_hint) == children[2]->asReal(sign_hint))
3005 newNode->realvalue = children[1]->asReal(sign_hint);
3006 else
3007 // IEEE Std 1800-2012 Sec. 11.4.11 states that the entry in Table 7-1 for
3008 // the data type in question should be returned if the ?: is ambiguous. The
3009 // value in Table 7-1 for the 'real' type is 0.0.
3010 newNode->realvalue = 0.0;
3011 }
3012 }
3013 break;
3014 case AST_CONCAT:
3015 string_op = !children.empty();
3016 for (auto it = children.begin(); it != children.end(); it++) {
3017 if ((*it)->type != AST_CONSTANT)
3018 goto not_const;
3019 if (!(*it)->is_string)
3020 string_op = false;
3021 tmp_bits.insert(tmp_bits.end(), (*it)->bits.begin(), (*it)->bits.end());
3022 }
3023 newNode = string_op ? mkconst_str(tmp_bits) : mkconst_bits(tmp_bits, false);
3024 break;
3025 case AST_REPLICATE:
3026 if (children.at(0)->type != AST_CONSTANT || children.at(1)->type != AST_CONSTANT)
3027 goto not_const;
3028 for (int i = 0; i < children[0]->bitsAsConst().as_int(); i++)
3029 tmp_bits.insert(tmp_bits.end(), children.at(1)->bits.begin(), children.at(1)->bits.end());
3030 newNode = children.at(1)->is_string ? mkconst_str(tmp_bits) : mkconst_bits(tmp_bits, false);
3031 break;
3032 default:
3033 not_const:
3034 break;
3035 }
3036 }
3037
3038 // if any of the above set 'newNode' -> use 'newNode' as template to update 'this'
3039 if (newNode) {
3040 apply_newNode:
3041 // fprintf(stderr, "----\n");
3042 // dumpAst(stderr, "- ");
3043 // newNode->dumpAst(stderr, "+ ");
3044 log_assert(newNode != NULL);
3045 newNode->filename = filename;
3046 newNode->location = location;
3047 newNode->cloneInto(this);
3048 delete newNode;
3049 did_something = true;
3050 }
3051
3052 if (!did_something)
3053 basic_prep = true;
3054
3055 recursion_counter--;
3056 return did_something;
3057 }
3058
3059 static void replace_result_wire_name_in_function(AstNode *node, std::string &from, std::string &to)
3060 {
3061 for (auto &it : node->children)
3062 replace_result_wire_name_in_function(it, from, to);
3063 if (node->str == from)
3064 node->str = to;
3065 }
3066
3067 // replace a readmem[bh] TCALL ast node with a block of memory assignments
3068 AstNode *AstNode::readmem(bool is_readmemh, std::string mem_filename, AstNode *memory, int start_addr, int finish_addr, bool unconditional_init)
3069 {
3070 int mem_width, mem_size, addr_bits;
3071 memory->meminfo(mem_width, mem_size, addr_bits);
3072
3073 AstNode *block = new AstNode(AST_BLOCK);
3074
3075 AstNode *meminit = nullptr;
3076 int next_meminit_cursor=0;
3077 vector<State> meminit_bits;
3078 int meminit_size=0;
3079
3080 std::ifstream f;
3081 f.open(mem_filename.c_str());
3082 if (f.fail()) {
3083 #ifdef _WIN32
3084 char slash = '\\';
3085 #else
3086 char slash = '/';
3087 #endif
3088 std::string path = filename.substr(0, filename.find_last_of(slash)+1);
3089 f.open(path + mem_filename.c_str());
3090 yosys_input_files.insert(path + mem_filename);
3091 } else {
3092 yosys_input_files.insert(mem_filename);
3093 }
3094 if (f.fail() || GetSize(mem_filename) == 0)
3095 log_file_error(filename, location.first_line, "Can not open file `%s` for %s.\n", mem_filename.c_str(), str.c_str());
3096
3097 log_assert(GetSize(memory->children) == 2 && memory->children[1]->type == AST_RANGE && memory->children[1]->range_valid);
3098 int range_left = memory->children[1]->range_left, range_right = memory->children[1]->range_right;
3099 int range_min = min(range_left, range_right), range_max = max(range_left, range_right);
3100
3101 if (start_addr < 0)
3102 start_addr = range_min;
3103
3104 if (finish_addr < 0)
3105 finish_addr = range_max + 1;
3106
3107 bool in_comment = false;
3108 int increment = start_addr <= finish_addr ? +1 : -1;
3109 int cursor = start_addr;
3110
3111 while (!f.eof())
3112 {
3113 std::string line, token;
3114 std::getline(f, line);
3115
3116 for (int i = 0; i < GetSize(line); i++) {
3117 if (in_comment && line.compare(i, 2, "*/") == 0) {
3118 line[i] = ' ';
3119 line[i+1] = ' ';
3120 in_comment = false;
3121 continue;
3122 }
3123 if (!in_comment && line.compare(i, 2, "/*") == 0)
3124 in_comment = true;
3125 if (in_comment)
3126 line[i] = ' ';
3127 }
3128
3129 while (1)
3130 {
3131 token = next_token(line, " \t\r\n");
3132 if (token.empty() || token.compare(0, 2, "//") == 0)
3133 break;
3134
3135 if (token[0] == '@') {
3136 token = token.substr(1);
3137 const char *nptr = token.c_str();
3138 char *endptr;
3139 cursor = strtol(nptr, &endptr, 16);
3140 if (!*nptr || *endptr)
3141 log_file_error(filename, location.first_line, "Can not parse address `%s` for %s.\n", nptr, str.c_str());
3142 continue;
3143 }
3144
3145 AstNode *value = VERILOG_FRONTEND::const2ast(stringf("%d'%c", mem_width, is_readmemh ? 'h' : 'b') + token);
3146
3147 if (unconditional_init)
3148 {
3149 if (meminit == nullptr || cursor != next_meminit_cursor)
3150 {
3151 if (meminit != nullptr) {
3152 meminit->children[1] = AstNode::mkconst_bits(meminit_bits, false);
3153 meminit->children[2] = AstNode::mkconst_int(meminit_size, false);
3154 }
3155
3156 meminit = new AstNode(AST_MEMINIT);
3157 meminit->children.push_back(AstNode::mkconst_int(cursor, false));
3158 meminit->children.push_back(nullptr);
3159 meminit->children.push_back(nullptr);
3160 meminit->str = memory->str;
3161 meminit->id2ast = memory;
3162 meminit_bits.clear();
3163 meminit_size = 0;
3164
3165 current_ast_mod->children.push_back(meminit);
3166 next_meminit_cursor = cursor;
3167 }
3168
3169 meminit_size++;
3170 next_meminit_cursor++;
3171 meminit_bits.insert(meminit_bits.end(), value->bits.begin(), value->bits.end());
3172 delete value;
3173 }
3174 else
3175 {
3176 block->children.push_back(new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER, new AstNode(AST_RANGE, AstNode::mkconst_int(cursor, false))), value));
3177 block->children.back()->children[0]->str = memory->str;
3178 block->children.back()->children[0]->id2ast = memory;
3179 block->children.back()->children[0]->was_checked = true;
3180 }
3181
3182 cursor += increment;
3183 if ((cursor == finish_addr+increment) || (increment > 0 && cursor > range_max) || (increment < 0 && cursor < range_min))
3184 break;
3185 }
3186
3187 if ((cursor == finish_addr+increment) || (increment > 0 && cursor > range_max) || (increment < 0 && cursor < range_min))
3188 break;
3189 }
3190
3191 if (meminit != nullptr) {
3192 meminit->children[1] = AstNode::mkconst_bits(meminit_bits, false);
3193 meminit->children[2] = AstNode::mkconst_int(meminit_size, false);
3194 }
3195
3196 return block;
3197 }
3198
3199 // annotate the names of all wires and other named objects in a generate block
3200 void AstNode::expand_genblock(std::string index_var, std::string prefix, std::map<std::string, std::string> &name_map)
3201 {
3202 if (!index_var.empty() && type == AST_IDENTIFIER && str == index_var) {
3203 if (children.empty()) {
3204 current_scope[index_var]->children[0]->cloneInto(this);
3205 } else {
3206 AstNode *p = new AstNode(AST_LOCALPARAM, current_scope[index_var]->children[0]->clone());
3207 p->str = stringf("$genval$%d", autoidx++);
3208 current_ast_mod->children.push_back(p);
3209 str = p->str;
3210 id2ast = p;
3211 }
3212 }
3213
3214 if ((type == AST_IDENTIFIER || type == AST_FCALL || type == AST_TCALL || type == AST_WIRETYPE) && name_map.count(str) > 0)
3215 str = name_map[str];
3216
3217 std::map<std::string, std::string> backup_name_map;
3218
3219 for (size_t i = 0; i < children.size(); i++) {
3220 AstNode *child = children[i];
3221 if (child->type == AST_WIRE || child->type == AST_MEMORY || child->type == AST_PARAMETER || child->type == AST_LOCALPARAM ||
3222 child->type == AST_FUNCTION || child->type == AST_TASK || child->type == AST_CELL || child->type == AST_TYPEDEF || child->type == AST_ENUM_ITEM) {
3223 if (backup_name_map.size() == 0)
3224 backup_name_map = name_map;
3225 std::string new_name = prefix[0] == '\\' ? prefix.substr(1) : prefix;
3226 size_t pos = child->str.rfind('.');
3227 if (pos == std::string::npos)
3228 pos = child->str[0] == '\\' && prefix[0] == '\\' ? 1 : 0;
3229 else
3230 pos = pos + 1;
3231 new_name = child->str.substr(0, pos) + new_name + child->str.substr(pos);
3232 if (new_name[0] != '$' && new_name[0] != '\\')
3233 new_name = prefix[0] + new_name;
3234 name_map[child->str] = new_name;
3235 if (child->type == AST_FUNCTION)
3236 replace_result_wire_name_in_function(child, child->str, new_name);
3237 else
3238 child->str = new_name;
3239 current_scope[new_name] = child;
3240 }
3241 if (child->type == AST_ENUM){
3242 current_scope[child->str] = child;
3243 for (auto enode : child->children){
3244 log_assert(enode->type == AST_ENUM_ITEM);
3245 if (backup_name_map.size() == 0)
3246 backup_name_map = name_map;
3247 std::string new_name = prefix[0] == '\\' ? prefix.substr(1) : prefix;
3248 size_t pos = enode->str.rfind('.');
3249 if (pos == std::string::npos)
3250 pos = enode->str[0] == '\\' && prefix[0] == '\\' ? 1 : 0;
3251 else
3252 pos = pos + 1;
3253 new_name = enode->str.substr(0, pos) + new_name + enode->str.substr(pos);
3254 if (new_name[0] != '$' && new_name[0] != '\\')
3255 new_name = prefix[0] + new_name;
3256 name_map[enode->str] = new_name;
3257
3258 enode->str = new_name;
3259 current_scope[new_name] = enode;
3260 }
3261 }
3262 }
3263
3264 for (size_t i = 0; i < children.size(); i++) {
3265 AstNode *child = children[i];
3266 // AST_PREFIX member names should not be prefixed; a nested AST_PREFIX
3267 // still needs to recursed-into
3268 if (type == AST_PREFIX && i == 1 && child->type == AST_IDENTIFIER)
3269 continue;
3270 if (child->type != AST_FUNCTION && child->type != AST_TASK)
3271 child->expand_genblock(index_var, prefix, name_map);
3272 }
3273
3274
3275 if (backup_name_map.size() > 0)
3276 name_map.swap(backup_name_map);
3277 }
3278
3279 // rename stuff (used when tasks of functions are instantiated)
3280 void AstNode::replace_ids(const std::string &prefix, const std::map<std::string, std::string> &rules)
3281 {
3282 if (type == AST_BLOCK)
3283 {
3284 std::map<std::string, std::string> new_rules = rules;
3285 std::string new_prefix = prefix + str;
3286
3287 for (auto child : children)
3288 if (child->type == AST_WIRE) {
3289 new_rules[child->str] = new_prefix + child->str;
3290 child->str = new_prefix + child->str;
3291 }
3292
3293 for (auto child : children)
3294 if (child->type != AST_WIRE)
3295 child->replace_ids(new_prefix, new_rules);
3296 }
3297 else
3298 {
3299 if (type == AST_IDENTIFIER && rules.count(str) > 0)
3300 str = rules.at(str);
3301 for (auto child : children)
3302 child->replace_ids(prefix, rules);
3303 }
3304 }
3305
3306 // helper function for mem2reg_as_needed_pass1
3307 static void mark_memories_assign_lhs_complex(dict<AstNode*, pool<std::string>> &mem2reg_places,
3308 dict<AstNode*, uint32_t> &mem2reg_candidates, AstNode *that)
3309 {
3310 for (auto &child : that->children)
3311 mark_memories_assign_lhs_complex(mem2reg_places, mem2reg_candidates, child);
3312
3313 if (that->type == AST_IDENTIFIER && that->id2ast && that->id2ast->type == AST_MEMORY) {
3314 AstNode *mem = that->id2ast;
3315 if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_CMPLX_LHS))
3316 mem2reg_places[mem].insert(stringf("%s:%d", that->filename.c_str(), that->location.first_line));
3317 mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_CMPLX_LHS;
3318 }
3319 }
3320
3321 // find memories that should be replaced by registers
3322 void AstNode::mem2reg_as_needed_pass1(dict<AstNode*, pool<std::string>> &mem2reg_places,
3323 dict<AstNode*, uint32_t> &mem2reg_candidates, dict<AstNode*, uint32_t> &proc_flags, uint32_t &flags)
3324 {
3325 uint32_t children_flags = 0;
3326 int lhs_children_counter = 0;
3327
3328 if (type == AST_TYPEDEF)
3329 return; // don't touch content of typedefs
3330
3331 if (type == AST_ASSIGN || type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ)
3332 {
3333 // mark all memories that are used in a complex expression on the left side of an assignment
3334 for (auto &lhs_child : children[0]->children)
3335 mark_memories_assign_lhs_complex(mem2reg_places, mem2reg_candidates, lhs_child);
3336
3337 if (children[0]->type == AST_IDENTIFIER && children[0]->id2ast && children[0]->id2ast->type == AST_MEMORY)
3338 {
3339 AstNode *mem = children[0]->id2ast;
3340
3341 // activate mem2reg if this is assigned in an async proc
3342 if (flags & AstNode::MEM2REG_FL_ASYNC) {
3343 if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_SET_ASYNC))
3344 mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), location.first_line));
3345 mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_SET_ASYNC;
3346 }
3347
3348 // remember if this is assigned blocking (=)
3349 if (type == AST_ASSIGN_EQ) {
3350 if (!(proc_flags[mem] & AstNode::MEM2REG_FL_EQ1))
3351 mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), location.first_line));
3352 proc_flags[mem] |= AstNode::MEM2REG_FL_EQ1;
3353 }
3354
3355 // for proper (non-init) writes: remember if this is a constant index or not
3356 if ((flags & MEM2REG_FL_INIT) == 0) {
3357 if (children[0]->children.size() && children[0]->children[0]->type == AST_RANGE && children[0]->children[0]->children.size()) {
3358 if (children[0]->children[0]->children[0]->type == AST_CONSTANT)
3359 mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_CONST_LHS;
3360 else
3361 mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_VAR_LHS;
3362 }
3363 }
3364
3365 // remember where this is
3366 if (flags & MEM2REG_FL_INIT) {
3367 if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_SET_INIT))
3368 mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), location.first_line));
3369 mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_SET_INIT;
3370 } else {
3371 if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_SET_ELSE))
3372 mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), location.first_line));
3373 mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_SET_ELSE;
3374 }
3375 }
3376
3377 lhs_children_counter = 1;
3378 }
3379
3380 if (type == AST_IDENTIFIER && id2ast && id2ast->type == AST_MEMORY)
3381 {
3382 AstNode *mem = id2ast;
3383
3384 // flag if used after blocking assignment (in same proc)
3385 if ((proc_flags[mem] & AstNode::MEM2REG_FL_EQ1) && !(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_EQ2)) {
3386 mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), location.first_line));
3387 mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_EQ2;
3388 }
3389 }
3390
3391 // also activate if requested, either by using mem2reg attribute or by declaring array as 'wire' instead of 'reg'
3392 if (type == AST_MEMORY && (get_bool_attribute(ID::mem2reg) || (flags & AstNode::MEM2REG_FL_ALL) || !is_reg))
3393 mem2reg_candidates[this] |= AstNode::MEM2REG_FL_FORCED;
3394
3395 if (type == AST_MODULE && get_bool_attribute(ID::mem2reg))
3396 children_flags |= AstNode::MEM2REG_FL_ALL;
3397
3398 dict<AstNode*, uint32_t> *proc_flags_p = NULL;
3399
3400 if (type == AST_ALWAYS) {
3401 int count_edge_events = 0;
3402 for (auto child : children)
3403 if (child->type == AST_POSEDGE || child->type == AST_NEGEDGE)
3404 count_edge_events++;
3405 if (count_edge_events != 1)
3406 children_flags |= AstNode::MEM2REG_FL_ASYNC;
3407 proc_flags_p = new dict<AstNode*, uint32_t>;
3408 }
3409
3410 if (type == AST_INITIAL) {
3411 children_flags |= AstNode::MEM2REG_FL_INIT;
3412 proc_flags_p = new dict<AstNode*, uint32_t>;
3413 }
3414
3415 uint32_t backup_flags = flags;
3416 flags |= children_flags;
3417 log_assert((flags & ~0x000000ff) == 0);
3418
3419 for (auto child : children)
3420 {
3421 if (lhs_children_counter > 0) {
3422 lhs_children_counter--;
3423 if (child->children.size() && child->children[0]->type == AST_RANGE && child->children[0]->children.size()) {
3424 for (auto c : child->children[0]->children) {
3425 if (proc_flags_p)
3426 c->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, *proc_flags_p, flags);
3427 else
3428 c->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, proc_flags, flags);
3429 }
3430 }
3431 } else
3432 if (proc_flags_p)
3433 child->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, *proc_flags_p, flags);
3434 else
3435 child->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, proc_flags, flags);
3436 }
3437
3438 flags &= ~children_flags | backup_flags;
3439
3440 if (proc_flags_p) {
3441 #ifndef NDEBUG
3442 for (auto it : *proc_flags_p)
3443 log_assert((it.second & ~0xff000000) == 0);
3444 #endif
3445 delete proc_flags_p;
3446 }
3447 }
3448
3449 bool AstNode::mem2reg_check(pool<AstNode*> &mem2reg_set)
3450 {
3451 if (type != AST_IDENTIFIER || !id2ast || !mem2reg_set.count(id2ast))
3452 return false;
3453
3454 if (children.empty() || children[0]->type != AST_RANGE || GetSize(children[0]->children) != 1)
3455 log_file_error(filename, location.first_line, "Invalid array access.\n");
3456
3457 return true;
3458 }
3459
3460 void AstNode::mem2reg_remove(pool<AstNode*> &mem2reg_set, vector<AstNode*> &delnodes)
3461 {
3462 log_assert(mem2reg_set.count(this) == 0);
3463
3464 if (mem2reg_set.count(id2ast))
3465 id2ast = nullptr;
3466
3467 for (size_t i = 0; i < children.size(); i++) {
3468 if (mem2reg_set.count(children[i]) > 0) {
3469 delnodes.push_back(children[i]);
3470 children.erase(children.begin() + (i--));
3471 } else {
3472 children[i]->mem2reg_remove(mem2reg_set, delnodes);
3473 }
3474 }
3475 }
3476
3477 // actually replace memories with registers
3478 bool AstNode::mem2reg_as_needed_pass2(pool<AstNode*> &mem2reg_set, AstNode *mod, AstNode *block, AstNode *&async_block)
3479 {
3480 bool did_something = false;
3481
3482 if (type == AST_BLOCK)
3483 block = this;
3484
3485 if (type == AST_FUNCTION || type == AST_TASK)
3486 return false;
3487
3488 if (type == AST_TYPEDEF)
3489 return false;
3490
3491 if (type == AST_MEMINIT && id2ast && mem2reg_set.count(id2ast))
3492 {
3493 log_assert(children[0]->type == AST_CONSTANT);
3494 log_assert(children[1]->type == AST_CONSTANT);
3495 log_assert(children[2]->type == AST_CONSTANT);
3496
3497 int cursor = children[0]->asInt(false);
3498 Const data = children[1]->bitsAsConst();
3499 int length = children[2]->asInt(false);
3500
3501 if (length != 0)
3502 {
3503 AstNode *block = new AstNode(AST_INITIAL, new AstNode(AST_BLOCK));
3504 mod->children.push_back(block);
3505 block = block->children[0];
3506
3507 int wordsz = GetSize(data) / length;
3508
3509 for (int i = 0; i < length; i++) {
3510 block->children.push_back(new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER, new AstNode(AST_RANGE, AstNode::mkconst_int(cursor+i, false))), mkconst_bits(data.extract(i*wordsz, wordsz).bits, false)));
3511 block->children.back()->children[0]->str = str;
3512 block->children.back()->children[0]->id2ast = id2ast;
3513 block->children.back()->children[0]->was_checked = true;
3514 }
3515 }
3516
3517 AstNode *newNode = new AstNode(AST_NONE);
3518 newNode->cloneInto(this);
3519 delete newNode;
3520
3521 did_something = true;
3522 }
3523
3524 if (type == AST_ASSIGN && block == NULL && children[0]->mem2reg_check(mem2reg_set))
3525 {
3526 if (async_block == NULL) {
3527 async_block = new AstNode(AST_ALWAYS, new AstNode(AST_BLOCK));
3528 mod->children.push_back(async_block);
3529 }
3530
3531 AstNode *newNode = clone();
3532 newNode->type = AST_ASSIGN_EQ;
3533 newNode->children[0]->was_checked = true;
3534 async_block->children[0]->children.push_back(newNode);
3535
3536 newNode = new AstNode(AST_NONE);
3537 newNode->cloneInto(this);
3538 delete newNode;
3539
3540 did_something = true;
3541 }
3542
3543 if ((type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ) && children[0]->mem2reg_check(mem2reg_set) &&
3544 children[0]->children[0]->children[0]->type != AST_CONSTANT)
3545 {
3546 std::stringstream sstr;
3547 sstr << "$mem2reg_wr$" << children[0]->str << "$" << filename << ":" << location.first_line << "$" << (autoidx++);
3548 std::string id_addr = sstr.str() + "_ADDR", id_data = sstr.str() + "_DATA";
3549
3550 int mem_width, mem_size, addr_bits;
3551 bool mem_signed = children[0]->id2ast->is_signed;
3552 children[0]->id2ast->meminfo(mem_width, mem_size, addr_bits);
3553
3554 AstNode *wire_addr = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(addr_bits-1, true), mkconst_int(0, true)));
3555 wire_addr->str = id_addr;
3556 wire_addr->is_reg = true;
3557 wire_addr->was_checked = true;
3558 wire_addr->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
3559 mod->children.push_back(wire_addr);
3560 while (wire_addr->simplify(true, false, false, 1, -1, false, false)) { }
3561
3562 AstNode *wire_data = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(mem_width-1, true), mkconst_int(0, true)));
3563 wire_data->str = id_data;
3564 wire_data->is_reg = true;
3565 wire_data->was_checked = true;
3566 wire_data->is_signed = mem_signed;
3567 wire_data->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
3568 mod->children.push_back(wire_data);
3569 while (wire_data->simplify(true, false, false, 1, -1, false, false)) { }
3570
3571 log_assert(block != NULL);
3572 size_t assign_idx = 0;
3573 while (assign_idx < block->children.size() && block->children[assign_idx] != this)
3574 assign_idx++;
3575 log_assert(assign_idx < block->children.size());
3576
3577 AstNode *assign_addr = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), children[0]->children[0]->children[0]->clone());
3578 assign_addr->children[0]->str = id_addr;
3579 assign_addr->children[0]->was_checked = true;
3580 block->children.insert(block->children.begin()+assign_idx+1, assign_addr);
3581
3582 AstNode *case_node = new AstNode(AST_CASE, new AstNode(AST_IDENTIFIER));
3583 case_node->children[0]->str = id_addr;
3584 for (int i = 0; i < mem_size; i++) {
3585 if (children[0]->children[0]->children[0]->type == AST_CONSTANT && int(children[0]->children[0]->children[0]->integer) != i)
3586 continue;
3587 AstNode *cond_node = new AstNode(AST_COND, AstNode::mkconst_int(i, false, addr_bits), new AstNode(AST_BLOCK));
3588 AstNode *assign_reg = new AstNode(type, new AstNode(AST_IDENTIFIER), new AstNode(AST_IDENTIFIER));
3589 if (children[0]->children.size() == 2)
3590 assign_reg->children[0]->children.push_back(children[0]->children[1]->clone());
3591 assign_reg->children[0]->str = stringf("%s[%d]", children[0]->str.c_str(), i);
3592 assign_reg->children[1]->str = id_data;
3593 cond_node->children[1]->children.push_back(assign_reg);
3594 case_node->children.push_back(cond_node);
3595 }
3596 block->children.insert(block->children.begin()+assign_idx+2, case_node);
3597
3598 children[0]->delete_children();
3599 children[0]->range_valid = false;
3600 children[0]->id2ast = NULL;
3601 children[0]->str = id_data;
3602 type = AST_ASSIGN_EQ;
3603 children[0]->was_checked = true;
3604
3605 did_something = true;
3606 }
3607
3608 if (mem2reg_check(mem2reg_set))
3609 {
3610 AstNode *bit_part_sel = NULL;
3611 if (children.size() == 2)
3612 bit_part_sel = children[1]->clone();
3613
3614 if (children[0]->children[0]->type == AST_CONSTANT)
3615 {
3616 int id = children[0]->children[0]->integer;
3617 str = stringf("%s[%d]", str.c_str(), id);
3618
3619 delete_children();
3620 range_valid = false;
3621 id2ast = NULL;
3622 }
3623 else
3624 {
3625 std::stringstream sstr;
3626 sstr << "$mem2reg_rd$" << str << "$" << filename << ":" << location.first_line << "$" << (autoidx++);
3627 std::string id_addr = sstr.str() + "_ADDR", id_data = sstr.str() + "_DATA";
3628
3629 int mem_width, mem_size, addr_bits;
3630 bool mem_signed = id2ast->is_signed;
3631 id2ast->meminfo(mem_width, mem_size, addr_bits);
3632
3633 AstNode *wire_addr = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(addr_bits-1, true), mkconst_int(0, true)));
3634 wire_addr->str = id_addr;
3635 wire_addr->is_reg = true;
3636 wire_addr->was_checked = true;
3637 if (block)
3638 wire_addr->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
3639 mod->children.push_back(wire_addr);
3640 while (wire_addr->simplify(true, false, false, 1, -1, false, false)) { }
3641
3642 AstNode *wire_data = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(mem_width-1, true), mkconst_int(0, true)));
3643 wire_data->str = id_data;
3644 wire_data->is_reg = true;
3645 wire_data->was_checked = true;
3646 wire_data->is_signed = mem_signed;
3647 if (block)
3648 wire_data->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
3649 mod->children.push_back(wire_data);
3650 while (wire_data->simplify(true, false, false, 1, -1, false, false)) { }
3651
3652 AstNode *assign_addr = new AstNode(block ? AST_ASSIGN_EQ : AST_ASSIGN, new AstNode(AST_IDENTIFIER), children[0]->children[0]->clone());
3653 assign_addr->children[0]->str = id_addr;
3654 assign_addr->children[0]->was_checked = true;
3655
3656 AstNode *case_node = new AstNode(AST_CASE, new AstNode(AST_IDENTIFIER));
3657 case_node->children[0]->str = id_addr;
3658
3659 for (int i = 0; i < mem_size; i++) {
3660 if (children[0]->children[0]->type == AST_CONSTANT && int(children[0]->children[0]->integer) != i)
3661 continue;
3662 AstNode *cond_node = new AstNode(AST_COND, AstNode::mkconst_int(i, false, addr_bits), new AstNode(AST_BLOCK));
3663 AstNode *assign_reg = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), new AstNode(AST_IDENTIFIER));
3664 assign_reg->children[0]->str = id_data;
3665 assign_reg->children[0]->was_checked = true;
3666 assign_reg->children[1]->str = stringf("%s[%d]", str.c_str(), i);
3667 cond_node->children[1]->children.push_back(assign_reg);
3668 case_node->children.push_back(cond_node);
3669 }
3670
3671 std::vector<RTLIL::State> x_bits;
3672 for (int i = 0; i < mem_width; i++)
3673 x_bits.push_back(RTLIL::State::Sx);
3674
3675 AstNode *cond_node = new AstNode(AST_COND, new AstNode(AST_DEFAULT), new AstNode(AST_BLOCK));
3676 AstNode *assign_reg = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), AstNode::mkconst_bits(x_bits, false));
3677 assign_reg->children[0]->str = id_data;
3678 assign_reg->children[0]->was_checked = true;
3679 cond_node->children[1]->children.push_back(assign_reg);
3680 case_node->children.push_back(cond_node);
3681
3682 if (block)
3683 {
3684 size_t assign_idx = 0;
3685 while (assign_idx < block->children.size() && !block->children[assign_idx]->contains(this))
3686 assign_idx++;
3687 log_assert(assign_idx < block->children.size());
3688 block->children.insert(block->children.begin()+assign_idx, case_node);
3689 block->children.insert(block->children.begin()+assign_idx, assign_addr);
3690 }
3691 else
3692 {
3693 AstNode *proc = new AstNode(AST_ALWAYS, new AstNode(AST_BLOCK));
3694 proc->children[0]->children.push_back(case_node);
3695 mod->children.push_back(proc);
3696 mod->children.push_back(assign_addr);
3697 }
3698
3699 delete_children();
3700 range_valid = false;
3701 id2ast = NULL;
3702 str = id_data;
3703 }
3704
3705 if (bit_part_sel)
3706 children.push_back(bit_part_sel);
3707
3708 did_something = true;
3709 }
3710
3711 log_assert(id2ast == NULL || mem2reg_set.count(id2ast) == 0);
3712
3713 auto children_list = children;
3714 for (size_t i = 0; i < children_list.size(); i++)
3715 if (children_list[i]->mem2reg_as_needed_pass2(mem2reg_set, mod, block, async_block))
3716 did_something = true;
3717
3718 return did_something;
3719 }
3720
3721 // calculate memory dimensions
3722 void AstNode::meminfo(int &mem_width, int &mem_size, int &addr_bits)
3723 {
3724 log_assert(type == AST_MEMORY);
3725
3726 mem_width = children[0]->range_left - children[0]->range_right + 1;
3727 mem_size = children[1]->range_left - children[1]->range_right;
3728
3729 if (mem_size < 0)
3730 mem_size *= -1;
3731 mem_size += min(children[1]->range_left, children[1]->range_right) + 1;
3732
3733 addr_bits = 1;
3734 while ((1 << addr_bits) < mem_size)
3735 addr_bits++;
3736 }
3737
3738 bool AstNode::has_const_only_constructs(bool &recommend_const_eval)
3739 {
3740 if (type == AST_FOR)
3741 recommend_const_eval = true;
3742 if (type == AST_WHILE || type == AST_REPEAT)
3743 return true;
3744 if (type == AST_FCALL && current_scope.count(str))
3745 if (current_scope[str]->has_const_only_constructs(recommend_const_eval))
3746 return true;
3747 for (auto child : children)
3748 if (child->AstNode::has_const_only_constructs(recommend_const_eval))
3749 return true;
3750 return false;
3751 }
3752
3753 bool AstNode::is_simple_const_expr()
3754 {
3755 if (type == AST_IDENTIFIER)
3756 return false;
3757 for (auto child : children)
3758 if (!child->is_simple_const_expr())
3759 return false;
3760 return true;
3761 }
3762
3763 // helper function for AstNode::eval_const_function()
3764 void AstNode::replace_variables(std::map<std::string, AstNode::varinfo_t> &variables, AstNode *fcall)
3765 {
3766 if (type == AST_IDENTIFIER && variables.count(str)) {
3767 int offset = variables.at(str).offset, width = variables.at(str).val.bits.size();
3768 if (!children.empty()) {
3769 if (children.size() != 1 || children.at(0)->type != AST_RANGE)
3770 log_file_error(filename, location.first_line, "Memory access in constant function is not supported\n%s:%d.%d-%d.%d: ...called from here.\n",
3771 fcall->filename.c_str(), fcall->location.first_line, fcall->location.first_column, fcall->location.last_line, fcall->location.last_column);
3772 children.at(0)->replace_variables(variables, fcall);
3773 while (simplify(true, false, false, 1, -1, false, true)) { }
3774 if (!children.at(0)->range_valid)
3775 log_file_error(filename, location.first_line, "Non-constant range\n%s:%d.%d-%d.%d: ... called from here.\n",
3776 fcall->filename.c_str(), fcall->location.first_line, fcall->location.first_column, fcall->location.last_line, fcall->location.last_column);
3777 offset = min(children.at(0)->range_left, children.at(0)->range_right);
3778 width = min(std::abs(children.at(0)->range_left - children.at(0)->range_right) + 1, width);
3779 }
3780 offset -= variables.at(str).offset;
3781 std::vector<RTLIL::State> &var_bits = variables.at(str).val.bits;
3782 std::vector<RTLIL::State> new_bits(var_bits.begin() + offset, var_bits.begin() + offset + width);
3783 AstNode *newNode = mkconst_bits(new_bits, variables.at(str).is_signed);
3784 newNode->cloneInto(this);
3785 delete newNode;
3786 return;
3787 }
3788
3789 for (auto &child : children)
3790 child->replace_variables(variables, fcall);
3791 }
3792
3793 // evaluate functions with all-const arguments
3794 AstNode *AstNode::eval_const_function(AstNode *fcall)
3795 {
3796 std::map<std::string, AstNode*> backup_scope;
3797 std::map<std::string, AstNode::varinfo_t> variables;
3798 AstNode *block = new AstNode(AST_BLOCK);
3799
3800 size_t argidx = 0;
3801 for (auto child : children)
3802 {
3803 if (child->type == AST_WIRE)
3804 {
3805 while (child->simplify(true, false, false, 1, -1, false, true)) { }
3806 if (!child->range_valid)
3807 log_file_error(child->filename, child->location.first_line, "Can't determine size of variable %s\n%s:%d.%d-%d.%d: ... called from here.\n",
3808 child->str.c_str(), fcall->filename.c_str(), fcall->location.first_line, fcall->location.first_column, fcall->location.last_line, fcall->location.last_column);
3809 variables[child->str].val = RTLIL::Const(RTLIL::State::Sx, abs(child->range_left - child->range_right)+1);
3810 variables[child->str].offset = min(child->range_left, child->range_right);
3811 variables[child->str].is_signed = child->is_signed;
3812 if (child->is_input && argidx < fcall->children.size())
3813 variables[child->str].val = fcall->children.at(argidx++)->bitsAsConst(variables[child->str].val.bits.size());
3814 backup_scope[child->str] = current_scope[child->str];
3815 current_scope[child->str] = child;
3816 continue;
3817 }
3818
3819 block->children.push_back(child->clone());
3820 }
3821
3822 log_assert(variables.count(str) != 0);
3823
3824 while (!block->children.empty())
3825 {
3826 AstNode *stmt = block->children.front();
3827
3828 #if 0
3829 log("-----------------------------------\n");
3830 for (auto &it : variables)
3831 log("%20s %40s\n", it.first.c_str(), log_signal(it.second.val));
3832 stmt->dumpAst(NULL, "stmt> ");
3833 #endif
3834
3835 if (stmt->type == AST_ASSIGN_EQ)
3836 {
3837 if (stmt->children.at(0)->type == AST_IDENTIFIER && stmt->children.at(0)->children.size() != 0 &&
3838 stmt->children.at(0)->children.at(0)->type == AST_RANGE)
3839 stmt->children.at(0)->children.at(0)->replace_variables(variables, fcall);
3840 stmt->children.at(1)->replace_variables(variables, fcall);
3841 while (stmt->simplify(true, false, false, 1, -1, false, true)) { }
3842
3843 if (stmt->type != AST_ASSIGN_EQ)
3844 continue;
3845
3846 if (stmt->children.at(1)->type != AST_CONSTANT)
3847 log_file_error(stmt->filename, stmt->location.first_line, "Non-constant expression in constant function\n%s:%d.%d-%d.%d: ... called from here. X\n",
3848 fcall->filename.c_str(), fcall->location.first_line, fcall->location.first_column, fcall->location.last_line, fcall->location.last_column);
3849
3850 if (stmt->children.at(0)->type != AST_IDENTIFIER)
3851 log_file_error(stmt->filename, stmt->location.first_line, "Unsupported composite left hand side in constant function\n%s:%d.%d-%d.%d: ... called from here.\n",
3852 fcall->filename.c_str(), fcall->location.first_line, fcall->location.first_column, fcall->location.last_line, fcall->location.last_column);
3853
3854 if (!variables.count(stmt->children.at(0)->str))
3855 log_file_error(stmt->filename, stmt->location.first_line, "Assignment to non-local variable in constant function\n%s:%d.%d-%d.%d: ... called from here.\n",
3856 fcall->filename.c_str(), fcall->location.first_line, fcall->location.first_column, fcall->location.last_line, fcall->location.last_column);
3857
3858 if (stmt->children.at(0)->children.empty()) {
3859 variables[stmt->children.at(0)->str].val = stmt->children.at(1)->bitsAsConst(variables[stmt->children.at(0)->str].val.bits.size());
3860 } else {
3861 AstNode *range = stmt->children.at(0)->children.at(0);
3862 if (!range->range_valid)
3863 log_file_error(range->filename, range->location.first_line, "Non-constant range\n%s:%d.%d-%d.%d: ... called from here.\n",
3864 fcall->filename.c_str(), fcall->location.first_line, fcall->location.first_column, fcall->location.last_line, fcall->location.last_column);
3865 int offset = min(range->range_left, range->range_right);
3866 int width = std::abs(range->range_left - range->range_right) + 1;
3867 varinfo_t &v = variables[stmt->children.at(0)->str];
3868 RTLIL::Const r = stmt->children.at(1)->bitsAsConst(v.val.bits.size());
3869 for (int i = 0; i < width; i++)
3870 v.val.bits.at(i+offset-v.offset) = r.bits.at(i);
3871 }
3872
3873 delete block->children.front();
3874 block->children.erase(block->children.begin());
3875 continue;
3876 }
3877
3878 if (stmt->type == AST_FOR)
3879 {
3880 block->children.insert(block->children.begin(), stmt->children.at(0));
3881 stmt->children.at(3)->children.push_back(stmt->children.at(2));
3882 stmt->children.erase(stmt->children.begin() + 2);
3883 stmt->children.erase(stmt->children.begin());
3884 stmt->type = AST_WHILE;
3885 continue;
3886 }
3887
3888 if (stmt->type == AST_WHILE)
3889 {
3890 AstNode *cond = stmt->children.at(0)->clone();
3891 cond->replace_variables(variables, fcall);
3892 while (cond->simplify(true, false, false, 1, -1, false, true)) { }
3893
3894 if (cond->type != AST_CONSTANT)
3895 log_file_error(stmt->filename, stmt->location.first_line, "Non-constant expression in constant function\n%s:%d.%d-%d.%d: ... called from here.\n",
3896 fcall->filename.c_str(), fcall->location.first_line, fcall->location.first_column, fcall->location.last_line, fcall->location.last_column);
3897
3898 if (cond->asBool()) {
3899 block->children.insert(block->children.begin(), stmt->children.at(1)->clone());
3900 } else {
3901 delete block->children.front();
3902 block->children.erase(block->children.begin());
3903 }
3904
3905 delete cond;
3906 continue;
3907 }
3908
3909 if (stmt->type == AST_REPEAT)
3910 {
3911 AstNode *num = stmt->children.at(0)->clone();
3912 num->replace_variables(variables, fcall);
3913 while (num->simplify(true, false, false, 1, -1, false, true)) { }
3914
3915 if (num->type != AST_CONSTANT)
3916 log_file_error(stmt->filename, stmt->location.first_line, "Non-constant expression in constant function\n%s:%d.%d-%d.%d: ... called from here.\n",
3917 fcall->filename.c_str(), fcall->location.first_line, fcall->location.first_column, fcall->location.last_line, fcall->location.last_column);
3918
3919 block->children.erase(block->children.begin());
3920 for (int i = 0; i < num->bitsAsConst().as_int(); i++)
3921 block->children.insert(block->children.begin(), stmt->children.at(1)->clone());
3922
3923 delete stmt;
3924 delete num;
3925 continue;
3926 }
3927
3928 if (stmt->type == AST_CASE)
3929 {
3930 AstNode *expr = stmt->children.at(0)->clone();
3931 expr->replace_variables(variables, fcall);
3932 while (expr->simplify(true, false, false, 1, -1, false, true)) { }
3933
3934 AstNode *sel_case = NULL;
3935 for (size_t i = 1; i < stmt->children.size(); i++)
3936 {
3937 bool found_match = false;
3938 log_assert(stmt->children.at(i)->type == AST_COND || stmt->children.at(i)->type == AST_CONDX || stmt->children.at(i)->type == AST_CONDZ);
3939
3940 if (stmt->children.at(i)->children.front()->type == AST_DEFAULT) {
3941 sel_case = stmt->children.at(i)->children.back();
3942 continue;
3943 }
3944
3945 for (size_t j = 0; j+1 < stmt->children.at(i)->children.size() && !found_match; j++)
3946 {
3947 AstNode *cond = stmt->children.at(i)->children.at(j)->clone();
3948 cond->replace_variables(variables, fcall);
3949
3950 cond = new AstNode(AST_EQ, expr->clone(), cond);
3951 while (cond->simplify(true, false, false, 1, -1, false, true)) { }
3952
3953 if (cond->type != AST_CONSTANT)
3954 log_file_error(stmt->filename, stmt->location.first_line, "Non-constant expression in constant function\n%s:%d.%d-%d.%d: ... called from here.\n",
3955 fcall->filename.c_str(), fcall->location.first_line, fcall->location.first_column, fcall->location.last_line, fcall->location.last_column);
3956
3957 found_match = cond->asBool();
3958 delete cond;
3959 }
3960
3961 if (found_match) {
3962 sel_case = stmt->children.at(i)->children.back();
3963 break;
3964 }
3965 }
3966
3967 block->children.erase(block->children.begin());
3968 if (sel_case)
3969 block->children.insert(block->children.begin(), sel_case->clone());
3970 delete stmt;
3971 delete expr;
3972 continue;
3973 }
3974
3975 if (stmt->type == AST_BLOCK)
3976 {
3977 block->children.erase(block->children.begin());
3978 block->children.insert(block->children.begin(), stmt->children.begin(), stmt->children.end());
3979 stmt->children.clear();
3980 delete stmt;
3981 continue;
3982 }
3983
3984 log_file_error(stmt->filename, stmt->location.first_line, "Unsupported language construct in constant function\n%s:%d.%d-%d.%d: ... called from here.\n",
3985 fcall->filename.c_str(), fcall->location.first_line, fcall->location.first_column, fcall->location.last_line, fcall->location.last_column);
3986 log_abort();
3987 }
3988
3989 delete block;
3990
3991 for (auto &it : backup_scope)
3992 if (it.second == NULL)
3993 current_scope.erase(it.first);
3994 else
3995 current_scope[it.first] = it.second;
3996
3997 return AstNode::mkconst_bits(variables.at(str).val.bits, variables.at(str).is_signed);
3998 }
3999
4000 void AstNode::allocateDefaultEnumValues()
4001 {
4002 log_assert(type==AST_ENUM);
4003 int last_enum_int = -1;
4004 for (auto node : children) {
4005 log_assert(node->type==AST_ENUM_ITEM);
4006 node->attributes["\\enum_base_type"] = mkconst_str(str);
4007 for (size_t i = 0; i < node->children.size(); i++) {
4008 switch (node->children[i]->type) {
4009 case AST_NONE:
4010 // replace with auto-incremented constant
4011 delete node->children[i];
4012 node->children[i] = AstNode::mkconst_int(++last_enum_int, true);
4013 break;
4014 case AST_CONSTANT:
4015 // explicit constant (or folded expression)
4016 // TODO: can't extend 'x or 'z item
4017 last_enum_int = node->children[i]->integer;
4018 break;
4019 default:
4020 // ignore ranges
4021 break;
4022 }
4023 // TODO: range check
4024 }
4025 }
4026 }
4027
4028 YOSYS_NAMESPACE_END