-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathStatements.cpp
More file actions
1152 lines (1015 loc) · 43.7 KB
/
Statements.cpp
File metadata and controls
1152 lines (1015 loc) · 43.7 KB
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
//===- Statements.cpp - Slang statement conversion ------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "ImportVerilogInternals.h"
#include "circt/Dialect/Moore/MooreOps.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Diagnostics.h"
#include "slang/ast/Compilation.h"
#include "slang/ast/SemanticFacts.h"
#include "slang/ast/Statement.h"
#include "slang/ast/SystemSubroutine.h"
#include "llvm/ADT/ScopeExit.h"
using namespace mlir;
using namespace circt;
using namespace ImportVerilog;
// NOLINTBEGIN(misc-no-recursion)
namespace {
struct StmtVisitor {
Context &context;
Location loc;
OpBuilder &builder;
StmtVisitor(Context &context, Location loc)
: context(context), loc(loc), builder(context.builder) {}
bool isTerminated() const { return !builder.getInsertionBlock(); }
void setTerminated() { builder.clearInsertionPoint(); }
Block &createBlock() {
assert(builder.getInsertionBlock());
auto block = std::make_unique<Block>();
block->insertAfter(builder.getInsertionBlock());
return *block.release();
}
LogicalResult recursiveForeach(const slang::ast::ForeachLoopStatement &stmt,
uint32_t level) {
// find current dimension we are operate.
const auto &loopDim = stmt.loopDims[level];
if (!loopDim.range.has_value())
return mlir::emitError(loc) << "dynamic loop variable is unsupported";
auto &exitBlock = createBlock();
auto &stepBlock = createBlock();
auto &bodyBlock = createBlock();
auto &checkBlock = createBlock();
// Push the blocks onto the loop stack such that we can continue and break.
context.loopStack.push_back({&stepBlock, &exitBlock});
llvm::scope_exit done([&] { context.loopStack.pop_back(); });
const auto &iter = loopDim.loopVar;
auto type = context.convertType(*iter->getDeclaredType());
if (!type)
return failure();
Value initial = moore::ConstantOp::create(
builder, loc, cast<moore::IntType>(type), loopDim.range->lower());
// Create loop varirable in this dimension
Value varOp = moore::VariableOp::create(
builder, loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
builder.getStringAttr(iter->name), initial);
context.valueSymbols.insertIntoScope(context.valueSymbols.getCurScope(),
iter, varOp);
cf::BranchOp::create(builder, loc, &checkBlock);
builder.setInsertionPointToEnd(&checkBlock);
// When the loop variable is greater than the upper bound, goto exit
auto upperBound = moore::ConstantOp::create(
builder, loc, cast<moore::IntType>(type), loopDim.range->upper());
auto var = moore::ReadOp::create(builder, loc, varOp);
Value cond = moore::SleOp::create(builder, loc, var, upperBound);
if (!cond)
return failure();
cond = builder.createOrFold<moore::BoolCastOp>(loc, cond);
if (auto ty = dyn_cast<moore::IntType>(cond.getType());
ty && ty.getDomain() == Domain::FourValued) {
cond = moore::LogicToIntOp::create(builder, loc, cond);
}
cond = moore::ToBuiltinIntOp::create(builder, loc, cond);
cf::CondBranchOp::create(builder, loc, cond, &bodyBlock, &exitBlock);
builder.setInsertionPointToEnd(&bodyBlock);
// find next dimension in this foreach statement, it finded then recuersive
// resolve, else perform body statement
bool hasNext = false;
for (uint32_t nextLevel = level + 1; nextLevel < stmt.loopDims.size();
nextLevel++) {
if (stmt.loopDims[nextLevel].loopVar) {
if (failed(recursiveForeach(stmt, nextLevel)))
return failure();
hasNext = true;
break;
}
}
if (!hasNext) {
if (failed(context.convertStatement(stmt.body)))
return failure();
}
if (!isTerminated())
cf::BranchOp::create(builder, loc, &stepBlock);
builder.setInsertionPointToEnd(&stepBlock);
// add one to loop variable
var = moore::ReadOp::create(builder, loc, varOp);
auto one =
moore::ConstantOp::create(builder, loc, cast<moore::IntType>(type), 1);
auto postValue = moore::AddOp::create(builder, loc, var, one).getResult();
moore::BlockingAssignOp::create(builder, loc, varOp, postValue);
cf::BranchOp::create(builder, loc, &checkBlock);
if (exitBlock.hasNoPredecessors()) {
exitBlock.erase();
setTerminated();
} else {
builder.setInsertionPointToEnd(&exitBlock);
}
return success();
}
// Skip empty statements (stray semicolons).
LogicalResult visit(const slang::ast::EmptyStatement &) { return success(); }
// Convert every statement in a statement list. The Verilog syntax follows a
// similar philosophy as C/C++, where things like `if` and `for` accept a
// single statement as body. But then a `{...}` block is a valid statement,
// which allows for the `if {...}` syntax. In Verilog, things like `final`
// accept a single body statement, but that can be a `begin ... end` block,
// which in turn has a single body statement, which then commonly is a list of
// statements.
LogicalResult visit(const slang::ast::StatementList &stmts) {
for (auto *stmt : stmts.list) {
if (isTerminated()) {
auto loc = context.convertLocation(stmt->sourceRange);
mlir::emitWarning(loc, "unreachable code");
break;
}
if (failed(context.convertStatement(*stmt)))
return failure();
}
return success();
}
// Process slang BlockStatements. These comprise all standard `begin ... end`
// blocks as well as `fork ... join` constructs. Standard blocks can have
// their contents extracted directly, however fork-join blocks require special
// handling.
LogicalResult visit(const slang::ast::BlockStatement &stmt) {
moore::JoinKind kind;
switch (stmt.blockKind) {
case slang::ast::StatementBlockKind::Sequential:
// Inline standard `begin ... end` blocks into the parent.
return context.convertStatement(stmt.body);
case slang::ast::StatementBlockKind::JoinAll:
kind = moore::JoinKind::Join;
break;
case slang::ast::StatementBlockKind::JoinAny:
kind = moore::JoinKind::JoinAny;
break;
case slang::ast::StatementBlockKind::JoinNone:
kind = moore::JoinKind::JoinNone;
break;
}
// Slang stores all threads of a fork-join block inside a `StatementList`.
// This cannot be visited normally due to the need to make each statement a
// separate thread so must be converted here.
auto &threadList = stmt.body.as<slang::ast::StatementList>();
unsigned int threadCount = threadList.list.size();
auto forkOp = moore::ForkJoinOp::create(builder, loc, kind, threadCount);
OpBuilder::InsertionGuard guard(builder);
int i = 0;
for (auto *thread : threadList.list) {
auto &tBlock = forkOp->getRegion(i).emplaceBlock();
builder.setInsertionPointToStart(&tBlock);
// Populate thread operator with thread body and finish with a thread
// terminator.
if (failed(context.convertStatement(*thread)))
return failure();
moore::CompleteOp::create(builder, loc);
i++;
}
return success();
}
// Handle expression statements.
LogicalResult visit(const slang::ast::ExpressionStatement &stmt) {
// Special handling for calls to system tasks that return no result value.
if (const auto *call = stmt.expr.as_if<slang::ast::CallExpression>()) {
if (const auto *info =
std::get_if<slang::ast::CallExpression::SystemCallInfo>(
&call->subroutine)) {
auto handled = visitSystemCall(stmt, *call, *info);
if (failed(handled))
return failure();
if (handled == true)
return success();
}
// According to IEEE 1800-2023 Section 21.3.3 "Formatting data to a
// string" the first argument of $sformat/$swrite is its output; the
// other arguments work like a FormatString.
// In Moore we only support writing to a location if it is a reference;
// However, Section 21.3.3 explains that the output of $sformat/$swrite
// is assigned as if it were cast from a string literal (Section 5.9),
// so this implementation casts the string to the target value.
if (!call->getSubroutineName().compare("$sformat") ||
!call->getSubroutineName().compare("$swrite")) {
// Use the first argument as the output location
auto *lhsExpr = call->arguments().front();
// Format the second and all later arguments as a string
auto fmtValue =
context.convertFormatString(call->arguments().subspan(1), loc,
moore::IntFormat::Decimal, false);
if (failed(fmtValue))
return failure();
// Convert the FormatString to a StringType
auto strValue = moore::FormatStringToStringOp::create(builder, loc,
fmtValue.value());
// The Slang AST produces a `AssignmentExpression` for the first
// argument; the RHS of this expression is invalid though
// (`EmptyArgument`), so we only use the LHS of the
// `AssignmentExpression` and plug in the formatted string for the RHS.
if (auto assignExpr =
lhsExpr->as_if<slang::ast::AssignmentExpression>()) {
auto lhs = context.convertLvalueExpression(assignExpr->left());
if (!lhs)
return failure();
auto convertedValue = context.materializeConversion(
cast<moore::RefType>(lhs.getType()).getNestedType(), strValue,
false, loc);
moore::BlockingAssignOp::create(builder, loc, lhs, convertedValue);
return success();
} else {
return failure();
}
}
}
auto value = context.convertRvalueExpression(stmt.expr);
if (!value)
return failure();
// Expressions like calls to void functions return a dummy value that has no
// uses. If the returned value is trivially dead, remove it.
if (auto *defOp = value.getDefiningOp())
if (isOpTriviallyDead(defOp))
defOp->erase();
return success();
}
// Handle variable declarations.
LogicalResult visit(const slang::ast::VariableDeclStatement &stmt) {
const auto &var = stmt.symbol;
auto type = context.convertType(*var.getDeclaredType());
if (!type)
return failure();
Value initial;
if (const auto *init = var.getInitializer()) {
initial = context.convertRvalueExpression(*init, type);
if (!initial)
return failure();
}
// Collect local temporary variables.
auto varOp = moore::VariableOp::create(
builder, loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
builder.getStringAttr(var.name), initial);
context.valueSymbols.insertIntoScope(context.valueSymbols.getCurScope(),
&var, varOp);
return success();
}
// Handle if statements.
LogicalResult visit(const slang::ast::ConditionalStatement &stmt) {
// Generate the condition. There may be multiple conditions linked with the
// `&&&` operator.
Value allConds;
for (const auto &condition : stmt.conditions) {
if (condition.pattern)
return mlir::emitError(loc,
"match patterns in if conditions not supported");
auto cond = context.convertRvalueExpression(*condition.expr);
if (!cond)
return failure();
cond = builder.createOrFold<moore::BoolCastOp>(loc, cond);
if (allConds)
allConds = moore::AndOp::create(builder, loc, allConds, cond);
else
allConds = cond;
}
assert(allConds && "slang guarantees at least one condition");
if (auto ty = dyn_cast<moore::IntType>(allConds.getType());
ty && ty.getDomain() == Domain::FourValued) {
allConds = moore::LogicToIntOp::create(builder, loc, allConds);
}
allConds = moore::ToBuiltinIntOp::create(builder, loc, allConds);
// Create the blocks for the true and false branches, and the exit block.
Block &exitBlock = createBlock();
Block *falseBlock = stmt.ifFalse ? &createBlock() : nullptr;
Block &trueBlock = createBlock();
cf::CondBranchOp::create(builder, loc, allConds, &trueBlock,
falseBlock ? falseBlock : &exitBlock);
// Generate the true branch.
builder.setInsertionPointToEnd(&trueBlock);
if (failed(context.convertStatement(stmt.ifTrue)))
return failure();
if (!isTerminated())
cf::BranchOp::create(builder, loc, &exitBlock);
// Generate the false branch if present.
if (stmt.ifFalse) {
builder.setInsertionPointToEnd(falseBlock);
if (failed(context.convertStatement(*stmt.ifFalse)))
return failure();
if (!isTerminated())
cf::BranchOp::create(builder, loc, &exitBlock);
}
// If control never reaches the exit block, remove it and mark control flow
// as terminated. Otherwise we continue inserting ops in the exit block.
if (exitBlock.hasNoPredecessors()) {
exitBlock.erase();
setTerminated();
} else {
builder.setInsertionPointToEnd(&exitBlock);
}
return success();
}
/// Handle case statements.
LogicalResult visit(const slang::ast::CaseStatement &caseStmt) {
using slang::ast::AttributeSymbol;
using slang::ast::CaseStatementCondition;
auto caseExpr = context.convertRvalueExpression(caseStmt.expr);
if (!caseExpr)
return failure();
// Check each case individually. This currently ignores the `unique`,
// `unique0`, and `priority` modifiers which would allow for additional
// optimizations.
auto &exitBlock = createBlock();
Block *lastMatchBlock = nullptr;
SmallVector<moore::FVIntegerAttr> itemConsts;
for (const auto &item : caseStmt.items) {
// Create the block that will contain the main body of the expression.
// This is where any of the comparisons will branch to if they match.
auto &matchBlock = createBlock();
lastMatchBlock = &matchBlock;
// The SV standard requires expressions to be checked in the order
// specified by the user, and for the evaluation to stop as soon as the
// first matching expression is encountered.
for (const auto *expr : item.expressions) {
auto value = context.convertRvalueExpression(*expr);
if (!value)
return failure();
auto itemLoc = value.getLoc();
// Take note if the expression is a constant.
auto maybeConst = value;
while (isa_and_nonnull<moore::ConversionOp, moore::IntToLogicOp,
moore::LogicToIntOp>(maybeConst.getDefiningOp()))
maybeConst = maybeConst.getDefiningOp()->getOperand(0);
if (auto defOp = maybeConst.getDefiningOp<moore::ConstantOp>())
itemConsts.push_back(defOp.getValueAttr());
// Generate the appropriate equality operator.
Value cond;
switch (caseStmt.condition) {
case CaseStatementCondition::Normal:
cond = moore::CaseEqOp::create(builder, itemLoc, caseExpr, value);
break;
case CaseStatementCondition::WildcardXOrZ:
cond = moore::CaseXZEqOp::create(builder, itemLoc, caseExpr, value);
break;
case CaseStatementCondition::WildcardJustZ:
cond = moore::CaseZEqOp::create(builder, itemLoc, caseExpr, value);
break;
case CaseStatementCondition::Inside:
mlir::emitError(loc, "unsupported set membership case statement");
return failure();
}
if (auto ty = dyn_cast<moore::IntType>(cond.getType());
ty && ty.getDomain() == Domain::FourValued) {
cond = moore::LogicToIntOp::create(builder, loc, cond);
}
cond = moore::ToBuiltinIntOp::create(builder, loc, cond);
// If the condition matches, branch to the match block. Otherwise
// continue checking the next expression in a new block.
auto &nextBlock = createBlock();
mlir::cf::CondBranchOp::create(builder, itemLoc, cond, &matchBlock,
&nextBlock);
builder.setInsertionPointToEnd(&nextBlock);
}
// The current block is the fall-through after all conditions have been
// checked and nothing matched. Move the match block up before this point
// to make the IR easier to read.
matchBlock.moveBefore(builder.getInsertionBlock());
// Generate the code for this item's statement in the match block.
OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPointToEnd(&matchBlock);
if (failed(context.convertStatement(*item.stmt)))
return failure();
if (!isTerminated()) {
auto loc = context.convertLocation(item.stmt->sourceRange);
mlir::cf::BranchOp::create(builder, loc, &exitBlock);
}
}
const auto caseStmtAttrs = context.compilation.getAttributes(caseStmt);
const bool hasFullCaseAttr =
llvm::find_if(caseStmtAttrs, [](const AttributeSymbol *attr) {
return attr->name == "full_case";
}) != caseStmtAttrs.end();
// Check if the case statement looks exhaustive assuming two-state values.
// We use this information to work around a common bug in input Verilog
// where a case statement enumerates all possible two-state values of the
// case expression, but forgets to deal with cases involving X and Z bits in
// the input.
//
// Once the core dialects start supporting four-state values we may want to
// tuck this behind an import option that is on by default, since it does
// not preserve semantics.
auto twoStateExhaustive = false;
if (auto intType = dyn_cast<moore::IntType>(caseExpr.getType());
intType && intType.getWidth() < 32 &&
itemConsts.size() == (1 << intType.getWidth())) {
// Sort the constants by value.
llvm::sort(itemConsts, [](auto a, auto b) {
return a.getValue().getRawValue().ult(b.getValue().getRawValue());
});
// Ensure that every possible value of the case expression is present. Do
// this by starting at 0 and iterating over all sorted items. Each item
// must be the previous item + 1. At the end, the addition must exactly
// overflow and take us back to zero.
auto nextValue = FVInt::getZero(intType.getWidth());
for (auto value : itemConsts) {
if (value.getValue() != nextValue)
break;
nextValue += 1;
}
twoStateExhaustive = nextValue.isZero();
}
// If the case statement is exhaustive assuming two-state values, don't
// generate the default case. Instead, branch to the last match block. This
// will essentially make the last case item the "default".
//
// Alternatively, if the case statement has an (* full_case *) attribute
// but no default case, it indicates that the developer has intentionally
// covered all known possible values. Hence, the last match block is
// treated as the implicit "default" case.
if ((twoStateExhaustive || (hasFullCaseAttr && !caseStmt.defaultCase)) &&
lastMatchBlock &&
caseStmt.condition == CaseStatementCondition::Normal) {
mlir::cf::BranchOp::create(builder, loc, lastMatchBlock);
} else {
// Generate the default case if present.
if (caseStmt.defaultCase)
if (failed(context.convertStatement(*caseStmt.defaultCase)))
return failure();
if (!isTerminated())
mlir::cf::BranchOp::create(builder, loc, &exitBlock);
}
// If control never reaches the exit block, remove it and mark control flow
// as terminated. Otherwise we continue inserting ops in the exit block.
if (exitBlock.hasNoPredecessors()) {
exitBlock.erase();
setTerminated();
} else {
builder.setInsertionPointToEnd(&exitBlock);
}
return success();
}
// Handle `for` loops.
LogicalResult visit(const slang::ast::ForLoopStatement &stmt) {
// Generate the initializers.
for (auto *initExpr : stmt.initializers)
if (!context.convertRvalueExpression(*initExpr))
return failure();
// Create the blocks for the loop condition, body, step, and exit.
auto &exitBlock = createBlock();
auto &stepBlock = createBlock();
auto &bodyBlock = createBlock();
auto &checkBlock = createBlock();
cf::BranchOp::create(builder, loc, &checkBlock);
// Push the blocks onto the loop stack such that we can continue and break.
context.loopStack.push_back({&stepBlock, &exitBlock});
llvm::scope_exit done([&] { context.loopStack.pop_back(); });
// Generate the loop condition check.
builder.setInsertionPointToEnd(&checkBlock);
auto cond = context.convertRvalueExpression(*stmt.stopExpr);
if (!cond)
return failure();
cond = builder.createOrFold<moore::BoolCastOp>(loc, cond);
if (auto ty = dyn_cast<moore::IntType>(cond.getType());
ty && ty.getDomain() == Domain::FourValued) {
cond = moore::LogicToIntOp::create(builder, loc, cond);
}
cond = moore::ToBuiltinIntOp::create(builder, loc, cond);
cf::CondBranchOp::create(builder, loc, cond, &bodyBlock, &exitBlock);
// Generate the loop body.
builder.setInsertionPointToEnd(&bodyBlock);
if (failed(context.convertStatement(stmt.body)))
return failure();
if (!isTerminated())
cf::BranchOp::create(builder, loc, &stepBlock);
// Generate the step expressions.
builder.setInsertionPointToEnd(&stepBlock);
for (auto *stepExpr : stmt.steps)
if (!context.convertRvalueExpression(*stepExpr))
return failure();
if (!isTerminated())
cf::BranchOp::create(builder, loc, &checkBlock);
// If control never reaches the exit block, remove it and mark control flow
// as terminated. Otherwise we continue inserting ops in the exit block.
if (exitBlock.hasNoPredecessors()) {
exitBlock.erase();
setTerminated();
} else {
builder.setInsertionPointToEnd(&exitBlock);
}
return success();
}
LogicalResult visit(const slang::ast::ForeachLoopStatement &stmt) {
for (uint32_t level = 0; level < stmt.loopDims.size(); level++) {
if (stmt.loopDims[level].loopVar)
return recursiveForeach(stmt, level);
}
return success();
}
// Handle `repeat` loops.
LogicalResult visit(const slang::ast::RepeatLoopStatement &stmt) {
auto count = context.convertRvalueExpression(stmt.count);
if (!count)
return failure();
// Create the blocks for the loop condition, body, step, and exit.
auto &exitBlock = createBlock();
auto &stepBlock = createBlock();
auto &bodyBlock = createBlock();
auto &checkBlock = createBlock();
auto currentCount = checkBlock.addArgument(count.getType(), count.getLoc());
cf::BranchOp::create(builder, loc, &checkBlock, count);
// Push the blocks onto the loop stack such that we can continue and break.
context.loopStack.push_back({&stepBlock, &exitBlock});
llvm::scope_exit done([&] { context.loopStack.pop_back(); });
// Generate the loop condition check.
builder.setInsertionPointToEnd(&checkBlock);
auto cond = builder.createOrFold<moore::BoolCastOp>(loc, currentCount);
if (auto ty = dyn_cast<moore::IntType>(cond.getType());
ty && ty.getDomain() == Domain::FourValued) {
cond = moore::LogicToIntOp::create(builder, loc, cond);
}
cond = moore::ToBuiltinIntOp::create(builder, loc, cond);
cf::CondBranchOp::create(builder, loc, cond, &bodyBlock, &exitBlock);
// Generate the loop body.
builder.setInsertionPointToEnd(&bodyBlock);
if (failed(context.convertStatement(stmt.body)))
return failure();
if (!isTerminated())
cf::BranchOp::create(builder, loc, &stepBlock);
// Decrement the current count and branch back to the check block.
builder.setInsertionPointToEnd(&stepBlock);
auto one = moore::ConstantOp::create(
builder, count.getLoc(), cast<moore::IntType>(count.getType()), 1);
Value nextCount =
moore::SubOp::create(builder, count.getLoc(), currentCount, one);
cf::BranchOp::create(builder, loc, &checkBlock, nextCount);
// If control never reaches the exit block, remove it and mark control flow
// as terminated. Otherwise we continue inserting ops in the exit block.
if (exitBlock.hasNoPredecessors()) {
exitBlock.erase();
setTerminated();
} else {
builder.setInsertionPointToEnd(&exitBlock);
}
return success();
}
// Handle `while` and `do-while` loops.
LogicalResult createWhileLoop(const slang::ast::Expression &condExpr,
const slang::ast::Statement &bodyStmt,
bool atLeastOnce) {
// Create the blocks for the loop condition, body, and exit.
auto &exitBlock = createBlock();
auto &bodyBlock = createBlock();
auto &checkBlock = createBlock();
cf::BranchOp::create(builder, loc, atLeastOnce ? &bodyBlock : &checkBlock);
if (atLeastOnce)
bodyBlock.moveBefore(&checkBlock);
// Push the blocks onto the loop stack such that we can continue and break.
context.loopStack.push_back({&checkBlock, &exitBlock});
llvm::scope_exit done([&] { context.loopStack.pop_back(); });
// Generate the loop condition check.
builder.setInsertionPointToEnd(&checkBlock);
auto cond = context.convertRvalueExpression(condExpr);
if (!cond)
return failure();
cond = builder.createOrFold<moore::BoolCastOp>(loc, cond);
if (auto ty = dyn_cast<moore::IntType>(cond.getType());
ty && ty.getDomain() == Domain::FourValued) {
cond = moore::LogicToIntOp::create(builder, loc, cond);
}
cond = moore::ToBuiltinIntOp::create(builder, loc, cond);
cf::CondBranchOp::create(builder, loc, cond, &bodyBlock, &exitBlock);
// Generate the loop body.
builder.setInsertionPointToEnd(&bodyBlock);
if (failed(context.convertStatement(bodyStmt)))
return failure();
if (!isTerminated())
cf::BranchOp::create(builder, loc, &checkBlock);
// If control never reaches the exit block, remove it and mark control flow
// as terminated. Otherwise we continue inserting ops in the exit block.
if (exitBlock.hasNoPredecessors()) {
exitBlock.erase();
setTerminated();
} else {
builder.setInsertionPointToEnd(&exitBlock);
}
return success();
}
LogicalResult visit(const slang::ast::WhileLoopStatement &stmt) {
return createWhileLoop(stmt.cond, stmt.body, false);
}
LogicalResult visit(const slang::ast::DoWhileLoopStatement &stmt) {
return createWhileLoop(stmt.cond, stmt.body, true);
}
// Handle `forever` loops.
LogicalResult visit(const slang::ast::ForeverLoopStatement &stmt) {
// Create the blocks for the loop body and exit.
auto &exitBlock = createBlock();
auto &bodyBlock = createBlock();
cf::BranchOp::create(builder, loc, &bodyBlock);
// Push the blocks onto the loop stack such that we can continue and break.
context.loopStack.push_back({&bodyBlock, &exitBlock});
llvm::scope_exit done([&] { context.loopStack.pop_back(); });
// Generate the loop body.
builder.setInsertionPointToEnd(&bodyBlock);
if (failed(context.convertStatement(stmt.body)))
return failure();
if (!isTerminated())
cf::BranchOp::create(builder, loc, &bodyBlock);
// If control never reaches the exit block, remove it and mark control flow
// as terminated. Otherwise we continue inserting ops in the exit block.
if (exitBlock.hasNoPredecessors()) {
exitBlock.erase();
setTerminated();
} else {
builder.setInsertionPointToEnd(&exitBlock);
}
return success();
}
// Handle timing control.
LogicalResult visit(const slang::ast::TimedStatement &stmt) {
return context.convertTimingControl(stmt.timing, stmt.stmt);
}
// Handle return statements.
LogicalResult visit(const slang::ast::ReturnStatement &stmt) {
if (stmt.expr) {
auto expr = context.convertRvalueExpression(*stmt.expr);
if (!expr)
return failure();
mlir::func::ReturnOp::create(builder, loc, expr);
} else {
mlir::func::ReturnOp::create(builder, loc);
}
setTerminated();
return success();
}
// Handle continue statements.
LogicalResult visit(const slang::ast::ContinueStatement &stmt) {
if (context.loopStack.empty())
return mlir::emitError(loc,
"cannot `continue` without a surrounding loop");
cf::BranchOp::create(builder, loc, context.loopStack.back().continueBlock);
setTerminated();
return success();
}
// Handle break statements.
LogicalResult visit(const slang::ast::BreakStatement &stmt) {
if (context.loopStack.empty())
return mlir::emitError(loc, "cannot `break` without a surrounding loop");
cf::BranchOp::create(builder, loc, context.loopStack.back().breakBlock);
setTerminated();
return success();
}
// Handle immediate assertion statements.
LogicalResult visit(const slang::ast::ImmediateAssertionStatement &stmt) {
auto cond = context.convertRvalueExpression(stmt.cond);
cond = context.convertToBool(cond);
if (!cond)
return failure();
// Handle assertion statements that don't have an action block.
if (stmt.ifTrue && stmt.ifTrue->as_if<slang::ast::EmptyStatement>()) {
auto defer = moore::DeferAssert::Immediate;
if (stmt.isFinal)
defer = moore::DeferAssert::Final;
else if (stmt.isDeferred)
defer = moore::DeferAssert::Observed;
switch (stmt.assertionKind) {
case slang::ast::AssertionKind::Assert:
moore::AssertOp::create(builder, loc, defer, cond, StringAttr{});
return success();
case slang::ast::AssertionKind::Assume:
moore::AssumeOp::create(builder, loc, defer, cond, StringAttr{});
return success();
case slang::ast::AssertionKind::CoverProperty:
moore::CoverOp::create(builder, loc, defer, cond, StringAttr{});
return success();
default:
break;
}
mlir::emitError(loc) << "unsupported immediate assertion kind: "
<< slang::ast::toString(stmt.assertionKind);
return failure();
}
// Regard assertion statements with an action block as the "if-else".
if (auto ty = dyn_cast<moore::IntType>(cond.getType());
ty && ty.getDomain() == Domain::FourValued) {
cond = moore::LogicToIntOp::create(builder, loc, cond);
}
cond = moore::ToBuiltinIntOp::create(builder, loc, cond);
// Create the blocks for the true and false branches, and the exit block.
Block &exitBlock = createBlock();
Block *falseBlock = stmt.ifFalse ? &createBlock() : nullptr;
Block &trueBlock = createBlock();
cf::CondBranchOp::create(builder, loc, cond, &trueBlock,
falseBlock ? falseBlock : &exitBlock);
// Generate the true branch.
builder.setInsertionPointToEnd(&trueBlock);
if (stmt.ifTrue && failed(context.convertStatement(*stmt.ifTrue)))
return failure();
if (!isTerminated())
cf::BranchOp::create(builder, loc, &exitBlock);
if (stmt.ifFalse) {
// Generate the false branch if present.
builder.setInsertionPointToEnd(falseBlock);
if (failed(context.convertStatement(*stmt.ifFalse)))
return failure();
if (!isTerminated())
cf::BranchOp::create(builder, loc, &exitBlock);
}
// If control never reaches the exit block, remove it and mark control flow
// as terminated. Otherwise we continue inserting ops in the exit block.
if (exitBlock.hasNoPredecessors()) {
exitBlock.erase();
setTerminated();
} else {
builder.setInsertionPointToEnd(&exitBlock);
}
return success();
}
// Handle concurrent assertion statements.
LogicalResult visit(const slang::ast::ConcurrentAssertionStatement &stmt) {
auto loc = context.convertLocation(stmt.sourceRange);
// Check for a `disable iff` expression:
// The DisableIff construct can only occcur at the top level of an assertion
// and cannot be nested within properties.
// Hence we only need to detect if the top level assertion expression
// has type DisableIff, negate the `disable` expression, then pass it to
// the `enable` parameter of AssertOp/AssumeOp.
Value enable;
Value property;
if (auto *disableIff =
stmt.propertySpec.as_if<slang::ast::DisableIffAssertionExpr>()) {
auto disableCond = context.convertRvalueExpression(disableIff->condition);
auto enableCond = moore::NotOp::create(builder, loc, disableCond);
enable = context.convertToI1(enableCond);
property = context.convertAssertionExpression(disableIff->expr, loc);
} else {
property = context.convertAssertionExpression(stmt.propertySpec, loc);
}
if (!property)
return failure();
// Handle assertion statements that don't have an action block.
if (stmt.ifTrue && stmt.ifTrue->as_if<slang::ast::EmptyStatement>()) {
switch (stmt.assertionKind) {
case slang::ast::AssertionKind::Assert:
verif::AssertOp::create(builder, loc, property, enable, StringAttr{});
return success();
case slang::ast::AssertionKind::Assume:
verif::AssumeOp::create(builder, loc, property, enable, StringAttr{});
return success();
default:
break;
}
mlir::emitError(loc) << "unsupported concurrent assertion kind: "
<< slang::ast::toString(stmt.assertionKind);
return failure();
}
mlir::emitError(loc)
<< "concurrent assertion statements with action blocks "
"are not supported yet";
return failure();
}
// According to 1800-2023 Section 21.2.1 "The display and write tasks":
// >> The $display and $write tasks display their arguments in the same
// >> order as they appear in the argument list. Each argument can be a
// >> string literal or an expression that returns a value.
// According to Section 20.10 "Severity system tasks", the same
// semantics apply to $fatal, $error, $warning, and $info.
// This means we must first check whether the first "string-able"
// argument is a Literal Expression which doesn't represent a fully-formatted
// string, otherwise we convert it to a FormatStringType.
FailureOr<Value>
getDisplayMessage(std::span<const slang::ast::Expression *const> args) {
if (args.size() == 0)
return Value{};
// Handle the string formatting.
// If the second argument is a Literal of some type, we should either
// treat it as a literal-to-be-formatted or a FormatStringType.
// In this check we use a StringLiteral, but slang allows casting between
// any literal expressions (strings, integers, reals, and time at least) so
// this is short-hand for "any value literal"
if (args[0]->as_if<slang::ast::StringLiteral>()) {
return context.convertFormatString(args, loc);
}
// Check if there's only one argument and it's a FormatStringType
if (args.size() == 1) {
return context.convertRvalueExpression(
*args[0], builder.getType<moore::FormatStringType>());
}
// Otherwise this looks invalid. Raise an error.
return emitError(loc) << "Failed to convert Display Message!";
}
/// Handle the subset of system calls that return no result value. Return
/// true if the called system task could be handled, false otherwise. Return
/// failure if an error occurred.
FailureOr<bool>
visitSystemCall(const slang::ast::ExpressionStatement &stmt,
const slang::ast::CallExpression &expr,
const slang::ast::CallExpression::SystemCallInfo &info) {
const auto &subroutine = *info.subroutine;
auto args = expr.arguments();
// Simulation Control Tasks
if (subroutine.name == "$stop") {
createFinishMessage(args.size() >= 1 ? args[0] : nullptr);
moore::StopBIOp::create(builder, loc);
return true;
}
if (subroutine.name == "$finish") {
createFinishMessage(args.size() >= 1 ? args[0] : nullptr);
moore::FinishBIOp::create(builder, loc, 0);
moore::UnreachableOp::create(builder, loc);
setTerminated();
return true;
}
if (subroutine.name == "$exit") {
// Calls to `$exit` from outside a `program` are ignored. Since we don't
// yet support programs, there is nothing to do here.
// TODO: Fix this once we support programs.
return true;
}
// Display and Write Tasks (`$display[boh]?` or `$write[boh]?`)
// Check for a `$display` or `$write` prefix.
bool isDisplay = false; // display or write
bool appendNewline = false; // display
StringRef remainingName = subroutine.name;
if (remainingName.consume_front("$display")) {
isDisplay = true;
appendNewline = true;
} else if (remainingName.consume_front("$write")) {
isDisplay = true;
}
// Check for optional `b`, `o`, or `h` suffix indicating default format.
using moore::IntFormat;
IntFormat defaultFormat = IntFormat::Decimal;
if (isDisplay && !remainingName.empty()) {
if (remainingName == "b")
defaultFormat = IntFormat::Binary;
else if (remainingName == "o")
defaultFormat = IntFormat::Octal;
else if (remainingName == "h")
defaultFormat = IntFormat::HexLower;
else
isDisplay = false;
}
if (isDisplay) {
auto message =
context.convertFormatString(args, loc, defaultFormat, appendNewline);
if (failed(message))
return failure();
if (*message == Value{})
return true;
moore::DisplayBIOp::create(builder, loc, *message);
return true;
}
// Severity Tasks
using moore::Severity;
std::optional<Severity> severity;
if (subroutine.name == "$info")
severity = Severity::Info;
else if (subroutine.name == "$warning")
severity = Severity::Warning;
else if (subroutine.name == "$error")
severity = Severity::Error;
else if (subroutine.name == "$fatal")
severity = Severity::Fatal;
if (severity) {
// The `$fatal` task has an optional leading verbosity argument.
const slang::ast::Expression *verbosityExpr = nullptr;
if (severity == Severity::Fatal && args.size() >= 1) {
verbosityExpr = args[0];
args = args.subspan(1);
}
FailureOr<Value> maybeMessage = getDisplayMessage(args);
if (failed(maybeMessage))
return failure();
auto message = maybeMessage.value();
if (message == Value{})
message = moore::FormatLiteralOp::create(builder, loc, "");
moore::SeverityBIOp::create(builder, loc, *severity, message);