2 * yosys -- Yosys Open SYnthesis Suite
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
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.
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.
20 * This is the AST frontend library.
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.
29 #include "kernel/log.h"
30 #include "kernel/utils.h"
31 #include "libs/sha1/sha1.h"
41 using namespace AST_INTERNAL
;
43 // helper function for creating RTLIL code for unary operations
44 static RTLIL::SigSpec
uniop2rtlil(AstNode
*that
, std::string type
, int result_width
, const RTLIL::SigSpec
&arg
, bool gen_attributes
= true)
46 std::stringstream sstr
;
47 sstr
<< type
<< "$" << that
->filename
<< ":" << that
->linenum
<< "$" << (autoidx
++);
49 RTLIL::Cell
*cell
= current_module
->addCell(sstr
.str(), type
);
50 cell
->attributes
["\\src"] = stringf("%s:%d", that
->filename
.c_str(), that
->linenum
);
52 RTLIL::Wire
*wire
= current_module
->addWire(cell
->name
.str() + "_Y", result_width
);
53 wire
->attributes
["\\src"] = stringf("%s:%d", that
->filename
.c_str(), that
->linenum
);
56 for (auto &attr
: that
->attributes
) {
57 if (attr
.second
->type
!= AST_CONSTANT
)
58 log_file_error(that
->filename
, that
->linenum
, "Attribute `%s' with non-constant value!\n", attr
.first
.c_str());
59 cell
->attributes
[attr
.first
] = attr
.second
->asAttrConst();
62 cell
->parameters
["\\A_SIGNED"] = RTLIL::Const(that
->children
[0]->is_signed
);
63 cell
->parameters
["\\A_WIDTH"] = RTLIL::Const(arg
.size());
64 cell
->setPort("\\A", arg
);
66 cell
->parameters
["\\Y_WIDTH"] = result_width
;
67 cell
->setPort("\\Y", wire
);
71 // helper function for extending bit width (preferred over SigSpec::extend() because of correct undef propagation in ConstEval)
72 static void widthExtend(AstNode
*that
, RTLIL::SigSpec
&sig
, int width
, bool is_signed
)
74 if (width
<= sig
.size()) {
75 sig
.extend_u0(width
, is_signed
);
79 std::stringstream sstr
;
80 sstr
<< "$extend" << "$" << that
->filename
<< ":" << that
->linenum
<< "$" << (autoidx
++);
82 RTLIL::Cell
*cell
= current_module
->addCell(sstr
.str(), "$pos");
83 cell
->attributes
["\\src"] = stringf("%s:%d", that
->filename
.c_str(), that
->linenum
);
85 RTLIL::Wire
*wire
= current_module
->addWire(cell
->name
.str() + "_Y", width
);
86 wire
->attributes
["\\src"] = stringf("%s:%d", that
->filename
.c_str(), that
->linenum
);
89 for (auto &attr
: that
->attributes
) {
90 if (attr
.second
->type
!= AST_CONSTANT
)
91 log_file_error(that
->filename
, that
->linenum
, "Attribute `%s' with non-constant value!\n", attr
.first
.c_str());
92 cell
->attributes
[attr
.first
] = attr
.second
->asAttrConst();
95 cell
->parameters
["\\A_SIGNED"] = RTLIL::Const(is_signed
);
96 cell
->parameters
["\\A_WIDTH"] = RTLIL::Const(sig
.size());
97 cell
->setPort("\\A", sig
);
99 cell
->parameters
["\\Y_WIDTH"] = width
;
100 cell
->setPort("\\Y", wire
);
104 // helper function for creating RTLIL code for binary operations
105 static RTLIL::SigSpec
binop2rtlil(AstNode
*that
, std::string type
, int result_width
, const RTLIL::SigSpec
&left
, const RTLIL::SigSpec
&right
)
107 std::stringstream sstr
;
108 sstr
<< type
<< "$" << that
->filename
<< ":" << that
->linenum
<< "$" << (autoidx
++);
110 RTLIL::Cell
*cell
= current_module
->addCell(sstr
.str(), type
);
111 cell
->attributes
["\\src"] = stringf("%s:%d", that
->filename
.c_str(), that
->linenum
);
113 RTLIL::Wire
*wire
= current_module
->addWire(cell
->name
.str() + "_Y", result_width
);
114 wire
->attributes
["\\src"] = stringf("%s:%d", that
->filename
.c_str(), that
->linenum
);
116 for (auto &attr
: that
->attributes
) {
117 if (attr
.second
->type
!= AST_CONSTANT
)
118 log_file_error(that
->filename
, that
->linenum
, "Attribute `%s' with non-constant value!\n", attr
.first
.c_str());
119 cell
->attributes
[attr
.first
] = attr
.second
->asAttrConst();
122 cell
->parameters
["\\A_SIGNED"] = RTLIL::Const(that
->children
[0]->is_signed
);
123 cell
->parameters
["\\B_SIGNED"] = RTLIL::Const(that
->children
[1]->is_signed
);
125 cell
->parameters
["\\A_WIDTH"] = RTLIL::Const(left
.size());
126 cell
->parameters
["\\B_WIDTH"] = RTLIL::Const(right
.size());
128 cell
->setPort("\\A", left
);
129 cell
->setPort("\\B", right
);
131 cell
->parameters
["\\Y_WIDTH"] = result_width
;
132 cell
->setPort("\\Y", wire
);
136 // helper function for creating RTLIL code for multiplexers
137 static RTLIL::SigSpec
mux2rtlil(AstNode
*that
, const RTLIL::SigSpec
&cond
, const RTLIL::SigSpec
&left
, const RTLIL::SigSpec
&right
)
139 log_assert(cond
.size() == 1);
141 std::stringstream sstr
;
142 sstr
<< "$ternary$" << that
->filename
<< ":" << that
->linenum
<< "$" << (autoidx
++);
144 RTLIL::Cell
*cell
= current_module
->addCell(sstr
.str(), "$mux");
145 cell
->attributes
["\\src"] = stringf("%s:%d", that
->filename
.c_str(), that
->linenum
);
147 RTLIL::Wire
*wire
= current_module
->addWire(cell
->name
.str() + "_Y", left
.size());
148 wire
->attributes
["\\src"] = stringf("%s:%d", that
->filename
.c_str(), that
->linenum
);
150 for (auto &attr
: that
->attributes
) {
151 if (attr
.second
->type
!= AST_CONSTANT
)
152 log_file_error(that
->filename
, that
->linenum
, "Attribute `%s' with non-constant value!\n", attr
.first
.c_str());
153 cell
->attributes
[attr
.first
] = attr
.second
->asAttrConst();
156 cell
->parameters
["\\WIDTH"] = RTLIL::Const(left
.size());
158 cell
->setPort("\\A", right
);
159 cell
->setPort("\\B", left
);
160 cell
->setPort("\\S", cond
);
161 cell
->setPort("\\Y", wire
);
166 // helper class for converting AST always nodes to RTLIL processes
167 struct AST_INTERNAL::ProcessGenerator
169 // input and output structures
171 RTLIL::SigSpec initSyncSignals
;
172 RTLIL::Process
*proc
;
173 RTLIL::SigSpec outputSignals
;
175 // This always points to the RTLIL::CaseRule being filled at the moment
176 RTLIL::CaseRule
*current_case
;
178 // This map contains the replacement pattern to be used in the right hand side
179 // of an assignment. E.g. in the code "foo = bar; foo = func(foo);" the foo in the right
180 // hand side of the 2nd assignment needs to be replace with the temporary signal holding
181 // the value assigned in the first assignment. So when the first assignment is processed
182 // the according information is appended to subst_rvalue_from and subst_rvalue_to.
183 stackmap
<RTLIL::SigBit
, RTLIL::SigBit
> subst_rvalue_map
;
185 // This map contains the replacement pattern to be used in the left hand side
186 // of an assignment. E.g. in the code "always @(posedge clk) foo <= bar" the signal bar
187 // should not be connected to the signal foo. Instead it must be connected to the temporary
188 // signal that is used as input for the register that drives the signal foo.
189 stackmap
<RTLIL::SigBit
, RTLIL::SigBit
> subst_lvalue_map
;
191 // The code here generates a number of temporary signal for each output register. This
192 // map helps generating nice numbered names for all this temporary signals.
193 std::map
<RTLIL::Wire
*, int> new_temp_count
;
195 // Buffer for generating the init action
196 RTLIL::SigSpec init_lvalue
, init_rvalue
;
198 ProcessGenerator(AstNode
*always
, RTLIL::SigSpec initSyncSignalsArg
= RTLIL::SigSpec()) : always(always
), initSyncSignals(initSyncSignalsArg
)
200 // generate process and simple root case
201 proc
= new RTLIL::Process
;
202 proc
->attributes
["\\src"] = stringf("%s:%d", always
->filename
.c_str(), always
->linenum
);
203 proc
->name
= stringf("$proc$%s:%d$%d", always
->filename
.c_str(), always
->linenum
, autoidx
++);
204 for (auto &attr
: always
->attributes
) {
205 if (attr
.second
->type
!= AST_CONSTANT
)
206 log_file_error(always
->filename
, always
->linenum
, "Attribute `%s' with non-constant value!\n",
208 proc
->attributes
[attr
.first
] = attr
.second
->asAttrConst();
210 current_module
->processes
[proc
->name
] = proc
;
211 current_case
= &proc
->root_case
;
213 // create initial temporary signal for all output registers
214 RTLIL::SigSpec subst_lvalue_from
, subst_lvalue_to
;
215 collect_lvalues(subst_lvalue_from
, always
, true, true);
216 subst_lvalue_to
= new_temp_signal(subst_lvalue_from
);
217 subst_lvalue_map
= subst_lvalue_from
.to_sigbit_map(subst_lvalue_to
);
219 bool found_global_syncs
= false;
220 bool found_anyedge_syncs
= false;
221 for (auto child
: always
->children
)
223 if ((child
->type
== AST_POSEDGE
|| child
->type
== AST_NEGEDGE
) && GetSize(child
->children
) == 1 && child
->children
.at(0)->type
== AST_IDENTIFIER
&&
224 child
->children
.at(0)->id2ast
&& child
->children
.at(0)->id2ast
->type
== AST_WIRE
&& child
->children
.at(0)->id2ast
->get_bool_attribute("\\gclk")) {
225 found_global_syncs
= true;
227 if (child
->type
== AST_EDGE
) {
228 if (GetSize(child
->children
) == 1 && child
->children
.at(0)->type
== AST_IDENTIFIER
&& child
->children
.at(0)->str
== "\\$global_clock")
229 found_global_syncs
= true;
231 found_anyedge_syncs
= true;
235 if (found_anyedge_syncs
) {
236 if (found_global_syncs
)
237 log_file_error(always
->filename
, always
->linenum
, "Found non-synthesizable event list!\n");
238 log("Note: Assuming pure combinatorial block at %s:%d in\n", always
->filename
.c_str(), always
->linenum
);
239 log("compliance with IEC 62142(E):2005 / IEEE Std. 1364.1(E):2002. Recommending\n");
240 log("use of @* instead of @(...) for better match of synthesis and simulation.\n");
243 // create syncs for the process
244 bool found_clocked_sync
= false;
245 for (auto child
: always
->children
)
246 if (child
->type
== AST_POSEDGE
|| child
->type
== AST_NEGEDGE
) {
247 if (GetSize(child
->children
) == 1 && child
->children
.at(0)->type
== AST_IDENTIFIER
&& child
->children
.at(0)->id2ast
&&
248 child
->children
.at(0)->id2ast
->type
== AST_WIRE
&& child
->children
.at(0)->id2ast
->get_bool_attribute("\\gclk"))
250 found_clocked_sync
= true;
251 if (found_global_syncs
|| found_anyedge_syncs
)
252 log_file_error(always
->filename
, always
->linenum
, "Found non-synthesizable event list!\n");
253 RTLIL::SyncRule
*syncrule
= new RTLIL::SyncRule
;
254 syncrule
->type
= child
->type
== AST_POSEDGE
? RTLIL::STp
: RTLIL::STn
;
255 syncrule
->signal
= child
->children
[0]->genRTLIL();
256 if (GetSize(syncrule
->signal
) != 1)
257 log_file_error(always
->filename
, always
->linenum
, "Found posedge/negedge event on a signal that is not 1 bit wide!\n");
258 addChunkActions(syncrule
->actions
, subst_lvalue_from
, subst_lvalue_to
, true);
259 proc
->syncs
.push_back(syncrule
);
261 if (proc
->syncs
.empty()) {
262 RTLIL::SyncRule
*syncrule
= new RTLIL::SyncRule
;
263 syncrule
->type
= found_global_syncs
? RTLIL::STg
: RTLIL::STa
;
264 syncrule
->signal
= RTLIL::SigSpec();
265 addChunkActions(syncrule
->actions
, subst_lvalue_from
, subst_lvalue_to
, true);
266 proc
->syncs
.push_back(syncrule
);
269 // create initial assignments for the temporary signals
270 if ((flag_nolatches
|| always
->get_bool_attribute("\\nolatches") || current_module
->get_bool_attribute("\\nolatches")) && !found_clocked_sync
) {
271 subst_rvalue_map
= subst_lvalue_from
.to_sigbit_dict(RTLIL::SigSpec(RTLIL::State::Sx
, GetSize(subst_lvalue_from
)));
273 addChunkActions(current_case
->actions
, subst_lvalue_to
, subst_lvalue_from
);
277 for (auto child
: always
->children
)
278 if (child
->type
== AST_BLOCK
)
281 if (initSyncSignals
.size() > 0)
283 RTLIL::SyncRule
*sync
= new RTLIL::SyncRule
;
284 sync
->type
= RTLIL::SyncType::STi
;
285 proc
->syncs
.push_back(sync
);
287 log_assert(init_lvalue
.size() == init_rvalue
.size());
290 for (auto &init_lvalue_c
: init_lvalue
.chunks()) {
291 RTLIL::SigSpec lhs
= init_lvalue_c
;
292 RTLIL::SigSpec rhs
= init_rvalue
.extract(offset
, init_lvalue_c
.width
);
293 remove_unwanted_lvalue_bits(lhs
, rhs
);
294 sync
->actions
.push_back(RTLIL::SigSig(lhs
, rhs
));
295 offset
+= lhs
.size();
299 outputSignals
= RTLIL::SigSpec(subst_lvalue_from
);
302 void remove_unwanted_lvalue_bits(RTLIL::SigSpec
&lhs
, RTLIL::SigSpec
&rhs
)
304 RTLIL::SigSpec new_lhs
, new_rhs
;
306 log_assert(GetSize(lhs
) == GetSize(rhs
));
307 for (int i
= 0; i
< GetSize(lhs
); i
++) {
308 if (lhs
[i
].wire
== nullptr)
310 new_lhs
.append(lhs
[i
]);
311 new_rhs
.append(rhs
[i
]);
318 // create new temporary signals
319 RTLIL::SigSpec
new_temp_signal(RTLIL::SigSpec sig
)
321 std::vector
<RTLIL::SigChunk
> chunks
= sig
.chunks();
323 for (int i
= 0; i
< GetSize(chunks
); i
++)
325 RTLIL::SigChunk
&chunk
= chunks
[i
];
326 if (chunk
.wire
== NULL
)
329 std::string wire_name
;
331 wire_name
= stringf("$%d%s[%d:%d]", new_temp_count
[chunk
.wire
]++,
332 chunk
.wire
->name
.c_str(), chunk
.width
+chunk
.offset
-1, chunk
.offset
);;
333 if (chunk
.wire
->name
.str().find('$') != std::string::npos
)
334 wire_name
+= stringf("$%d", autoidx
++);
335 } while (current_module
->wires_
.count(wire_name
) > 0);
337 RTLIL::Wire
*wire
= current_module
->addWire(wire_name
, chunk
.width
);
338 wire
->attributes
["\\src"] = stringf("%s:%d", always
->filename
.c_str(), always
->linenum
);
347 // recursively traverse the AST an collect all assigned signals
348 void collect_lvalues(RTLIL::SigSpec
®
, AstNode
*ast
, bool type_eq
, bool type_le
, bool run_sort_and_unify
= true)
353 for (auto child
: ast
->children
)
354 if (child
!= ast
->children
[0]) {
355 log_assert(child
->type
== AST_COND
|| child
->type
== AST_CONDX
|| child
->type
== AST_CONDZ
);
356 collect_lvalues(reg
, child
, type_eq
, type_le
, false);
365 for (auto child
: ast
->children
)
366 if (child
->type
== AST_BLOCK
)
367 collect_lvalues(reg
, child
, type_eq
, type_le
, false);
371 for (auto child
: ast
->children
) {
372 if (child
->type
== AST_ASSIGN_EQ
&& type_eq
)
373 reg
.append(child
->children
[0]->genRTLIL());
374 if (child
->type
== AST_ASSIGN_LE
&& type_le
)
375 reg
.append(child
->children
[0]->genRTLIL());
376 if (child
->type
== AST_CASE
|| child
->type
== AST_BLOCK
)
377 collect_lvalues(reg
, child
, type_eq
, type_le
, false);
385 if (run_sort_and_unify
) {
386 std::set
<RTLIL::SigBit
> sorted_reg
;
389 sorted_reg
.insert(bit
);
390 reg
= RTLIL::SigSpec(sorted_reg
);
394 // remove all assignments to the given signal pattern in a case and all its children.
395 // e.g. when the last statement in the code "a = 23; if (b) a = 42; a = 0;" is processed this
396 // function is called to clean up the first two assignments as they are overwritten by
397 // the third assignment.
398 void removeSignalFromCaseTree(const RTLIL::SigSpec
&pattern
, RTLIL::CaseRule
*cs
)
400 for (auto it
= cs
->actions
.begin(); it
!= cs
->actions
.end(); it
++)
401 it
->first
.remove2(pattern
, &it
->second
);
403 for (auto it
= cs
->switches
.begin(); it
!= cs
->switches
.end(); it
++)
404 for (auto it2
= (*it
)->cases
.begin(); it2
!= (*it
)->cases
.end(); it2
++)
405 removeSignalFromCaseTree(pattern
, *it2
);
408 // add an assignment (aka "action") but split it up in chunks. this way huge assignments
409 // are avoided and the generated $mux cells have a more "natural" size.
410 void addChunkActions(std::vector
<RTLIL::SigSig
> &actions
, RTLIL::SigSpec lvalue
, RTLIL::SigSpec rvalue
, bool inSyncRule
= false)
412 if (inSyncRule
&& initSyncSignals
.size() > 0) {
413 init_lvalue
.append(lvalue
.extract(initSyncSignals
));
414 init_rvalue
.append(lvalue
.extract(initSyncSignals
, &rvalue
));
415 lvalue
.remove2(initSyncSignals
, &rvalue
);
417 log_assert(lvalue
.size() == rvalue
.size());
420 for (auto &lvalue_c
: lvalue
.chunks()) {
421 RTLIL::SigSpec lhs
= lvalue_c
;
422 RTLIL::SigSpec rhs
= rvalue
.extract(offset
, lvalue_c
.width
);
423 if (inSyncRule
&& lvalue_c
.wire
&& lvalue_c
.wire
->get_bool_attribute("\\nosync"))
424 rhs
= RTLIL::SigSpec(RTLIL::State::Sx
, rhs
.size());
425 remove_unwanted_lvalue_bits(lhs
, rhs
);
426 actions
.push_back(RTLIL::SigSig(lhs
, rhs
));
427 offset
+= lhs
.size();
431 // recursively process the AST and fill the RTLIL::Process
432 void processAst(AstNode
*ast
)
437 for (auto child
: ast
->children
)
444 RTLIL::SigSpec unmapped_lvalue
= ast
->children
[0]->genRTLIL(), lvalue
= unmapped_lvalue
;
445 RTLIL::SigSpec rvalue
= ast
->children
[1]->genWidthRTLIL(lvalue
.size(), &subst_rvalue_map
.stdmap());
447 pool
<SigBit
> lvalue_sigbits
;
448 for (int i
= 0; i
< GetSize(lvalue
); i
++) {
449 if (lvalue_sigbits
.count(lvalue
[i
]) > 0) {
450 unmapped_lvalue
.remove(i
);
454 lvalue_sigbits
.insert(lvalue
[i
]);
457 lvalue
.replace(subst_lvalue_map
.stdmap());
459 if (ast
->type
== AST_ASSIGN_EQ
) {
460 for (int i
= 0; i
< GetSize(unmapped_lvalue
); i
++)
461 subst_rvalue_map
.set(unmapped_lvalue
[i
], rvalue
[i
]);
464 removeSignalFromCaseTree(lvalue
, current_case
);
465 remove_unwanted_lvalue_bits(lvalue
, rvalue
);
466 current_case
->actions
.push_back(RTLIL::SigSig(lvalue
, rvalue
));
472 RTLIL::SwitchRule
*sw
= new RTLIL::SwitchRule
;
473 sw
->attributes
["\\src"] = stringf("%s:%d", ast
->filename
.c_str(), ast
->linenum
);
474 sw
->signal
= ast
->children
[0]->genWidthRTLIL(-1, &subst_rvalue_map
.stdmap());
475 current_case
->switches
.push_back(sw
);
477 for (auto &attr
: ast
->attributes
) {
478 if (attr
.second
->type
!= AST_CONSTANT
)
479 log_file_error(ast
->filename
, ast
->linenum
, "Attribute `%s' with non-constant value!\n", attr
.first
.c_str());
480 sw
->attributes
[attr
.first
] = attr
.second
->asAttrConst();
483 RTLIL::SigSpec this_case_eq_lvalue
;
484 collect_lvalues(this_case_eq_lvalue
, ast
, true, false);
486 RTLIL::SigSpec this_case_eq_ltemp
= new_temp_signal(this_case_eq_lvalue
);
488 RTLIL::SigSpec this_case_eq_rvalue
= this_case_eq_lvalue
;
489 this_case_eq_rvalue
.replace(subst_rvalue_map
.stdmap());
491 RTLIL::CaseRule
*default_case
= NULL
;
492 RTLIL::CaseRule
*last_generated_case
= NULL
;
493 for (auto child
: ast
->children
)
495 if (child
== ast
->children
[0])
497 log_assert(child
->type
== AST_COND
|| child
->type
== AST_CONDX
|| child
->type
== AST_CONDZ
);
499 subst_lvalue_map
.save();
500 subst_rvalue_map
.save();
502 for (int i
= 0; i
< GetSize(this_case_eq_lvalue
); i
++)
503 subst_lvalue_map
.set(this_case_eq_lvalue
[i
], this_case_eq_ltemp
[i
]);
505 RTLIL::CaseRule
*backup_case
= current_case
;
506 current_case
= new RTLIL::CaseRule
;
507 last_generated_case
= current_case
;
508 addChunkActions(current_case
->actions
, this_case_eq_ltemp
, this_case_eq_rvalue
);
509 for (auto node
: child
->children
) {
510 if (node
->type
== AST_DEFAULT
)
511 default_case
= current_case
;
512 else if (node
->type
== AST_BLOCK
)
515 current_case
->compare
.push_back(node
->genWidthRTLIL(sw
->signal
.size(), &subst_rvalue_map
.stdmap()));
517 if (default_case
!= current_case
)
518 sw
->cases
.push_back(current_case
);
520 log_assert(current_case
->compare
.size() == 0);
521 current_case
= backup_case
;
523 subst_lvalue_map
.restore();
524 subst_rvalue_map
.restore();
527 if (last_generated_case
!= NULL
&& ast
->get_bool_attribute("\\full_case") && default_case
== NULL
) {
529 // this is a valid transformation, but as optimization it is premature.
530 // better: add a default case that assigns 'x' to everything, and let later
531 // optimizations take care of the rest
532 last_generated_case
->compare
.clear();
534 default_case
= new RTLIL::CaseRule
;
535 addChunkActions(default_case
->actions
, this_case_eq_ltemp
, SigSpec(State::Sx
, GetSize(this_case_eq_rvalue
)));
536 sw
->cases
.push_back(default_case
);
539 if (default_case
== NULL
) {
540 default_case
= new RTLIL::CaseRule
;
541 addChunkActions(default_case
->actions
, this_case_eq_ltemp
, this_case_eq_rvalue
);
543 sw
->cases
.push_back(default_case
);
546 for (int i
= 0; i
< GetSize(this_case_eq_lvalue
); i
++)
547 subst_rvalue_map
.set(this_case_eq_lvalue
[i
], this_case_eq_ltemp
[i
]);
549 this_case_eq_lvalue
.replace(subst_lvalue_map
.stdmap());
550 removeSignalFromCaseTree(this_case_eq_lvalue
, current_case
);
551 addChunkActions(current_case
->actions
, this_case_eq_lvalue
, this_case_eq_ltemp
);
556 log_file_error(ast
->filename
, ast
->linenum
, "Found reg declaration in block without label!\n");
560 log_file_error(ast
->filename
, ast
->linenum
, "Found continous assignment in always/initial block!\n");
565 log_file_error(ast
->filename
, ast
->linenum
, "Found parameter declaration in block without label!\n");
574 // ast->dumpAst(NULL, "ast> ");
575 // current_ast_mod->dumpAst(NULL, "mod> ");
581 // detect sign and width of an expression
582 void AstNode::detectSignWidthWorker(int &width_hint
, bool &sign_hint
, bool *found_real
)
584 std::string type_name
;
585 bool sub_sign_hint
= true;
586 int sub_width_hint
= -1;
588 AstNode
*range
= NULL
;
589 AstNode
*id_ast
= NULL
;
591 bool local_found_real
= false;
592 if (found_real
== NULL
)
593 found_real
= &local_found_real
;
598 width_hint
= max(width_hint
, int(bits
.size()));
605 width_hint
= max(width_hint
, 32);
610 if (id_ast
== NULL
&& current_scope
.count(str
))
611 id_ast
= current_scope
.at(str
);
613 log_file_error(filename
, linenum
, "Failed to resolve identifier %s for width detection!\n", str
.c_str());
614 if (id_ast
->type
== AST_PARAMETER
|| id_ast
->type
== AST_LOCALPARAM
) {
615 if (id_ast
->children
.size() > 1 && id_ast
->children
[1]->range_valid
) {
616 this_width
= id_ast
->children
[1]->range_left
- id_ast
->children
[1]->range_right
+ 1;
618 if (id_ast
->children
[0]->type
!= AST_CONSTANT
)
619 while (id_ast
->simplify(true, false, false, 1, -1, false, true)) { }
620 if (id_ast
->children
[0]->type
== AST_CONSTANT
)
621 this_width
= id_ast
->children
[0]->bits
.size();
623 log_file_error(filename
, linenum
, "Failed to detect width for parameter %s!\n", str
.c_str());
624 if (children
.size() != 0)
626 } else if (id_ast
->type
== AST_WIRE
|| id_ast
->type
== AST_AUTOWIRE
) {
627 if (!id_ast
->range_valid
) {
628 if (id_ast
->type
== AST_AUTOWIRE
)
631 // current_ast_mod->dumpAst(NULL, "mod> ");
633 // id_ast->dumpAst(NULL, "decl> ");
634 // dumpAst(NULL, "ref> ");
635 log_file_error(filename
, linenum
, "Failed to detect width of signal access `%s'!\n", str
.c_str());
638 this_width
= id_ast
->range_left
- id_ast
->range_right
+ 1;
639 if (children
.size() != 0)
642 } else if (id_ast
->type
== AST_GENVAR
) {
644 } else if (id_ast
->type
== AST_MEMORY
) {
645 if (!id_ast
->children
[0]->range_valid
)
646 log_file_error(filename
, linenum
, "Failed to detect width of memory access `%s'!\n", str
.c_str());
647 this_width
= id_ast
->children
[0]->range_left
- id_ast
->children
[0]->range_right
+ 1;
648 if (children
.size() > 1)
651 log_file_error(filename
, linenum
, "Failed to detect width for identifier %s!\n", str
.c_str());
653 if (range
->children
.size() == 1)
655 else if (!range
->range_valid
) {
656 AstNode
*left_at_zero_ast
= children
[0]->children
[0]->clone();
657 AstNode
*right_at_zero_ast
= children
[0]->children
.size() >= 2 ? children
[0]->children
[1]->clone() : left_at_zero_ast
->clone();
658 while (left_at_zero_ast
->simplify(true, true, false, 1, -1, false, false)) { }
659 while (right_at_zero_ast
->simplify(true, true, false, 1, -1, false, false)) { }
660 if (left_at_zero_ast
->type
!= AST_CONSTANT
|| right_at_zero_ast
->type
!= AST_CONSTANT
)
661 log_file_error(filename
, linenum
, "Unsupported expression on dynamic range select on signal `%s'!\n", str
.c_str());
662 this_width
= abs(int(left_at_zero_ast
->integer
- right_at_zero_ast
->integer
)) + 1;
663 delete left_at_zero_ast
;
664 delete right_at_zero_ast
;
666 this_width
= range
->range_left
- range
->range_right
+ 1;
669 width_hint
= max(width_hint
, this_width
);
670 if (!id_ast
->is_signed
)
675 while (children
[0]->simplify(true, false, false, 1, -1, false, false) == true) { }
676 if (children
[0]->type
!= AST_CONSTANT
)
677 log_file_error(filename
, linenum
, "Left operand of tobits expression is not constant!\n");
678 children
[1]->detectSignWidthWorker(sub_width_hint
, sign_hint
);
679 width_hint
= max(width_hint
, children
[0]->bitsAsConst().as_int());
683 children
.at(0)->detectSignWidthWorker(width_hint
, sub_sign_hint
);
686 case AST_TO_UNSIGNED
:
687 children
.at(0)->detectSignWidthWorker(width_hint
, sub_sign_hint
);
692 for (auto child
: children
) {
694 sub_sign_hint
= true;
695 child
->detectSignWidthWorker(sub_width_hint
, sub_sign_hint
);
696 this_width
+= sub_width_hint
;
698 width_hint
= max(width_hint
, this_width
);
703 while (children
[0]->simplify(true, false, false, 1, -1, false, true) == true) { }
704 if (children
[0]->type
!= AST_CONSTANT
)
705 log_file_error(filename
, linenum
, "Left operand of replicate expression is not constant!\n");
706 children
[1]->detectSignWidthWorker(sub_width_hint
, sub_sign_hint
);
707 width_hint
= max(width_hint
, children
[0]->bitsAsConst().as_int() * sub_width_hint
);
714 children
[0]->detectSignWidthWorker(width_hint
, sign_hint
, found_real
);
721 for (auto child
: children
)
722 child
->detectSignWidthWorker(width_hint
, sign_hint
, found_real
);
728 case AST_REDUCE_XNOR
:
729 case AST_REDUCE_BOOL
:
730 width_hint
= max(width_hint
, 1);
735 case AST_SHIFT_RIGHT
:
736 case AST_SHIFT_SLEFT
:
737 case AST_SHIFT_SRIGHT
:
739 children
[0]->detectSignWidthWorker(width_hint
, sign_hint
, found_real
);
750 width_hint
= max(width_hint
, 1);
759 for (auto child
: children
)
760 child
->detectSignWidthWorker(width_hint
, sign_hint
, found_real
);
766 width_hint
= max(width_hint
, 1);
771 children
.at(1)->detectSignWidthWorker(width_hint
, sign_hint
, found_real
);
772 children
.at(2)->detectSignWidthWorker(width_hint
, sign_hint
, found_real
);
776 if (!id2ast
->is_signed
)
778 if (!id2ast
->children
[0]->range_valid
)
779 log_file_error(filename
, linenum
, "Failed to detect width of memory access `%s'!\n", str
.c_str());
780 this_width
= id2ast
->children
[0]->range_left
- id2ast
->children
[0]->range_right
+ 1;
781 width_hint
= max(width_hint
, this_width
);
785 if (str
== "\\$anyconst" || str
== "\\$anyseq" || str
== "\\$allconst" || str
== "\\$allseq") {
786 if (GetSize(children
) == 1) {
787 while (children
[0]->simplify(true, false, false, 1, -1, false, true) == true) { }
788 if (children
[0]->type
!= AST_CONSTANT
)
789 log_file_error(filename
, linenum
, "System function %s called with non-const argument!\n",
790 RTLIL::unescape_id(str
).c_str());
791 width_hint
= max(width_hint
, int(children
[0]->asInt(true)));
795 if (str
== "\\$past") {
796 if (GetSize(children
) > 0) {
798 sub_sign_hint
= true;
799 children
.at(0)->detectSignWidthWorker(sub_width_hint
, sub_sign_hint
);
800 width_hint
= max(width_hint
, sub_width_hint
);
807 // everything should have been handled above -> print error if not.
809 for (auto f
: log_files
)
810 current_ast_mod
->dumpAst(f
, "verilog-ast> ");
811 log_file_error(filename
, linenum
, "Don't know how to detect sign and width for %s node!\n", type2str(type
).c_str());
818 // detect sign and width of an expression
819 void AstNode::detectSignWidth(int &width_hint
, bool &sign_hint
, bool *found_real
)
825 detectSignWidthWorker(width_hint
, sign_hint
, found_real
);
828 // create RTLIL from an AST node
829 // all generated cells, wires and processes are added to the module pointed to by 'current_module'
830 // when the AST node is an expression (AST_ADD, AST_BIT_XOR, etc.), the result signal is returned.
832 // note that this function is influenced by a number of global variables that might be set when
833 // called from genWidthRTLIL(). also note that this function recursively calls itself to transform
834 // larger expressions into a netlist of cells.
835 RTLIL::SigSpec
AstNode::genRTLIL(int width_hint
, bool sign_hint
)
837 // in the following big switch() statement there are some uses of
838 // Clifford's Device (http://www.clifford.at/cfun/cliffdev/). In this
839 // cases this variable is used to hold the type of the cell that should
840 // be instantiated for this type of AST node.
841 std::string type_name
;
843 current_filename
= filename
;
844 set_line_num(linenum
);
848 // simply ignore this nodes.
849 // they are either leftovers from simplify() or are referenced by other nodes
850 // and are only accessed here thru this references
854 case AST_DPI_FUNCTION
:
864 case AST_MODPORTMEMBER
:
866 case AST_INTERFACEPORT
: {
867 // If a port in a module with unknown type is found, mark it with the attribute 'is_interface'
868 // This is used by the hierarchy pass to know when it can replace interface connection with the individual
870 RTLIL::Wire
*wire
= current_module
->addWire(str
, 1);
871 wire
->attributes
["\\src"] = stringf("%s:%d", filename
.c_str(), linenum
);
872 wire
->start_offset
= 0;
873 wire
->port_id
= port_id
;
874 wire
->port_input
= true;
875 wire
->port_output
= true;
876 wire
->set_bool_attribute("\\is_interface");
877 if (children
.size() > 0) {
878 for(size_t i
=0; i
<children
.size();i
++) {
879 if(children
[i
]->type
== AST_INTERFACEPORTTYPE
) {
880 std::pair
<std::string
,std::string
> res
= AST::split_modport_from_type(children
[i
]->str
);
881 wire
->attributes
["\\interface_type"] = res
.first
;
882 if (res
.second
!= "")
883 wire
->attributes
["\\interface_modport"] = res
.second
;
891 case AST_INTERFACEPORTTYPE
:
894 // remember the parameter, needed for example in techmap
896 current_module
->avail_parameters
.insert(str
);
901 if (GetSize(children
) < 1 || children
[0]->type
!= AST_CONSTANT
)
902 log_file_error(filename
, linenum
, "Parameter `%s' with non-constant value!\n", str
.c_str());
904 RTLIL::Const val
= children
[0]->bitsAsConst();
905 RTLIL::Wire
*wire
= current_module
->addWire(str
, GetSize(val
));
906 current_module
->connect(wire
, val
);
908 wire
->attributes
["\\src"] = stringf("%s:%d", filename
.c_str(), linenum
);
909 wire
->attributes
[type
== AST_PARAMETER
? "\\parameter" : "\\localparam"] = 1;
911 for (auto &attr
: attributes
) {
912 if (attr
.second
->type
!= AST_CONSTANT
)
913 log_file_error(filename
, linenum
, "Attribute `%s' with non-constant value!\n", attr
.first
.c_str());
914 wire
->attributes
[attr
.first
] = attr
.second
->asAttrConst();
919 // create an RTLIL::Wire for an AST_WIRE node
921 if (current_module
->wires_
.count(str
) != 0)
922 log_file_error(filename
, linenum
, "Re-definition of signal `%s'!\n", str
.c_str());
924 log_file_error(filename
, linenum
, "Signal `%s' with non-constant width!\n", str
.c_str());
926 if (!(range_left
>= range_right
|| (range_left
== -1 && range_right
== 0)))
927 log_file_error(filename
, linenum
, "Signal `%s' with invalid width range %d!\n", str
.c_str(), range_left
- range_right
+ 1);
929 RTLIL::Wire
*wire
= current_module
->addWire(str
, range_left
- range_right
+ 1);
930 wire
->attributes
["\\src"] = stringf("%s:%d", filename
.c_str(), linenum
);
931 wire
->start_offset
= range_right
;
932 wire
->port_id
= port_id
;
933 wire
->port_input
= is_input
;
934 wire
->port_output
= is_output
;
935 wire
->upto
= range_swapped
;
937 for (auto &attr
: attributes
) {
938 if (attr
.second
->type
!= AST_CONSTANT
)
939 log_file_error(filename
, linenum
, "Attribute `%s' with non-constant value!\n", attr
.first
.c_str());
940 wire
->attributes
[attr
.first
] = attr
.second
->asAttrConst();
943 if (is_wand
) wire
->set_bool_attribute("\\wand");
944 if (is_wor
) wire
->set_bool_attribute("\\wor");
948 // create an RTLIL::Memory for an AST_MEMORY node
950 if (current_module
->memories
.count(str
) != 0)
951 log_file_error(filename
, linenum
, "Re-definition of memory `%s'!\n", str
.c_str());
953 log_assert(children
.size() >= 2);
954 log_assert(children
[0]->type
== AST_RANGE
);
955 log_assert(children
[1]->type
== AST_RANGE
);
957 if (!children
[0]->range_valid
|| !children
[1]->range_valid
)
958 log_file_error(filename
, linenum
, "Memory `%s' with non-constant width or size!\n", str
.c_str());
960 RTLIL::Memory
*memory
= new RTLIL::Memory
;
961 memory
->attributes
["\\src"] = stringf("%s:%d", filename
.c_str(), linenum
);
963 memory
->width
= children
[0]->range_left
- children
[0]->range_right
+ 1;
964 if (children
[1]->range_right
< children
[1]->range_left
) {
965 memory
->start_offset
= children
[1]->range_right
;
966 memory
->size
= children
[1]->range_left
- children
[1]->range_right
+ 1;
968 memory
->start_offset
= children
[1]->range_left
;
969 memory
->size
= children
[1]->range_right
- children
[1]->range_left
+ 1;
971 current_module
->memories
[memory
->name
] = memory
;
973 for (auto &attr
: attributes
) {
974 if (attr
.second
->type
!= AST_CONSTANT
)
975 log_file_error(filename
, linenum
, "Attribute `%s' with non-constant value!\n", attr
.first
.c_str());
976 memory
->attributes
[attr
.first
] = attr
.second
->asAttrConst();
981 // simply return the corresponding RTLIL::SigSpec for an AST_CONSTANT node
986 detectSignWidth(width_hint
, sign_hint
);
987 is_signed
= sign_hint
;
989 if (type
== AST_CONSTANT
) {
991 return RTLIL::SigSpec(bitsAsUnsizedConst(width_hint
));
993 return RTLIL::SigSpec(bitsAsConst());
997 RTLIL::SigSpec sig
= realAsConst(width_hint
);
998 log_file_warning(filename
, linenum
, "converting real value %e to binary %s.\n", realvalue
, log_signal(sig
));
1002 // simply return the corresponding RTLIL::SigSpec for an AST_IDENTIFIER node
1003 // for identifiers with dynamic bit ranges (e.g. "foo[bar]" or "foo[bar+3:bar]") a
1004 // shifter cell is created and the output signal of this cell is returned
1005 case AST_IDENTIFIER
:
1007 RTLIL::Wire
*wire
= NULL
;
1008 RTLIL::SigChunk chunk
;
1009 bool is_interface
= false;
1011 int add_undef_bits_msb
= 0;
1012 int add_undef_bits_lsb
= 0;
1014 if (id2ast
&& id2ast
->type
== AST_AUTOWIRE
&& current_module
->wires_
.count(str
) == 0) {
1015 RTLIL::Wire
*wire
= current_module
->addWire(str
);
1016 wire
->attributes
["\\src"] = stringf("%s:%d", filename
.c_str(), linenum
);
1019 log_file_warning(filename
, linenum
, "Identifier `%s' is implicitly declared.\n", str
.c_str());
1021 log_file_error(filename
, linenum
, "Identifier `%s' is implicitly declared and `default_nettype is set to none.\n", str
.c_str());
1023 else if (id2ast
->type
== AST_PARAMETER
|| id2ast
->type
== AST_LOCALPARAM
) {
1024 if (id2ast
->children
[0]->type
!= AST_CONSTANT
)
1025 log_file_error(filename
, linenum
, "Parameter %s does not evaluate to constant value!\n", str
.c_str());
1026 chunk
= RTLIL::Const(id2ast
->children
[0]->bits
);
1027 goto use_const_chunk
;
1029 else if (id2ast
&& (id2ast
->type
== AST_WIRE
|| id2ast
->type
== AST_AUTOWIRE
|| id2ast
->type
== AST_MEMORY
) && current_module
->wires_
.count(str
) != 0) {
1030 RTLIL::Wire
*current_wire
= current_module
->wire(str
);
1031 if (current_wire
->get_bool_attribute("\\is_interface"))
1032 is_interface
= true;
1035 // If an identifier is found that is not already known, assume that it is an interface:
1036 else if (1) { // FIXME: Check if sv_mode first?
1037 is_interface
= true;
1040 log_file_error(filename
, linenum
, "Identifier `%s' doesn't map to any signal!\n", str
.c_str());
1043 if (id2ast
->type
== AST_MEMORY
)
1044 log_file_error(filename
, linenum
, "Identifier `%s' does map to an unexpanded memory!\n", str
.c_str());
1046 // If identifier is an interface, create a RTLIL::SigSpec with a dummy wire with a attribute called 'is_interface'
1047 // This makes it possible for the hierarchy pass to see what are interface connections and then replace them
1048 // with the individual signals:
1050 RTLIL::Wire
*dummy_wire
;
1051 std::string dummy_wire_name
= "$dummywireforinterface" + str
;
1052 if (current_module
->wires_
.count(dummy_wire_name
))
1053 dummy_wire
= current_module
->wires_
[dummy_wire_name
];
1055 dummy_wire
= current_module
->addWire(dummy_wire_name
);
1056 dummy_wire
->set_bool_attribute("\\is_interface");
1058 RTLIL::SigSpec tmp
= RTLIL::SigSpec(dummy_wire
);
1062 wire
= current_module
->wires_
[str
];
1064 chunk
.width
= wire
->width
;
1068 if (children
.size() != 0) {
1069 if (children
[0]->type
!= AST_RANGE
)
1070 log_file_error(filename
, linenum
, "Single range expected.\n");
1071 int source_width
= id2ast
->range_left
- id2ast
->range_right
+ 1;
1072 int source_offset
= id2ast
->range_right
;
1073 if (!children
[0]->range_valid
) {
1074 AstNode
*left_at_zero_ast
= children
[0]->children
[0]->clone();
1075 AstNode
*right_at_zero_ast
= children
[0]->children
.size() >= 2 ? children
[0]->children
[1]->clone() : left_at_zero_ast
->clone();
1076 while (left_at_zero_ast
->simplify(true, true, false, 1, -1, false, false)) { }
1077 while (right_at_zero_ast
->simplify(true, true, false, 1, -1, false, false)) { }
1078 if (left_at_zero_ast
->type
!= AST_CONSTANT
|| right_at_zero_ast
->type
!= AST_CONSTANT
)
1079 log_file_error(filename
, linenum
, "Unsupported expression on dynamic range select on signal `%s'!\n", str
.c_str());
1080 int width
= abs(int(left_at_zero_ast
->integer
- right_at_zero_ast
->integer
)) + 1;
1081 AstNode
*fake_ast
= new AstNode(AST_NONE
, clone(), children
[0]->children
.size() >= 2 ?
1082 children
[0]->children
[1]->clone() : children
[0]->children
[0]->clone());
1083 fake_ast
->children
[0]->delete_children();
1084 RTLIL::SigSpec shift_val
= fake_ast
->children
[1]->genRTLIL();
1085 if (id2ast
->range_right
!= 0) {
1086 shift_val
= current_module
->Sub(NEW_ID
, shift_val
, id2ast
->range_right
, fake_ast
->children
[1]->is_signed
);
1087 fake_ast
->children
[1]->is_signed
= true;
1089 if (id2ast
->range_swapped
) {
1090 shift_val
= current_module
->Sub(NEW_ID
, RTLIL::SigSpec(source_width
- width
), shift_val
, fake_ast
->children
[1]->is_signed
);
1091 fake_ast
->children
[1]->is_signed
= true;
1093 if (GetSize(shift_val
) >= 32)
1094 fake_ast
->children
[1]->is_signed
= true;
1095 RTLIL::SigSpec sig
= binop2rtlil(fake_ast
, "$shiftx", width
, fake_ast
->children
[0]->genRTLIL(), shift_val
);
1096 delete left_at_zero_ast
;
1097 delete right_at_zero_ast
;
1101 chunk
.width
= children
[0]->range_left
- children
[0]->range_right
+ 1;
1102 chunk
.offset
= children
[0]->range_right
- source_offset
;
1103 if (id2ast
->range_swapped
)
1104 chunk
.offset
= (id2ast
->range_left
- id2ast
->range_right
+ 1) - (chunk
.offset
+ chunk
.width
);
1105 if (chunk
.offset
>= source_width
|| chunk
.offset
+ chunk
.width
< 0) {
1106 if (chunk
.width
== 1)
1107 log_file_warning(filename
, linenum
, "Range select out of bounds on signal `%s': Setting result bit to undef.\n",
1110 log_file_warning(filename
, linenum
, "Range select [%d:%d] out of bounds on signal `%s': Setting all %d result bits to undef.\n",
1111 children
[0]->range_left
, children
[0]->range_right
, str
.c_str(), chunk
.width
);
1112 chunk
= RTLIL::SigChunk(RTLIL::State::Sx
, chunk
.width
);
1114 if (chunk
.width
+ chunk
.offset
> source_width
) {
1115 add_undef_bits_msb
= (chunk
.width
+ chunk
.offset
) - source_width
;
1116 chunk
.width
-= add_undef_bits_msb
;
1118 if (chunk
.offset
< 0) {
1119 add_undef_bits_lsb
= -chunk
.offset
;
1120 chunk
.width
-= add_undef_bits_lsb
;
1121 chunk
.offset
+= add_undef_bits_lsb
;
1123 if (add_undef_bits_lsb
)
1124 log_file_warning(filename
, linenum
, "Range [%d:%d] select out of bounds on signal `%s': Setting %d LSB bits to undef.\n",
1125 children
[0]->range_left
, children
[0]->range_right
, str
.c_str(), add_undef_bits_lsb
);
1126 if (add_undef_bits_msb
)
1127 log_file_warning(filename
, linenum
, "Range [%d:%d] select out of bounds on signal `%s': Setting %d MSB bits to undef.\n",
1128 children
[0]->range_left
, children
[0]->range_right
, str
.c_str(), add_undef_bits_msb
);
1133 RTLIL::SigSpec sig
= { RTLIL::SigSpec(RTLIL::State::Sx
, add_undef_bits_msb
), chunk
, RTLIL::SigSpec(RTLIL::State::Sx
, add_undef_bits_lsb
) };
1135 if (genRTLIL_subst_ptr
)
1136 sig
.replace(*genRTLIL_subst_ptr
);
1138 is_signed
= children
.size() > 0 ? false : id2ast
->is_signed
&& sign_hint
;
1142 // just pass thru the signal. the parent will evaluate the is_signed property and interpret the SigSpec accordingly
1144 case AST_TO_UNSIGNED
: {
1145 RTLIL::SigSpec sig
= children
[0]->genRTLIL();
1146 if (sig
.size() < width_hint
)
1147 sig
.extend_u0(width_hint
, sign_hint
);
1148 is_signed
= sign_hint
;
1152 // concatenation of signals can be done directly using RTLIL::SigSpec
1155 for (auto it
= children
.begin(); it
!= children
.end(); it
++)
1156 sig
.append((*it
)->genRTLIL());
1157 if (sig
.size() < width_hint
)
1158 sig
.extend_u0(width_hint
, false);
1162 // replication of signals can be done directly using RTLIL::SigSpec
1163 case AST_REPLICATE
: {
1164 RTLIL::SigSpec left
= children
[0]->genRTLIL();
1165 RTLIL::SigSpec right
= children
[1]->genRTLIL();
1166 if (!left
.is_fully_const())
1167 log_file_error(filename
, linenum
, "Left operand of replicate expression is not constant!\n");
1168 int count
= left
.as_int();
1170 for (int i
= 0; i
< count
; i
++)
1172 if (sig
.size() < width_hint
)
1173 sig
.extend_u0(width_hint
, false);
1178 // generate cells for unary operations: $not, $pos, $neg
1179 if (0) { case AST_BIT_NOT
: type_name
= "$not"; }
1180 if (0) { case AST_POS
: type_name
= "$pos"; }
1181 if (0) { case AST_NEG
: type_name
= "$neg"; }
1183 RTLIL::SigSpec arg
= children
[0]->genRTLIL(width_hint
, sign_hint
);
1184 is_signed
= children
[0]->is_signed
;
1185 int width
= arg
.size();
1186 if (width_hint
> 0) {
1188 widthExtend(this, arg
, width
, is_signed
);
1190 return uniop2rtlil(this, type_name
, width
, arg
);
1193 // generate cells for binary operations: $and, $or, $xor, $xnor
1194 if (0) { case AST_BIT_AND
: type_name
= "$and"; }
1195 if (0) { case AST_BIT_OR
: type_name
= "$or"; }
1196 if (0) { case AST_BIT_XOR
: type_name
= "$xor"; }
1197 if (0) { case AST_BIT_XNOR
: type_name
= "$xnor"; }
1200 detectSignWidth(width_hint
, sign_hint
);
1201 RTLIL::SigSpec left
= children
[0]->genRTLIL(width_hint
, sign_hint
);
1202 RTLIL::SigSpec right
= children
[1]->genRTLIL(width_hint
, sign_hint
);
1203 int width
= max(left
.size(), right
.size());
1206 is_signed
= children
[0]->is_signed
&& children
[1]->is_signed
;
1207 return binop2rtlil(this, type_name
, width
, left
, right
);
1210 // generate cells for unary operations: $reduce_and, $reduce_or, $reduce_xor, $reduce_xnor
1211 if (0) { case AST_REDUCE_AND
: type_name
= "$reduce_and"; }
1212 if (0) { case AST_REDUCE_OR
: type_name
= "$reduce_or"; }
1213 if (0) { case AST_REDUCE_XOR
: type_name
= "$reduce_xor"; }
1214 if (0) { case AST_REDUCE_XNOR
: type_name
= "$reduce_xnor"; }
1216 RTLIL::SigSpec arg
= children
[0]->genRTLIL();
1217 RTLIL::SigSpec sig
= uniop2rtlil(this, type_name
, max(width_hint
, 1), arg
);
1221 // generate cells for unary operations: $reduce_bool
1222 // (this is actually just an $reduce_or, but for clarity a different cell type is used)
1223 if (0) { case AST_REDUCE_BOOL
: type_name
= "$reduce_bool"; }
1225 RTLIL::SigSpec arg
= children
[0]->genRTLIL();
1226 RTLIL::SigSpec sig
= arg
.size() > 1 ? uniop2rtlil(this, type_name
, max(width_hint
, 1), arg
) : arg
;
1230 // generate cells for binary operations: $shl, $shr, $sshl, $sshr
1231 if (0) { case AST_SHIFT_LEFT
: type_name
= "$shl"; }
1232 if (0) { case AST_SHIFT_RIGHT
: type_name
= "$shr"; }
1233 if (0) { case AST_SHIFT_SLEFT
: type_name
= "$sshl"; }
1234 if (0) { case AST_SHIFT_SRIGHT
: type_name
= "$sshr"; }
1237 detectSignWidth(width_hint
, sign_hint
);
1238 RTLIL::SigSpec left
= children
[0]->genRTLIL(width_hint
, sign_hint
);
1239 RTLIL::SigSpec right
= children
[1]->genRTLIL();
1240 int width
= width_hint
> 0 ? width_hint
: left
.size();
1241 is_signed
= children
[0]->is_signed
;
1242 return binop2rtlil(this, type_name
, width
, left
, right
);
1245 // generate cells for binary operations: $pow
1250 children
[1]->detectSignWidth(right_width
, right_signed
);
1252 detectSignWidth(width_hint
, sign_hint
);
1253 RTLIL::SigSpec left
= children
[0]->genRTLIL(width_hint
, sign_hint
);
1254 RTLIL::SigSpec right
= children
[1]->genRTLIL(right_width
, right_signed
);
1255 int width
= width_hint
> 0 ? width_hint
: left
.size();
1256 is_signed
= children
[0]->is_signed
;
1257 if (!flag_noopt
&& left
.is_fully_const() && left
.as_int() == 2 && !right_signed
)
1258 return binop2rtlil(this, "$shl", width
, RTLIL::SigSpec(1, left
.size()), right
);
1259 return binop2rtlil(this, "$pow", width
, left
, right
);
1262 // generate cells for binary operations: $lt, $le, $eq, $ne, $ge, $gt
1263 if (0) { case AST_LT
: type_name
= "$lt"; }
1264 if (0) { case AST_LE
: type_name
= "$le"; }
1265 if (0) { case AST_EQ
: type_name
= "$eq"; }
1266 if (0) { case AST_NE
: type_name
= "$ne"; }
1267 if (0) { case AST_EQX
: type_name
= "$eqx"; }
1268 if (0) { case AST_NEX
: type_name
= "$nex"; }
1269 if (0) { case AST_GE
: type_name
= "$ge"; }
1270 if (0) { case AST_GT
: type_name
= "$gt"; }
1272 int width
= max(width_hint
, 1);
1273 width_hint
= -1, sign_hint
= true;
1274 children
[0]->detectSignWidthWorker(width_hint
, sign_hint
);
1275 children
[1]->detectSignWidthWorker(width_hint
, sign_hint
);
1276 RTLIL::SigSpec left
= children
[0]->genRTLIL(width_hint
, sign_hint
);
1277 RTLIL::SigSpec right
= children
[1]->genRTLIL(width_hint
, sign_hint
);
1278 RTLIL::SigSpec sig
= binop2rtlil(this, type_name
, width
, left
, right
);
1282 // generate cells for binary operations: $add, $sub, $mul, $div, $mod
1283 if (0) { case AST_ADD
: type_name
= "$add"; }
1284 if (0) { case AST_SUB
: type_name
= "$sub"; }
1285 if (0) { case AST_MUL
: type_name
= "$mul"; }
1286 if (0) { case AST_DIV
: type_name
= "$div"; }
1287 if (0) { case AST_MOD
: type_name
= "$mod"; }
1290 detectSignWidth(width_hint
, sign_hint
);
1291 RTLIL::SigSpec left
= children
[0]->genRTLIL(width_hint
, sign_hint
);
1292 RTLIL::SigSpec right
= children
[1]->genRTLIL(width_hint
, sign_hint
);
1294 int width
= max(left
.size(), right
.size());
1295 if (width
> width_hint
&& width_hint
> 0)
1297 if (width
< width_hint
) {
1298 if (type
== AST_ADD
|| type
== AST_SUB
|| type
== AST_DIV
)
1300 if (type
== AST_SUB
&& (!children
[0]->is_signed
|| !children
[1]->is_signed
))
1302 if (type
== AST_MUL
)
1303 width
= min(left
.size() + right
.size(), width_hint
);
1306 int width
= max(max(left
.size(), right
.size()), width_hint
);
1308 is_signed
= children
[0]->is_signed
&& children
[1]->is_signed
;
1309 return binop2rtlil(this, type_name
, width
, left
, right
);
1312 // generate cells for binary operations: $logic_and, $logic_or
1313 if (0) { case AST_LOGIC_AND
: type_name
= "$logic_and"; }
1314 if (0) { case AST_LOGIC_OR
: type_name
= "$logic_or"; }
1316 RTLIL::SigSpec left
= children
[0]->genRTLIL();
1317 RTLIL::SigSpec right
= children
[1]->genRTLIL();
1318 return binop2rtlil(this, type_name
, max(width_hint
, 1), left
, right
);
1321 // generate cells for unary operations: $logic_not
1324 RTLIL::SigSpec arg
= children
[0]->genRTLIL();
1325 return uniop2rtlil(this, "$logic_not", max(width_hint
, 1), arg
);
1328 // generate multiplexer for ternary operator (aka ?:-operator)
1332 detectSignWidth(width_hint
, sign_hint
);
1334 RTLIL::SigSpec cond
= children
[0]->genRTLIL();
1335 RTLIL::SigSpec val1
= children
[1]->genRTLIL(width_hint
, sign_hint
);
1336 RTLIL::SigSpec val2
= children
[2]->genRTLIL(width_hint
, sign_hint
);
1338 if (cond
.size() > 1)
1339 cond
= uniop2rtlil(this, "$reduce_bool", 1, cond
, false);
1341 int width
= max(val1
.size(), val2
.size());
1342 is_signed
= children
[1]->is_signed
&& children
[2]->is_signed
;
1343 widthExtend(this, val1
, width
, is_signed
);
1344 widthExtend(this, val2
, width
, is_signed
);
1346 RTLIL::SigSpec sig
= mux2rtlil(this, cond
, val1
, val2
);
1348 if (sig
.size() < width_hint
)
1349 sig
.extend_u0(width_hint
, sign_hint
);
1353 // generate $memrd cells for memory read ports
1356 std::stringstream sstr
;
1357 sstr
<< "$memrd$" << str
<< "$" << filename
<< ":" << linenum
<< "$" << (autoidx
++);
1359 RTLIL::Cell
*cell
= current_module
->addCell(sstr
.str(), "$memrd");
1360 cell
->attributes
["\\src"] = stringf("%s:%d", filename
.c_str(), linenum
);
1362 RTLIL::Wire
*wire
= current_module
->addWire(cell
->name
.str() + "_DATA", current_module
->memories
[str
]->width
);
1363 wire
->attributes
["\\src"] = stringf("%s:%d", filename
.c_str(), linenum
);
1365 int mem_width
, mem_size
, addr_bits
;
1366 is_signed
= id2ast
->is_signed
;
1367 id2ast
->meminfo(mem_width
, mem_size
, addr_bits
);
1369 RTLIL::SigSpec addr_sig
= children
[0]->genRTLIL();
1371 cell
->setPort("\\CLK", RTLIL::SigSpec(RTLIL::State::Sx
, 1));
1372 cell
->setPort("\\EN", RTLIL::SigSpec(RTLIL::State::Sx
, 1));
1373 cell
->setPort("\\ADDR", addr_sig
);
1374 cell
->setPort("\\DATA", RTLIL::SigSpec(wire
));
1376 cell
->parameters
["\\MEMID"] = RTLIL::Const(str
);
1377 cell
->parameters
["\\ABITS"] = RTLIL::Const(GetSize(addr_sig
));
1378 cell
->parameters
["\\WIDTH"] = RTLIL::Const(wire
->width
);
1380 cell
->parameters
["\\CLK_ENABLE"] = RTLIL::Const(0);
1381 cell
->parameters
["\\CLK_POLARITY"] = RTLIL::Const(0);
1382 cell
->parameters
["\\TRANSPARENT"] = RTLIL::Const(0);
1387 return RTLIL::SigSpec(wire
);
1390 // generate $memwr cells for memory write ports
1394 std::stringstream sstr
;
1395 sstr
<< (type
== AST_MEMWR
? "$memwr$" : "$meminit$") << str
<< "$" << filename
<< ":" << linenum
<< "$" << (autoidx
++);
1397 RTLIL::Cell
*cell
= current_module
->addCell(sstr
.str(), type
== AST_MEMWR
? "$memwr" : "$meminit");
1398 cell
->attributes
["\\src"] = stringf("%s:%d", filename
.c_str(), linenum
);
1400 int mem_width
, mem_size
, addr_bits
;
1401 id2ast
->meminfo(mem_width
, mem_size
, addr_bits
);
1404 if (type
== AST_MEMINIT
) {
1405 if (children
[2]->type
!= AST_CONSTANT
)
1406 log_file_error(filename
, linenum
, "Memory init with non-constant word count!\n");
1407 num_words
= int(children
[2]->asInt(false));
1408 cell
->parameters
["\\WORDS"] = RTLIL::Const(num_words
);
1411 SigSpec addr_sig
= children
[0]->genRTLIL();
1413 cell
->setPort("\\ADDR", addr_sig
);
1414 cell
->setPort("\\DATA", children
[1]->genWidthRTLIL(current_module
->memories
[str
]->width
* num_words
));
1416 cell
->parameters
["\\MEMID"] = RTLIL::Const(str
);
1417 cell
->parameters
["\\ABITS"] = RTLIL::Const(GetSize(addr_sig
));
1418 cell
->parameters
["\\WIDTH"] = RTLIL::Const(current_module
->memories
[str
]->width
);
1420 if (type
== AST_MEMWR
) {
1421 cell
->setPort("\\CLK", RTLIL::SigSpec(RTLIL::State::Sx
, 1));
1422 cell
->setPort("\\EN", children
[2]->genRTLIL());
1423 cell
->parameters
["\\CLK_ENABLE"] = RTLIL::Const(0);
1424 cell
->parameters
["\\CLK_POLARITY"] = RTLIL::Const(0);
1427 cell
->parameters
["\\PRIORITY"] = RTLIL::Const(autoidx
-1);
1431 // generate $assert cells
1438 const char *celltype
= nullptr;
1439 if (type
== AST_ASSERT
) celltype
= "$assert";
1440 if (type
== AST_ASSUME
) celltype
= "$assume";
1441 if (type
== AST_LIVE
) celltype
= "$live";
1442 if (type
== AST_FAIR
) celltype
= "$fair";
1443 if (type
== AST_COVER
) celltype
= "$cover";
1445 log_assert(children
.size() == 2);
1447 RTLIL::SigSpec check
= children
[0]->genRTLIL();
1448 if (GetSize(check
) != 1)
1449 check
= current_module
->ReduceBool(NEW_ID
, check
);
1451 RTLIL::SigSpec en
= children
[1]->genRTLIL();
1452 if (GetSize(en
) != 1)
1453 en
= current_module
->ReduceBool(NEW_ID
, en
);
1457 std::stringstream sstr
;
1458 sstr
<< celltype
<< "$" << filename
<< ":" << linenum
<< "$" << (autoidx
++);
1459 cellname
= sstr
.str();
1464 RTLIL::Cell
*cell
= current_module
->addCell(cellname
, celltype
);
1465 cell
->attributes
["\\src"] = stringf("%s:%d", filename
.c_str(), linenum
);
1467 for (auto &attr
: attributes
) {
1468 if (attr
.second
->type
!= AST_CONSTANT
)
1469 log_file_error(filename
, linenum
, "Attribute `%s' with non-constant value!\n", attr
.first
.c_str());
1470 cell
->attributes
[attr
.first
] = attr
.second
->asAttrConst();
1473 cell
->setPort("\\A", check
);
1474 cell
->setPort("\\EN", en
);
1478 // add entries to current_module->connections for assignments (outside of always blocks)
1481 RTLIL::SigSpec left
= children
[0]->genRTLIL();
1482 RTLIL::SigSpec right
= children
[1]->genWidthRTLIL(left
.size());
1483 if (left
.has_const()) {
1484 RTLIL::SigSpec new_left
, new_right
;
1485 for (int i
= 0; i
< GetSize(left
); i
++)
1487 new_left
.append(left
[i
]);
1488 new_right
.append(right
[i
]);
1490 log_file_warning(filename
, linenum
, "Ignoring assignment to constant bits:\n"
1491 " old assignment: %s = %s\n new assignment: %s = %s.\n",
1492 log_signal(left
), log_signal(right
),
1493 log_signal(new_left
), log_signal(new_right
));
1497 current_module
->connect(RTLIL::SigSig(left
, right
));
1501 // create an RTLIL::Cell for an AST_CELL
1504 int port_counter
= 0, para_counter
= 0;
1506 if (current_module
->count_id(str
) != 0)
1507 log_file_error(filename
, linenum
, "Re-definition of cell `%s'!\n", str
.c_str());
1509 RTLIL::Cell
*cell
= current_module
->addCell(str
, "");
1510 cell
->attributes
["\\src"] = stringf("%s:%d", filename
.c_str(), linenum
);
1511 // Set attribute 'module_not_derived' which will be cleared again after the hierarchy pass
1512 cell
->set_bool_attribute("\\module_not_derived");
1514 for (auto it
= children
.begin(); it
!= children
.end(); it
++) {
1515 AstNode
*child
= *it
;
1516 if (child
->type
== AST_CELLTYPE
) {
1517 cell
->type
= child
->str
;
1518 if (flag_icells
&& cell
->type
.substr(0, 2) == "\\$")
1519 cell
->type
= cell
->type
.substr(1);
1522 if (child
->type
== AST_PARASET
) {
1523 int extra_const_flags
= 0;
1524 IdString paraname
= child
->str
.empty() ? stringf("$%d", ++para_counter
) : child
->str
;
1525 if (child
->children
[0]->type
== AST_REALVALUE
) {
1526 log_file_warning(filename
, linenum
, "Replacing floating point parameter %s.%s = %f with string.\n",
1527 log_id(cell
), log_id(paraname
), child
->children
[0]->realvalue
);
1528 extra_const_flags
= RTLIL::CONST_FLAG_REAL
;
1529 auto strnode
= AstNode::mkconst_str(stringf("%f", child
->children
[0]->realvalue
));
1530 strnode
->cloneInto(child
->children
[0]);
1533 if (child
->children
[0]->type
!= AST_CONSTANT
)
1534 log_file_error(filename
, linenum
, "Parameter %s.%s with non-constant value!\n",
1535 log_id(cell
), log_id(paraname
));
1536 cell
->parameters
[paraname
] = child
->children
[0]->asParaConst();
1537 cell
->parameters
[paraname
].flags
|= extra_const_flags
;
1540 if (child
->type
== AST_ARGUMENT
) {
1542 if (child
->children
.size() > 0)
1543 sig
= child
->children
[0]->genRTLIL();
1544 if (child
->str
.size() == 0) {
1546 snprintf(buf
, 100, "$%d", ++port_counter
);
1547 cell
->setPort(buf
, sig
);
1549 cell
->setPort(child
->str
, sig
);
1555 for (auto &attr
: attributes
) {
1556 if (attr
.second
->type
!= AST_CONSTANT
)
1557 log_file_error(filename
, linenum
, "Attribute `%s' with non-constant value.\n", attr
.first
.c_str());
1558 cell
->attributes
[attr
.first
] = attr
.second
->asAttrConst();
1560 if (cell
->type
.in("$specify2", "$specify3")) {
1561 int src_width
= GetSize(cell
->getPort("\\SRC"));
1562 int dst_width
= GetSize(cell
->getPort("\\DST"));
1563 bool full
= cell
->getParam("\\FULL").as_bool();
1564 if (!full
&& src_width
!= dst_width
)
1565 log_file_error(filename
, linenum
, "Parallel specify SRC width does not match DST width.\n");
1566 if (cell
->type
== "$specify3") {
1567 int dat_width
= GetSize(cell
->getPort("\\DAT"));
1568 if (dat_width
!= dst_width
)
1569 log_file_error(filename
, linenum
, "Specify DAT width does not match DST width.\n");
1571 cell
->setParam("\\SRC_WIDTH", Const(src_width
));
1572 cell
->setParam("\\DST_WIDTH", Const(dst_width
));
1574 if (cell
->type
== "$specrule") {
1575 int src_width
= GetSize(cell
->getPort("\\SRC"));
1576 int dst_width
= GetSize(cell
->getPort("\\DST"));
1577 cell
->setParam("\\SRC_WIDTH", Const(src_width
));
1578 cell
->setParam("\\DST_WIDTH", Const(dst_width
));
1583 // use ProcessGenerator for always blocks
1585 AstNode
*always
= this->clone();
1586 ProcessGenerator
generator(always
);
1587 ignoreThisSignalsInInitial
.append(generator
.outputSignals
);
1592 AstNode
*always
= this->clone();
1593 ProcessGenerator
generator(always
, ignoreThisSignalsInInitial
);
1598 int sz
= children
.size();
1599 if (str
== "$info") {
1601 log_file_info(filename
, linenum
, "%s.\n", children
[0]->str
.c_str());
1603 log_file_info(filename
, linenum
, "\n");
1604 } else if (str
== "$warning") {
1606 log_file_warning(filename
, linenum
, "%s.\n", children
[0]->str
.c_str());
1608 log_file_warning(filename
, linenum
, "\n");
1609 } else if (str
== "$error") {
1611 log_file_error(filename
, linenum
, "%s.\n", children
[0]->str
.c_str());
1613 log_file_error(filename
, linenum
, "\n");
1614 } else if (str
== "$fatal") {
1615 // TODO: 1st parameter, if exists, is 0,1 or 2, and passed to $finish()
1616 // if no parameter is given, default value is 1
1617 // dollar_finish(sz ? children[0] : 1);
1618 // perhaps create & use log_file_fatal()
1620 log_file_error(filename
, linenum
, "FATAL: %s.\n", children
[0]->str
.c_str());
1622 log_file_error(filename
, linenum
, "FATAL.\n");
1624 log_file_error(filename
, linenum
, "Unknown elabortoon system task '%s'.\n", str
.c_str());
1629 if (str
== "\\$anyconst" || str
== "\\$anyseq" || str
== "\\$allconst" || str
== "\\$allseq")
1631 string myid
= stringf("%s$%d", str
.c_str() + 1, autoidx
++);
1632 int width
= width_hint
;
1634 if (GetSize(children
) > 1)
1635 log_file_error(filename
, linenum
, "System function %s got %d arguments, expected 1 or 0.\n",
1636 RTLIL::unescape_id(str
).c_str(), GetSize(children
));
1638 if (GetSize(children
) == 1) {
1639 if (children
[0]->type
!= AST_CONSTANT
)
1640 log_file_error(filename
, linenum
, "System function %s called with non-const argument!\n",
1641 RTLIL::unescape_id(str
).c_str());
1642 width
= children
[0]->asInt(true);
1646 log_file_error(filename
, linenum
, "Failed to detect width of %s!\n", RTLIL::unescape_id(str
).c_str());
1648 Cell
*cell
= current_module
->addCell(myid
, str
.substr(1));
1649 cell
->attributes
["\\src"] = stringf("%s:%d", filename
.c_str(), linenum
);
1650 cell
->parameters
["\\WIDTH"] = width
;
1652 if (attributes
.count("\\reg")) {
1653 auto &attr
= attributes
.at("\\reg");
1654 if (attr
->type
!= AST_CONSTANT
)
1655 log_file_error(filename
, linenum
, "Attribute `reg' with non-constant value!\n");
1656 cell
->attributes
["\\reg"] = attr
->asAttrConst();
1659 Wire
*wire
= current_module
->addWire(myid
+ "_wire", width
);
1660 wire
->attributes
["\\src"] = stringf("%s:%d", filename
.c_str(), linenum
);
1661 cell
->setPort("\\Y", wire
);
1663 is_signed
= sign_hint
;
1664 return SigSpec(wire
);
1666 } /* fall through */
1668 // everything should have been handled above -> print error if not.
1670 for (auto f
: log_files
)
1671 current_ast_mod
->dumpAst(f
, "verilog-ast> ");
1672 type_name
= type2str(type
);
1673 log_file_error(filename
, linenum
, "Don't know how to generate RTLIL code for %s node!\n", type_name
.c_str());
1676 return RTLIL::SigSpec();
1679 // this is a wrapper for AstNode::genRTLIL() when a specific signal width is requested and/or
1680 // signals must be substituted before being used as input values (used by ProcessGenerator)
1681 // note that this is using some global variables to communicate this special settings to AstNode::genRTLIL().
1682 RTLIL::SigSpec
AstNode::genWidthRTLIL(int width
, const dict
<RTLIL::SigBit
, RTLIL::SigBit
> *new_subst_ptr
)
1684 const dict
<RTLIL::SigBit
, RTLIL::SigBit
> *backup_subst_ptr
= genRTLIL_subst_ptr
;
1687 genRTLIL_subst_ptr
= new_subst_ptr
;
1689 bool sign_hint
= true;
1690 int width_hint
= width
;
1691 detectSignWidthWorker(width_hint
, sign_hint
);
1692 RTLIL::SigSpec sig
= genRTLIL(width_hint
, sign_hint
);
1694 genRTLIL_subst_ptr
= backup_subst_ptr
;
1697 sig
.extend_u0(width
, is_signed
);