-
Notifications
You must be signed in to change notification settings - Fork 913
/
Copy pathsimplify.cc
5734 lines (5017 loc) · 196 KB
/
simplify.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* ---
*
* This is the AST frontend library.
*
* The AST frontend library is not a frontend on it's own but provides a
* generic abstract syntax tree (AST) abstraction for HDL code and can be
* used by HDL frontends. See "ast.h" for an overview of the API and the
* Verilog frontend for an usage example.
*
*/
#include "kernel/log.h"
#include "libs/sha1/sha1.h"
#include "frontends/verilog/verilog_frontend.h"
#include "ast.h"
#include <sstream>
#include <stdarg.h>
#include <stdlib.h>
#include <math.h>
// For std::gcd in C++17
// #include <numeric>
YOSYS_NAMESPACE_BEGIN
using namespace AST;
using namespace AST_INTERNAL;
// gcd computed by Euclidian division.
// To be replaced by C++17 std::gcd
template<class I> I gcd(I a, I b) {
while (b != 0) {
I tmp = b;
b = a%b;
a = tmp;
}
return std::abs(a);
}
void AstNode::set_in_lvalue_flag(bool flag, bool no_descend)
{
if (flag != in_lvalue_from_above) {
in_lvalue_from_above = flag;
if (!no_descend)
fixup_hierarchy_flags();
}
}
void AstNode::set_in_param_flag(bool flag, bool no_descend)
{
if (flag != in_param_from_above) {
in_param_from_above = flag;
if (!no_descend)
fixup_hierarchy_flags();
}
}
void AstNode::fixup_hierarchy_flags(bool force_descend)
{
// With forced descend, we disable the implicit
// descend from within the set_* functions, instead
// we do an explicit descend at the end of this function
in_param = in_param_from_above;
switch (type) {
case AST_PARAMETER:
case AST_LOCALPARAM:
case AST_DEFPARAM:
case AST_PARASET:
case AST_PREFIX:
in_param = true;
for (auto child : children)
child->set_in_param_flag(true, force_descend);
break;
case AST_REPLICATE:
case AST_WIRE:
case AST_GENIF:
case AST_GENCASE:
for (auto child : children)
child->set_in_param_flag(in_param, force_descend);
if (children.size() >= 1)
children[0]->set_in_param_flag(true, force_descend);
break;
case AST_GENFOR:
case AST_FOR:
for (auto child : children)
child->set_in_param_flag(in_param, force_descend);
if (children.size() >= 2)
children[1]->set_in_param_flag(true, force_descend);
break;
default:
in_param = in_param_from_above;
for (auto child : children)
child->set_in_param_flag(in_param, force_descend);
}
for (auto attr : attributes)
attr.second->set_in_param_flag(true, force_descend);
in_lvalue = in_lvalue_from_above;
switch (type) {
case AST_ASSIGN:
case AST_ASSIGN_EQ:
case AST_ASSIGN_LE:
if (children.size() >= 1)
children[0]->set_in_lvalue_flag(true, force_descend);
if (children.size() >= 2)
children[1]->set_in_lvalue_flag(in_lvalue, force_descend);
break;
default:
for (auto child : children)
child->set_in_lvalue_flag(in_lvalue, force_descend);
}
if (force_descend) {
for (auto child : children)
child->fixup_hierarchy_flags(true);
for (auto attr : attributes)
attr.second->fixup_hierarchy_flags(true);
}
}
// Process a format string and arguments for $display, $write, $sprintf, etc
Fmt AstNode::processFormat(int stage, bool sformat_like, int default_base, size_t first_arg_at, bool may_fail) {
std::vector<VerilogFmtArg> args;
for (size_t index = first_arg_at; index < children.size(); index++) {
AstNode *node_arg = children[index];
while (node_arg->simplify(true, stage, -1, false)) { }
VerilogFmtArg arg = {};
arg.filename = filename;
arg.first_line = location.first_line;
if (node_arg->type == AST_CONSTANT && node_arg->is_string) {
arg.type = VerilogFmtArg::STRING;
arg.str = node_arg->bitsAsConst().decode_string();
// and in case this will be used as an argument...
arg.sig = node_arg->bitsAsConst();
arg.signed_ = false;
} else if (node_arg->type == AST_IDENTIFIER && node_arg->str == "$time") {
arg.type = VerilogFmtArg::TIME;
} else if (node_arg->type == AST_IDENTIFIER && node_arg->str == "$realtime") {
arg.type = VerilogFmtArg::TIME;
arg.realtime = true;
} else if (node_arg->type == AST_CONSTANT) {
arg.type = VerilogFmtArg::INTEGER;
arg.sig = node_arg->bitsAsConst();
arg.signed_ = node_arg->is_signed;
} else if (may_fail) {
log_file_info(filename, location.first_line, "Skipping system task `%s' with non-constant argument at position %zu.\n", str.c_str(), index + 1);
return Fmt();
} else {
log_file_error(filename, location.first_line, "Failed to evaluate system task `%s' with non-constant argument at position %zu.\n", str.c_str(), index + 1);
}
args.push_back(arg);
}
Fmt fmt;
fmt.parse_verilog(args, sformat_like, default_base, /*task_name=*/str, current_module->name);
return fmt;
}
void AstNode::annotateTypedEnums(AstNode *template_node)
{
//check if enum
if (template_node->attributes.count(ID::enum_type)) {
//get reference to enum node:
std::string enum_type = template_node->attributes[ID::enum_type]->str.c_str();
// log("enum_type=%s (count=%lu)\n", enum_type.c_str(), current_scope.count(enum_type));
// log("current scope:\n");
// for (auto &it : current_scope)
// log(" %s\n", it.first.c_str());
log_assert(current_scope.count(enum_type) == 1);
AstNode *enum_node = current_scope.at(enum_type);
log_assert(enum_node->type == AST_ENUM);
while (enum_node->simplify(true, 1, -1, false)) { }
//get width from 1st enum item:
log_assert(enum_node->children.size() >= 1);
AstNode *enum_item0 = enum_node->children[0];
log_assert(enum_item0->type == AST_ENUM_ITEM);
int width;
if (!enum_item0->range_valid)
width = 1;
else if (enum_item0->range_swapped)
width = enum_item0->range_right - enum_item0->range_left + 1;
else
width = enum_item0->range_left - enum_item0->range_right + 1;
log_assert(width > 0);
//add declared enum items:
for (auto enum_item : enum_node->children){
log_assert(enum_item->type == AST_ENUM_ITEM);
//get is_signed
bool is_signed;
if (enum_item->children.size() == 1){
is_signed = false;
} else if (enum_item->children.size() == 2){
log_assert(enum_item->children[1]->type == AST_RANGE);
is_signed = enum_item->children[1]->is_signed;
} else {
log_error("enum_item children size==%zu, expected 1 or 2 for %s (%s)\n",
(size_t) enum_item->children.size(),
enum_item->str.c_str(), enum_node->str.c_str()
);
}
//start building attribute string
std::string enum_item_str = "\\enum_value_";
//get enum item value
if(enum_item->children[0]->type != AST_CONSTANT){
log_error("expected const, got %s for %s (%s)\n",
type2str(enum_item->children[0]->type).c_str(),
enum_item->str.c_str(), enum_node->str.c_str()
);
}
RTLIL::Const val = enum_item->children[0]->bitsAsConst(width, is_signed);
enum_item_str.append(val.as_string());
//set attribute for available val to enum item name mappings
set_attribute(enum_item_str.c_str(), mkconst_str(enum_item->str));
}
}
}
static AstNode *make_range(int left, int right, bool is_signed = false)
{
// generate a pre-validated range node for a fixed signal range.
auto range = new AstNode(AST_RANGE);
range->range_left = left;
range->range_right = right;
range->range_valid = true;
range->children.push_back(AstNode::mkconst_int(left, true));
range->children.push_back(AstNode::mkconst_int(right, true));
range->is_signed = is_signed;
return range;
}
static int range_width(AstNode *node, AstNode *rnode)
{
log_assert(rnode->type==AST_RANGE);
if (!rnode->range_valid) {
node->input_error("Non-constant range in declaration of %s\n", node->str.c_str());
}
// note: range swapping has already been checked for
return rnode->range_left - rnode->range_right + 1;
}
static int add_dimension(AstNode *node, AstNode *rnode)
{
int width = range_width(node, rnode);
node->dimensions.push_back({ rnode->range_right, width, rnode->range_swapped });
return width;
}
[[noreturn]] static void struct_array_packing_error(AstNode *node)
{
node->input_error("Unpacked array in packed struct/union member %s\n", node->str.c_str());
}
static int size_packed_struct(AstNode *snode, int base_offset)
{
// Struct members will be laid out in the structure contiguously from left to right.
// Union members all have zero offset from the start of the union.
// Determine total packed size and assign offsets. Store these in the member node.
bool is_union = (snode->type == AST_UNION);
int offset = 0;
int packed_width = -1;
// examine members from last to first
for (auto it = snode->children.rbegin(); it != snode->children.rend(); ++it) {
auto node = *it;
int width;
if (node->type == AST_STRUCT || node->type == AST_UNION) {
// embedded struct or union
width = size_packed_struct(node, base_offset + offset);
}
else {
log_assert(node->type == AST_STRUCT_ITEM);
if (node->children.size() > 0 && node->children[0]->type == AST_RANGE) {
// member width e.g. bit [7:0] a
width = range_width(node, node->children[0]);
if (node->children.size() == 2) {
// Unpacked array. Note that this is a Yosys extension; only packed data types
// and integer data types are allowed in packed structs / unions in SystemVerilog.
if (node->children[1]->type == AST_RANGE) {
// Unpacked array, e.g. bit [63:0] a [0:3]
// Pretend it's declared as a packed array, e.g. bit [0:3][63:0] a
auto rnode = node->children[1];
if (rnode->children.size() == 1) {
// C-style array size, e.g. bit [63:0] a [4]
node->dimensions.push_back({ 0, rnode->range_left, true });
width *= rnode->range_left;
} else {
width *= add_dimension(node, rnode);
}
add_dimension(node, node->children[0]);
}
else {
// The Yosys extension for unpacked arrays in packed structs / unions
// only supports memories, i.e. e.g. logic [7:0] a [256] - see above.
struct_array_packing_error(node);
}
} else {
// Vector
add_dimension(node, node->children[0]);
}
// range nodes are now redundant
for (AstNode *child : node->children)
delete child;
node->children.clear();
}
else if (node->children.size() > 0 && node->children[0]->type == AST_MULTIRANGE) {
// Packed array, e.g. bit [3:0][63:0] a
if (node->children.size() != 1) {
// The Yosys extension for unpacked arrays in packed structs / unions
// only supports memories, i.e. e.g. logic [7:0] a [256] - see above.
struct_array_packing_error(node);
}
width = 1;
for (auto rnode : node->children[0]->children) {
width *= add_dimension(node, rnode);
}
// range nodes are now redundant
for (AstNode *child : node->children)
delete child;
node->children.clear();
}
else if (node->range_left < 0) {
// 1 bit signal: bit, logic or reg
width = 1;
node->dimensions.push_back({ 0, width, false });
}
else {
// already resolved and compacted
width = node->range_left - node->range_right + 1;
}
if (is_union) {
node->range_right = base_offset;
node->range_left = base_offset + width - 1;
}
else {
node->range_right = base_offset + offset;
node->range_left = base_offset + offset + width - 1;
}
node->range_valid = true;
}
if (is_union) {
// check that all members have the same size
if (packed_width == -1) {
// first member
packed_width = width;
}
else {
if (packed_width != width)
node->input_error("member %s of a packed union has %d bits, expecting %d\n", node->str.c_str(), width, packed_width);
}
}
else {
offset += width;
}
}
int width = is_union ? packed_width : offset;
snode->range_right = base_offset;
snode->range_left = base_offset + width - 1;
snode->range_valid = true;
snode->dimensions.push_back({ 0, width, false });
return width;
}
static AstNode *node_int(int ival)
{
return AstNode::mkconst_int(ival, true);
}
static AstNode *multiply_by_const(AstNode *expr_node, int stride)
{
return new AstNode(AST_MUL, expr_node, node_int(stride));
}
static AstNode *normalize_index(AstNode *expr, AstNode *decl_node, int dimension)
{
expr = expr->clone();
int offset = decl_node->dimensions[dimension].range_right;
if (offset) {
expr = new AstNode(AST_SUB, expr, node_int(offset));
}
// Packed dimensions are normally indexed by lsb, while unpacked dimensions are normally indexed by msb.
if ((dimension < decl_node->unpacked_dimensions) ^ decl_node->dimensions[dimension].range_swapped) {
// Swap the index if the dimension is declared the "wrong" way.
int left = decl_node->dimensions[dimension].range_width - 1;
expr = new AstNode(AST_SUB, node_int(left), expr);
}
return expr;
}
static AstNode *index_offset(AstNode *offset, AstNode *rnode, AstNode *decl_node, int dimension, int &stride)
{
stride /= decl_node->dimensions[dimension].range_width;
auto right = normalize_index(rnode->children.back(), decl_node, dimension);
auto add_offset = stride > 1 ? multiply_by_const(right, stride) : right;
return offset ? new AstNode(AST_ADD, offset, add_offset) : add_offset;
}
static AstNode *index_msb_offset(AstNode *lsb_offset, AstNode *rnode, AstNode *decl_node, int dimension, int stride)
{
log_assert(rnode->children.size() <= 2);
// Offset to add to LSB
AstNode *add_offset;
if (rnode->children.size() == 1) {
// Index, e.g. s.a[i]
add_offset = node_int(stride - 1);
}
else {
// rnode->children.size() == 2
// Slice, e.g. s.a[i:j]
auto left = normalize_index(rnode->children[0], decl_node, dimension);
auto right = normalize_index(rnode->children[1], decl_node, dimension);
add_offset = new AstNode(AST_SUB, left, right);
if (stride > 1) {
// offset = (msb - lsb + 1)*stride - 1
auto slice_width = new AstNode(AST_ADD, add_offset, node_int(1));
add_offset = new AstNode(AST_SUB, multiply_by_const(slice_width, stride), node_int(1));
}
}
return new AstNode(AST_ADD, lsb_offset, add_offset);
}
AstNode *AstNode::make_index_range(AstNode *decl_node, bool unpacked_range)
{
// Work out the range in the packed array that corresponds to a struct member
// taking into account any range operations applicable to the current node
// such as array indexing or slicing
if (children.empty()) {
// no range operations apply, return the whole width
return make_range(decl_node->range_left - decl_node->range_right, 0);
}
log_assert(children.size() == 1);
// Range operations
AstNode *rnode = children[0];
AstNode *offset = NULL;
int dim = unpacked_range ? 0 : decl_node->unpacked_dimensions;
int max_dim = unpacked_range ? decl_node->unpacked_dimensions : GetSize(decl_node->dimensions);
int stride = 1;
for (int i = dim; i < max_dim; i++) {
stride *= decl_node->dimensions[i].range_width;
}
// Calculate LSB offset for the final index / slice
if (rnode->type == AST_RANGE) {
offset = index_offset(offset, rnode, decl_node, dim, stride);
}
else if (rnode->type == AST_MULTIRANGE) {
// Add offset for each dimension
AstNode *mrnode = rnode;
int stop_dim = std::min(GetSize(mrnode->children), max_dim);
for (; dim < stop_dim; dim++) {
rnode = mrnode->children[dim];
offset = index_offset(offset, rnode, decl_node, dim, stride);
}
dim--; // Step back to the final index / slice
}
else {
input_error("Unsupported range operation for %s\n", str.c_str());
}
AstNode *index_range = new AstNode(AST_RANGE);
if (!unpacked_range && (stride > 1 || GetSize(rnode->children) == 2)) {
// Calculate MSB offset for the final index / slice of packed dimensions.
AstNode *msb_offset = index_msb_offset(offset->clone(), rnode, decl_node, dim, stride);
index_range->children.push_back(msb_offset);
}
index_range->children.push_back(offset);
return index_range;
}
AstNode *AstNode::get_struct_member() const
{
AstNode *member_node;
if (attributes.count(ID::wiretype) && (member_node = attributes.at(ID::wiretype)) &&
(member_node->type == AST_STRUCT_ITEM || member_node->type == AST_STRUCT || member_node->type == AST_UNION))
{
return member_node;
}
return nullptr;
}
static void add_members_to_scope(AstNode *snode, std::string name)
{
// add all the members in a struct or union to local scope
// in case later referenced in assignments
log_assert(snode->type==AST_STRUCT || snode->type==AST_UNION);
for (auto *node : snode->children) {
auto member_name = name + "." + node->str;
current_scope[member_name] = node;
if (node->type != AST_STRUCT_ITEM) {
// embedded struct or union
add_members_to_scope(node, name + "." + node->str);
}
}
}
static AstNode *make_packed_struct(AstNode *template_node, std::string &name, decltype(AstNode::attributes) &attributes)
{
// create a wire for the packed struct
auto wnode = new AstNode(AST_WIRE, make_range(template_node->range_left, 0));
wnode->str = name;
wnode->is_logic = true;
wnode->range_valid = true;
wnode->is_signed = template_node->is_signed;
for (auto &pair : attributes) {
wnode->set_attribute(pair.first, pair.second->clone());
}
// resolve packed dimension
while (wnode->simplify(true, 1, -1, false)) {}
// make sure this node is the one in scope for this name
current_scope[name] = wnode;
// add all the struct members to scope under the wire's name
add_members_to_scope(template_node, name);
return wnode;
}
static void prepend_ranges(AstNode *&range, AstNode *range_add)
{
// Convert range to multirange.
if (range->type == AST_RANGE)
range = new AstNode(AST_MULTIRANGE, range);
// Add range or ranges.
if (range_add->type == AST_RANGE)
range->children.insert(range->children.begin(), range_add->clone());
else {
int i = 0;
for (auto child : range_add->children)
range->children.insert(range->children.begin() + i++, child->clone());
}
}
// check if a node or its children contains an assignment to the given variable
static bool node_contains_assignment_to(const AstNode* node, const AstNode* var)
{
if (node->type == AST_ASSIGN_EQ || node->type == AST_ASSIGN_LE) {
// current node is iteslf an assignment
log_assert(node->children.size() >= 2);
const AstNode* lhs = node->children[0];
if (lhs->type == AST_IDENTIFIER && lhs->str == var->str)
return false;
}
for (const AstNode* child : node->children) {
// if this child shadows the given variable
if (child != var && child->str == var->str && child->type == AST_WIRE)
break; // skip the remainder of this block/scope
// depth-first short circuit
if (!node_contains_assignment_to(child, var))
return false;
}
return true;
}
static std::string prefix_id(const std::string &prefix, const std::string &str)
{
log_assert(!prefix.empty() && (prefix.front() == '$' || prefix.front() == '\\'));
log_assert(!str.empty() && (str.front() == '$' || str.front() == '\\'));
log_assert(prefix.back() == '.');
if (str.front() == '\\')
return prefix + str.substr(1);
return prefix + str;
}
// direct access to this global should be limited to the following two functions
static const RTLIL::Design *simplify_design_context = nullptr;
void AST::set_simplify_design_context(const RTLIL::Design *design)
{
log_assert(!simplify_design_context || !design);
simplify_design_context = design;
}
// lookup the module with the given name in the current design context
static const RTLIL::Module* lookup_module(const std::string &name)
{
return simplify_design_context->module(name);
}
const RTLIL::Module* AstNode::lookup_cell_module()
{
log_assert(type == AST_CELL);
auto reprocess_after = [this] (const std::string &modname) {
if (!attributes.count(ID::reprocess_after))
set_attribute(ID::reprocess_after, AstNode::mkconst_str(modname));
};
const AstNode *celltype = nullptr;
for (const AstNode *child : children)
if (child->type == AST_CELLTYPE) {
celltype = child;
break;
}
log_assert(celltype != nullptr);
const RTLIL::Module *module = lookup_module(celltype->str);
if (!module)
module = lookup_module("$abstract" + celltype->str);
if (!module) {
if (celltype->str.at(0) != '$')
reprocess_after(celltype->str);
return nullptr;
}
// build a mapping from true param name to param value
size_t para_counter = 0;
dict<RTLIL::IdString, RTLIL::Const> cell_params_map;
for (AstNode *child : children) {
if (child->type != AST_PARASET)
continue;
if (child->str.empty() && para_counter >= module->avail_parameters.size())
return nullptr; // let hierarchy handle this error
IdString paraname = child->str.empty() ? module->avail_parameters[para_counter++] : child->str;
const AstNode *value = child->children[0];
if (value->type != AST_REALVALUE && value->type != AST_CONSTANT)
return nullptr; // let genrtlil handle this error
cell_params_map[paraname] = value->asParaConst();
}
// put the parameters in order and generate the derived module name
std::vector<std::pair<RTLIL::IdString, RTLIL::Const>> named_parameters;
for (RTLIL::IdString param : module->avail_parameters) {
auto it = cell_params_map.find(param);
if (it != cell_params_map.end())
named_parameters.emplace_back(it->first, it->second);
}
std::string modname = celltype->str;
if (cell_params_map.size()) // not named_parameters to cover hierarchical defparams
modname = derived_module_name(celltype->str, named_parameters);
// try to find the resolved module
module = lookup_module(modname);
if (!module) {
reprocess_after(modname);
return nullptr;
}
return module;
}
// returns whether an expression contains an unbased unsized literal; does not
// check the literal exists in a self-determined context
static bool contains_unbased_unsized(const AstNode *node)
{
if (node->type == AST_CONSTANT)
return node->is_unsized;
for (const AstNode *child : node->children)
if (contains_unbased_unsized(child))
return true;
return false;
}
// adds a wire to the current module with the given name that matches the
// dimensions of the given wire reference
void add_wire_for_ref(const RTLIL::Wire *ref, const std::string &str)
{
AstNode *left = AstNode::mkconst_int(ref->width - 1 + ref->start_offset, true);
AstNode *right = AstNode::mkconst_int(ref->start_offset, true);
if (ref->upto)
std::swap(left, right);
AstNode *range = new AstNode(AST_RANGE, left, right);
AstNode *wire = new AstNode(AST_WIRE, range);
wire->is_signed = ref->is_signed;
wire->is_logic = true;
wire->str = str;
current_ast_mod->children.push_back(wire);
current_scope[str] = wire;
}
enum class IdentUsage {
NotReferenced, // target variable is neither read or written in the block
Assigned, // target variable is always assigned before use
SyncRequired, // target variable may be used before it has been assigned
};
// determines whether a local variable a block is always assigned before it is
// used, meaning the nosync attribute can automatically be added to that
// variable
static IdentUsage always_asgn_before_use(const AstNode *node, const std::string &target)
{
// This variable has been referenced before it has necessarily been assigned
// a value in this procedure.
if (node->type == AST_IDENTIFIER && node->str == target)
return IdentUsage::SyncRequired;
// For case statements (which are also used for if/else), we check each
// possible branch. If the variable is assigned in all branches, then it is
// assigned, and a sync isn't required. If it used before assignment in any
// branch, then a sync is required.
if (node->type == AST_CASE) {
bool all_defined = true;
bool any_used = false;
bool has_default = false;
for (const AstNode *child : node->children) {
if (child->type == AST_COND && child->children.at(0)->type == AST_DEFAULT)
has_default = true;
IdentUsage nested = always_asgn_before_use(child, target);
if (nested != IdentUsage::Assigned && child->type == AST_COND)
all_defined = false;
if (nested == IdentUsage::SyncRequired)
any_used = true;
}
if (any_used)
return IdentUsage::SyncRequired;
else if (all_defined && has_default)
return IdentUsage::Assigned;
else
return IdentUsage::NotReferenced;
}
// Check if this is an assignment to the target variable. For simplicity, we
// don't analyze sub-ranges of the variable.
if (node->type == AST_ASSIGN_EQ) {
const AstNode *ident = node->children.at(0);
if (ident->type == AST_IDENTIFIER && ident->str == target)
return IdentUsage::Assigned;
}
for (const AstNode *child : node->children) {
IdentUsage nested = always_asgn_before_use(child, target);
if (nested != IdentUsage::NotReferenced)
return nested;
}
return IdentUsage::NotReferenced;
}
AstNode *AstNode::clone_at_zero()
{
int width_hint;
bool sign_hint;
AstNode *pointee;
switch (type) {
case AST_IDENTIFIER:
if (id2ast)
pointee = id2ast;
else if (current_scope.count(str))
pointee = current_scope[str];
else
break;
if (pointee->type != AST_WIRE &&
pointee->type != AST_AUTOWIRE &&
pointee->type != AST_MEMORY)
break;
YS_FALLTHROUGH
case AST_MEMRD:
detectSignWidth(width_hint, sign_hint);
return mkconst_int(0, sign_hint, width_hint);
default:
break;
}
AstNode *that = new AstNode;
*that = *this;
for (auto &it : that->children)
it = it->clone_at_zero();
for (auto &it : that->attributes)
it.second = it.second->clone();
that->set_in_lvalue_flag(false);
that->set_in_param_flag(false);
that->fixup_hierarchy_flags();
return that;
}
static bool try_determine_range_width(AstNode *range, int &result_width)
{
log_assert(range->type == AST_RANGE);
if (range->children.size() == 1) {
result_width = 1;
return true;
}
AstNode *left_at_zero_ast = range->children[0]->clone_at_zero();
AstNode *right_at_zero_ast = range->children[1]->clone_at_zero();
while (left_at_zero_ast->simplify(true, 1, -1, false)) {}
while (right_at_zero_ast->simplify(true, 1, -1, false)) {}
bool ok = false;
if (left_at_zero_ast->type == AST_CONSTANT
&& right_at_zero_ast->type == AST_CONSTANT) {
ok = true;
result_width = abs(int(left_at_zero_ast->integer - right_at_zero_ast->integer)) + 1;
}
delete left_at_zero_ast;
delete right_at_zero_ast;
return ok;
}
static const std::string auto_nosync_prefix = "\\AutoNosync";
// mark a local variable in an always_comb block for automatic nosync
// consideration
static void mark_auto_nosync(AstNode *block, const AstNode *wire)
{
log_assert(block->type == AST_BLOCK);
log_assert(wire->type == AST_WIRE);
block->set_attribute(auto_nosync_prefix + wire->str, AstNode::mkconst_int(1, false));
}
// block names can be prefixed with an explicit scope during elaboration
static bool is_autonamed_block(const std::string &str) {
size_t last_dot = str.rfind('.');
// unprefixed names: autonamed if the first char is a dollar sign
if (last_dot == std::string::npos)
return str.at(0) == '$'; // e.g., `$fordecl_block$1`
// prefixed names: autonamed if the final chunk begins with a dollar sign
return str.rfind(".$") == last_dot; // e.g., `\foo.bar.$fordecl_block$1`
}
// check a procedural block for auto-nosync markings, remove them, and add
// nosync to local variables as necessary
static void check_auto_nosync(AstNode *node)
{
std::vector<RTLIL::IdString> attrs_to_drop;
for (const auto& elem : node->attributes) {
// skip attributes that don't begin with the prefix
if (elem.first.compare(0, auto_nosync_prefix.size(),
auto_nosync_prefix.c_str()))
continue;
// delete and remove the attribute once we're done iterating
attrs_to_drop.push_back(elem.first);
// find the wire based on the attribute
std::string wire_name = elem.first.substr(auto_nosync_prefix.size());
auto it = current_scope.find(wire_name);
if (it == current_scope.end())
continue;
// analyze the usage of the local variable in this block
IdentUsage ident_usage = always_asgn_before_use(node, wire_name);
if (ident_usage != IdentUsage::Assigned)
continue;
// mark the wire with `nosync`
AstNode *wire = it->second;
log_assert(wire->type == AST_WIRE);
wire->set_attribute(ID::nosync, AstNode::mkconst_int(1, false));
}
// remove the attributes we've "consumed"
for (const RTLIL::IdString &str : attrs_to_drop) {
auto it = node->attributes.find(str);
delete it->second;
node->attributes.erase(it);
}
// check local variables in any nested blocks
for (AstNode *child : node->children)
check_auto_nosync(child);
}
// convert the AST into a simpler AST that has all parameters substituted by their
// values, unrolled for-loops, expanded generate blocks, etc. when this function
// is done with an AST it can be converted into RTLIL using genRTLIL().
//
// this function also does all name resolving and sets the id2ast member of all
// nodes that link to a different node using names and lexical scoping.
bool AstNode::simplify(bool const_fold, int stage, int width_hint, bool sign_hint)
{
static int recursion_counter = 0;
static bool deep_recursion_warning = false;
if (recursion_counter++ == 1000 && deep_recursion_warning) {
log_warning("Deep recursion in AST simplifier.\nDoes this design contain overly long or deeply nested expressions, or excessive recursion?\n");
deep_recursion_warning = false;
}
static bool unevaluated_tern_branch = false;
AstNode *newNode = NULL;
bool did_something = false;
#if 0
log("-------------\n");
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);
log("const_fold=%d, stage=%d, width_hint=%d, sign_hint=%d\n",
int(const_fold), int(stage), int(width_hint), int(sign_hint));
// dumpAst(NULL, "> ");
#endif
if (stage == 0)
{
log_assert(type == AST_MODULE || type == AST_INTERFACE);
deep_recursion_warning = true;
while (simplify(const_fold, 1, width_hint, sign_hint)) { }
if (!flag_nomem2reg && !get_bool_attribute(ID::nomem2reg))
{
dict<AstNode*, pool<std::string>> mem2reg_places;
dict<AstNode*, uint32_t> mem2reg_candidates, dummy_proc_flags;
uint32_t flags = flag_mem2reg ? AstNode::MEM2REG_FL_ALL : 0;
mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, dummy_proc_flags, flags);
pool<AstNode*> mem2reg_set;
for (auto &it : mem2reg_candidates)
{
AstNode *mem = it.first;
uint32_t memflags = it.second;
bool this_nomeminit = flag_nomeminit;
log_assert((memflags & ~0x00ffff00) == 0);
if (mem->get_bool_attribute(ID::nomem2reg))
continue;
if (mem->get_bool_attribute(ID::nomeminit) || get_bool_attribute(ID::nomeminit))
this_nomeminit = true;
if (memflags & AstNode::MEM2REG_FL_FORCED)
goto silent_activate;
if (memflags & AstNode::MEM2REG_FL_EQ2)
goto verbose_activate;
if (memflags & AstNode::MEM2REG_FL_SET_ASYNC)
goto verbose_activate;
if ((memflags & AstNode::MEM2REG_FL_SET_INIT) && (memflags & AstNode::MEM2REG_FL_SET_ELSE) && this_nomeminit)
goto verbose_activate;
if (memflags & AstNode::MEM2REG_FL_CMPLX_LHS)
goto verbose_activate;
if ((memflags & AstNode::MEM2REG_FL_CONST_LHS) && !(memflags & AstNode::MEM2REG_FL_VAR_LHS))
goto verbose_activate;
// log("Note: Not replacing memory %s with list of registers (flags=0x%08lx).\n", mem->str.c_str(), long(memflags));
continue;
verbose_activate:
if (mem2reg_set.count(mem) == 0) {
std::string message = stringf("Replacing memory %s with list of registers.", mem->str.c_str());
bool first_element = true;
for (auto &place : mem2reg_places[it.first]) {
message += stringf("%s%s", first_element ? " See " : ", ", place.c_str());
first_element = false;
}
log_warning("%s\n", message.c_str());
}
silent_activate:
// log("Note: Replacing memory %s with list of registers (flags=0x%08lx).\n", mem->str.c_str(), long(memflags));
mem2reg_set.insert(mem);
}
for (auto node : mem2reg_set)
{
int mem_width, mem_size, addr_bits;
node->meminfo(mem_width, mem_size, addr_bits);