-
Notifications
You must be signed in to change notification settings - Fork 444
Expand file tree
/
Copy pathExpressions.cpp
More file actions
3354 lines (2927 loc) · 127 KB
/
Expressions.cpp
File metadata and controls
3354 lines (2927 loc) · 127 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
//===- Expressions.cpp - Slang expression 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/MooreTypes.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/Value.h"
#include "slang/ast/EvalContext.h"
#include "slang/ast/SystemSubroutine.h"
#include "slang/ast/types/AllTypes.h"
#include "slang/syntax/AllSyntax.h"
#include "llvm/ADT/ScopeExit.h"
using namespace circt;
using namespace ImportVerilog;
using moore::Domain;
/// Convert a Slang `SVInt` to a CIRCT `FVInt`.
static FVInt convertSVIntToFVInt(const slang::SVInt &svint) {
if (svint.hasUnknown()) {
unsigned numWords = svint.getNumWords() / 2;
auto value = ArrayRef<uint64_t>(svint.getRawPtr(), numWords);
auto unknown = ArrayRef<uint64_t>(svint.getRawPtr() + numWords, numWords);
return FVInt(APInt(svint.getBitWidth(), value),
APInt(svint.getBitWidth(), unknown));
}
auto value = ArrayRef<uint64_t>(svint.getRawPtr(), svint.getNumWords());
return FVInt(APInt(svint.getBitWidth(), value));
}
/// Map an index into an array, with bounds `range`, to a bit offset of the
/// underlying bit storage. This is a dynamic version of
/// `slang::ConstantRange::translateIndex`.
static Value getSelectIndex(Context &context, Location loc, Value index,
const slang::ConstantRange &range) {
auto &builder = context.builder;
auto indexType = cast<moore::UnpackedType>(index.getType());
// Compute offset first so we know if it is negative.
auto lo = range.lower();
auto hi = range.upper();
auto offset = range.isLittleEndian() ? lo : hi;
// If any bound is negative we need a signed index type.
const bool needSigned = (lo < 0) || (hi < 0);
// Magnitude over full range, not just the chosen offset.
const uint64_t maxAbs = std::max<uint64_t>(std::abs(lo), std::abs(hi));
// Bits needed from the range:
// - unsigned: ceil(log2(maxAbs + 1)) (ensure at least 1)
// - signed: ceil(log2(maxAbs)) + 1 sign bit (ensure at least 2 when neg)
unsigned want = needSigned
? (llvm::Log2_64_Ceil(std::max<uint64_t>(1, maxAbs)) + 1)
: std::max<unsigned>(1, llvm::Log2_64_Ceil(maxAbs + 1));
// Keep at least as wide as the incoming index.
const unsigned bw = std::max<unsigned>(want, indexType.getBitSize().value());
auto intType =
moore::IntType::get(index.getContext(), bw, indexType.getDomain());
index = context.materializeConversion(intType, index, needSigned, loc);
if (offset == 0) {
if (range.isLittleEndian())
return index;
else
return moore::NegOp::create(builder, loc, index);
}
auto offsetConst =
moore::ConstantOp::create(builder, loc, intType, offset, needSigned);
if (range.isLittleEndian())
return moore::SubOp::create(builder, loc, index, offsetConst);
else
return moore::SubOp::create(builder, loc, offsetConst, index);
}
/// Get the currently active timescale as an integer number of femtoseconds.
static uint64_t getTimeScaleInFemtoseconds(Context &context) {
static_assert(int(slang::TimeUnit::Seconds) == 0);
static_assert(int(slang::TimeUnit::Milliseconds) == 1);
static_assert(int(slang::TimeUnit::Microseconds) == 2);
static_assert(int(slang::TimeUnit::Nanoseconds) == 3);
static_assert(int(slang::TimeUnit::Picoseconds) == 4);
static_assert(int(slang::TimeUnit::Femtoseconds) == 5);
static_assert(int(slang::TimeScaleMagnitude::One) == 1);
static_assert(int(slang::TimeScaleMagnitude::Ten) == 10);
static_assert(int(slang::TimeScaleMagnitude::Hundred) == 100);
auto exp = static_cast<unsigned>(context.timeScale.base.unit);
assert(exp <= 5);
exp = 5 - exp;
auto scale = static_cast<uint64_t>(context.timeScale.base.magnitude);
while (exp-- > 0)
scale *= 1000;
return scale;
}
static Value visitClassProperty(Context &context,
const slang::ast::ClassPropertySymbol &expr) {
auto loc = context.convertLocation(expr.location);
auto builder = context.builder;
auto type = context.convertType(expr.getType());
auto fieldTy = cast<moore::UnpackedType>(type);
auto fieldRefTy = moore::RefType::get(fieldTy);
if (expr.lifetime == slang::ast::VariableLifetime::Static) {
// Variable may or may not have been hoisted already. Hoist if not.
if (!context.globalVariables.lookup(&expr)) {
if (failed(context.convertGlobalVariable(expr))) {
return {};
}
}
// Try the static variable after it has been hoisted.
if (auto globalOp = context.globalVariables.lookup(&expr))
return moore::GetGlobalVariableOp::create(builder, loc, globalOp);
mlir::emitError(loc) << "Failed to access static member variable "
<< expr.name << " as a global variable";
return {};
}
// Get the scope's implicit this variable
mlir::Value instRef = context.getImplicitThisRef();
if (!instRef) {
mlir::emitError(loc) << "class property '" << expr.name
<< "' referenced without an implicit 'this'";
return {};
}
auto fieldSym = mlir::FlatSymbolRefAttr::get(builder.getContext(), expr.name);
moore::ClassHandleType classTy =
cast<moore::ClassHandleType>(instRef.getType());
auto targetClassHandle =
context.getAncestorClassWithProperty(classTy, expr.name, loc);
if (!targetClassHandle)
return {};
auto upcastRef = context.materializeConversion(targetClassHandle, instRef,
false, instRef.getLoc());
if (!upcastRef)
return {};
Value fieldRef = moore::ClassPropertyRefOp::create(builder, loc, fieldRefTy,
upcastRef, fieldSym);
return fieldRef;
}
namespace {
/// A visitor handling expressions that can be lowered as lvalue and rvalue.
struct ExprVisitor {
Context &context;
Location loc;
OpBuilder &builder;
bool isLvalue;
ExprVisitor(Context &context, Location loc, bool isLvalue)
: context(context), loc(loc), builder(context.builder),
isLvalue(isLvalue) {}
/// Convert an expression either as an lvalue or rvalue, depending on whether
/// this is an lvalue or rvalue visitor. This is useful for projections such
/// as `a[i]`, where you want `a` as an lvalue if you want `a[i]` as an
/// lvalue, or `a` as an rvalue if you want `a[i]` as an rvalue.
Value convertLvalueOrRvalueExpression(const slang::ast::Expression &expr) {
if (isLvalue)
return context.convertLvalueExpression(expr);
return context.convertRvalueExpression(expr);
}
/// Materialize the rvalue of a symbol, regardless of whether it is backed by
/// a local reference, global variable, or class property.
Value materializeSymbolRvalue(const slang::ast::ValueSymbol &sym) {
if (auto value = context.valueSymbols.lookup(&sym)) {
if (isa<moore::RefType>(value.getType())) {
auto readOp = moore::ReadOp::create(builder, loc, value);
if (context.rvalueReadCallback)
context.rvalueReadCallback(readOp);
return readOp.getResult();
}
return value;
}
if (auto globalOp = context.globalVariables.lookup(&sym)) {
auto ref = moore::GetGlobalVariableOp::create(builder, loc, globalOp);
auto readOp = moore::ReadOp::create(builder, loc, ref);
if (context.rvalueReadCallback)
context.rvalueReadCallback(readOp);
return readOp.getResult();
}
if (auto *const property = sym.as_if<slang::ast::ClassPropertySymbol>()) {
auto fieldRef = visitClassProperty(context, *property);
auto readOp = moore::ReadOp::create(builder, loc, fieldRef);
if (context.rvalueReadCallback)
context.rvalueReadCallback(readOp);
return readOp.getResult();
}
return {};
}
Value visit(const slang::ast::NewArrayExpression &expr) {
Type type = context.convertType(*expr.type);
// TODO: Handle 'initExpr' if it exists
if (expr.initExpr()) {
mlir::emitError(loc)
<< "unsupported expression: array `new` with initializer\n";
return {};
}
auto initialSize = context.convertRvalueExpression(
expr.sizeExpr(), context.convertType(*expr.sizeExpr().type));
if (!initialSize)
return {};
return moore::OpenUArrayCreateOp::create(builder, loc, type, initialSize);
}
/// Handle single bit selections.
Value visit(const slang::ast::ElementSelectExpression &expr) {
auto type = context.convertType(*expr.type);
auto value = convertLvalueOrRvalueExpression(expr.value());
if (!type || !value)
return {};
// We only support indexing into a few select types for now.
auto derefType = value.getType();
if (isLvalue)
derefType = cast<moore::RefType>(derefType).getNestedType();
if (!isa<moore::IntType, moore::ArrayType, moore::UnpackedArrayType,
moore::QueueType, moore::AssocArrayType, moore::StringType,
moore::OpenUnpackedArrayType>(derefType)) {
mlir::emitError(loc) << "unsupported expression: element select into "
<< expr.value().type->toString() << "\n";
return {};
}
// Associative Arrays are a special case so handle them separately.
if (isa<moore::AssocArrayType>(derefType)) {
auto assocArray = cast<moore::AssocArrayType>(derefType);
auto expectedIndexType = assocArray.getIndexType();
auto givenIndex = context.convertRvalueExpression(expr.selector());
if (!givenIndex)
return {};
if (givenIndex.getType() != expectedIndexType) {
mlir::emitError(loc)
<< "Incorrect index type: expected index type of "
<< expectedIndexType << " but was given " << givenIndex.getType();
}
if (isLvalue)
return moore::AssocArrayExtractRefOp::create(
builder, loc, moore::RefType::get(cast<moore::UnpackedType>(type)),
value, givenIndex);
return moore::AssocArrayExtractOp::create(builder, loc, type, value,
givenIndex);
}
// Handle string indexing.
if (isa<moore::StringType>(derefType)) {
if (isLvalue) {
mlir::emitError(loc) << "string index assignment not supported";
return {};
}
// Convert the index to an rvalue with the required type (TwoValuedI32).
auto i32Type = moore::IntType::getInt(builder.getContext(), 32);
auto index = context.convertRvalueExpression(expr.selector(), i32Type);
if (!index)
return {};
// Create the StringGetOp operation.
return moore::StringGetOp::create(builder, loc, value, index);
}
auto resultType =
isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
auto range = expr.value().type->getFixedRange();
if (auto *constValue = expr.selector().getConstant();
constValue && constValue->isInteger()) {
assert(!constValue->hasUnknown());
assert(constValue->size() <= 32);
auto lowBit = constValue->integer().as<uint32_t>().value();
if (isLvalue)
return llvm::TypeSwitch<Type, Value>(derefType)
.Case<moore::QueueType>([&](moore::QueueType) {
mlir::emitError(loc)
<< "Unexpected LValue extract on Queue Type!";
return Value();
})
.Default([&](Type) {
return moore::ExtractRefOp::create(builder, loc, resultType,
value,
range.translateIndex(lowBit));
});
else
return llvm::TypeSwitch<Type, Value>(derefType)
.Case<moore::QueueType>([&](moore::QueueType) {
mlir::emitError(loc)
<< "Unexpected RValue extract on Queue Type!";
return Value();
})
.Default([&](Type) {
return moore::ExtractOp::create(builder, loc, resultType, value,
range.translateIndex(lowBit));
});
}
// Save the queue which is being indexed: this allows us to handle the `$`
// operator, which evaluates to the last valid index in the queue.
Value savedQueue = context.currentQueue;
llvm::scope_exit restoreQueue([&] { context.currentQueue = savedQueue; });
if (isa<moore::QueueType>(derefType)) {
// For QueueSizeBIOp, we need a byvalue queue, so if the queue is an
// lvalue (because we're assigning to it), we need to dereference it
if (isa<moore::RefType>(value.getType())) {
context.currentQueue = moore::ReadOp::create(builder, loc, value);
} else {
context.currentQueue = value;
}
}
auto lowBit = context.convertRvalueExpression(expr.selector());
if (!lowBit)
return {};
lowBit = getSelectIndex(context, loc, lowBit, range);
if (isLvalue)
return llvm::TypeSwitch<Type, Value>(derefType)
.Case<moore::QueueType>([&](moore::QueueType) {
return moore::DynQueueRefElementOp::create(builder, loc, resultType,
value, lowBit);
})
.Default([&](Type) {
return moore::DynExtractRefOp::create(builder, loc, resultType,
value, lowBit);
});
else
return llvm::TypeSwitch<Type, Value>(derefType)
.Case<moore::QueueType>([&](moore::QueueType) {
return moore::DynQueueExtractOp::create(builder, loc, resultType,
value, lowBit, lowBit);
})
.Default([&](Type) {
return moore::DynExtractOp::create(builder, loc, resultType, value,
lowBit);
});
}
/// Handle null assignments to variables.
/// Compare with IEEE 1800-2023 Table 6-7 - Default variable initial values
Value visit(const slang::ast::NullLiteral &expr) {
auto type = context.convertType(*expr.type);
if (isa<moore::ClassHandleType, moore::ChandleType, moore::EventType,
moore::NullType>(type))
return moore::NullOp::create(builder, loc);
mlir::emitError(loc) << "No null value definition found for value of type "
<< type;
return {};
}
/// Handle range bit selections.
Value visit(const slang::ast::RangeSelectExpression &expr) {
auto type = context.convertType(*expr.type);
auto value = convertLvalueOrRvalueExpression(expr.value());
if (!type || !value)
return {};
auto derefType = value.getType();
if (isLvalue)
derefType = cast<moore::RefType>(derefType).getNestedType();
if (isa<moore::QueueType>(derefType)) {
return handleQueueRangeSelectExpressions(expr, type, value);
}
return handleArrayRangeSelectExpressions(expr, type, value);
}
// Handles range selections into queues, in which neither bound needs to be
// constant
Value handleQueueRangeSelectExpressions(
const slang::ast::RangeSelectExpression &expr, Type type, Value value) {
Value savedQueue = context.currentQueue;
llvm::scope_exit restoreQueue([&] { context.currentQueue = savedQueue; });
context.currentQueue = value;
auto lowerIdx = context.convertRvalueExpression(expr.left());
auto upperIdx = context.convertRvalueExpression(expr.right());
auto resultType =
isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
if (isLvalue) {
mlir::emitError(loc) << "queue lvalue range selections are not supported";
return {};
}
return moore::DynQueueExtractOp::create(builder, loc, resultType, value,
lowerIdx, upperIdx);
}
// Handles range selections into arrays, which currently require a constant
// upper bound
Value handleArrayRangeSelectExpressions(
const slang::ast::RangeSelectExpression &expr, Type type, Value value) {
std::optional<int32_t> constLeft;
std::optional<int32_t> constRight;
if (auto *constant = expr.left().getConstant())
constLeft = constant->integer().as<int32_t>();
if (auto *constant = expr.right().getConstant())
constRight = constant->integer().as<int32_t>();
// We currently require the right-hand-side of the range to be constant.
// This catches things like `[42:$]` which we don't support at the moment.
if (!constRight) {
mlir::emitError(loc)
<< "unsupported expression: range select with non-constant bounds";
return {};
}
// We need to determine the right bound of the range. This is the address of
// the least significant bit of the underlying bit storage, which is the
// offset we want to pass to the extract op.
//
// The arrays [6:2] and [2:6] both have 5 bits worth of underlying storage.
// The left and right bound of the range only determine the addressing
// scheme of the storage bits:
//
// Storage bits: 4 3 2 1 0 <-- extract op works on storage bits
// [6:2] indices: 6 5 4 3 2 ("little endian" in Slang terms)
// [2:6] indices: 2 3 4 5 6 ("big endian" in Slang terms)
//
// Before we can extract, we need to map the range select left and right
// bounds from these indices to actual bit positions in the storage.
Value offsetDyn;
int32_t offsetConst = 0;
auto range = expr.value().type->getFixedRange();
using slang::ast::RangeSelectionKind;
if (expr.getSelectionKind() == RangeSelectionKind::Simple) {
// For a constant range [a:b], we want the offset of the lowest storage
// bit from which we are starting the extract. For a range [5:3] this is
// bit index 3; for a range [3:5] this is bit index 5. Both of these are
// later translated map to bit offset 1 (see bit indices above).
assert(constRight && "constness checked in slang");
offsetConst = *constRight;
} else {
// For an indexed range [a+:b] or [a-:b], determining the lowest storage
// bit is a bit more complicated. We start out with the base index `a`.
// This is the lower *index* of the range, but not the lower *storage bit
// position*.
//
// The range [a+:b] expands to [a+b-1:a] for a [6:2] range, or [a:a+b-1]
// for a [2:6] range. The range [a-:b] expands to [a:a-b+1] for a [6:2]
// range, or [a-b+1:a] for a [2:6] range.
if (constLeft) {
offsetConst = *constLeft;
} else {
offsetDyn = context.convertRvalueExpression(expr.left());
if (!offsetDyn)
return {};
}
// For a [a-:b] select on [2:6] and a [a+:b] select on [6:2], the range
// expands to [a-b+1:a] and [a+b-1:a]. In this case, the right bound which
// corresponds to the lower *storage bit offset*, is just `a` and there's
// no further tweaking to do.
int32_t offsetAdd = 0;
// For a [a-:b] select on [6:2], the range expands to [a:a-b+1]. We
// therefore have to take the `a` from above and adjust it by `-b+1` to
// arrive at the right bound.
if (expr.getSelectionKind() == RangeSelectionKind::IndexedDown &&
range.isLittleEndian()) {
assert(constRight && "constness checked in slang");
offsetAdd = 1 - *constRight;
}
// For a [a+:b] select on [2:6], the range expands to [a:a+b-1]. We
// therefore have to take the `a` from above and adjust it by `+b-1` to
// arrive at the right bound.
if (expr.getSelectionKind() == RangeSelectionKind::IndexedUp &&
!range.isLittleEndian()) {
assert(constRight && "constness checked in slang");
offsetAdd = *constRight - 1;
}
// Adjust the offset such that it matches the right bound of the range.
if (offsetAdd != 0) {
if (offsetDyn)
offsetDyn = moore::AddOp::create(
builder, loc, offsetDyn,
moore::ConstantOp::create(
builder, loc, cast<moore::IntType>(offsetDyn.getType()),
offsetAdd,
/*isSigned=*/offsetAdd < 0));
else
offsetConst += offsetAdd;
}
}
// Create a dynamic or constant extract. Use `getSelectIndex` and
// `ConstantRange::translateIndex` to map from the bit indices provided by
// the user to the actual storage bit position. Since `offset*` corresponds
// to the right bound of the range, which provides the index of the least
// significant selected storage bit, we get the bit offset at which we want
// to start extracting.
auto resultType =
isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type)) : type;
if (offsetDyn) {
offsetDyn = getSelectIndex(context, loc, offsetDyn, range);
if (isLvalue) {
return moore::DynExtractRefOp::create(builder, loc, resultType, value,
offsetDyn);
} else {
return moore::DynExtractOp::create(builder, loc, resultType, value,
offsetDyn);
}
} else {
offsetConst = range.translateIndex(offsetConst);
if (isLvalue) {
return moore::ExtractRefOp::create(builder, loc, resultType, value,
offsetConst);
} else {
return moore::ExtractOp::create(builder, loc, resultType, value,
offsetConst);
}
}
}
/// Handle concatenations.
Value visit(const slang::ast::ConcatenationExpression &expr) {
SmallVector<Value> operands;
if (expr.type->isString()) {
for (auto *operand : expr.operands()) {
assert(!isLvalue && "checked by Slang");
auto value = convertLvalueOrRvalueExpression(*operand);
if (!value)
return {};
value = context.materializeConversion(
moore::StringType::get(context.getContext()), value, false,
value.getLoc());
if (!value)
return {};
operands.push_back(value);
}
return moore::StringConcatOp::create(builder, loc, operands);
}
if (expr.type->isQueue()) {
return handleQueueConcat(expr);
}
for (auto *operand : expr.operands()) {
// Handle empty replications like `{0{...}}` which may occur within
// concatenations. Slang assigns them a `void` type which we can check for
// here.
if (operand->type->isVoid())
continue;
auto value = convertLvalueOrRvalueExpression(*operand);
if (!value)
return {};
if (!isLvalue)
value = context.convertToSimpleBitVector(value);
if (!value)
return {};
operands.push_back(value);
}
if (isLvalue)
return moore::ConcatRefOp::create(builder, loc, operands);
else
return moore::ConcatOp::create(builder, loc, operands);
}
// Handles a `ConcatenationExpression` which produces a queue as a result.
// Intuitively, queue concatenations are the same as unpacked array
// concatenations. However, because queues may vary in size, we can't
// just convert each argument to a simple bit vector.
Value handleQueueConcat(const slang::ast::ConcatenationExpression &expr) {
SmallVector<Value> operands;
auto queueType =
cast<moore::QueueType>(context.convertType(*expr.type, loc));
auto elementType = queueType.getElementType();
// Strategy:
// QueueConcatOp only takes queues, so other types must be converted to
// queues.
// - Unpacked arrays have a conversion to queues via
// `QueueFromUnpackedArrayOp`.
// - For individual elements, we create a new queue for each contiguous
// sequence of elements, and add this to the QueueConcatOp.
// The current contiguous sequence of individual elements.
Value contigElements;
for (auto *operand : expr.operands()) {
bool isSingleElement =
context.convertType(*operand->type, loc) == elementType;
// If the subsequent operand is not a single element, add the current
// sequence of contiguous elements to the QueueConcatOp
if (!isSingleElement && contigElements) {
operands.push_back(moore::ReadOp::create(builder, loc, contigElements));
contigElements = {};
}
assert(!isLvalue && "checked by Slang");
auto value = convertLvalueOrRvalueExpression(*operand);
if (!value)
return {};
// If value is an element of the queue, create an empty queue and add
// that element.
if (value.getType() == elementType) {
auto queueRefType =
moore::RefType::get(context.getContext(), queueType);
if (!contigElements) {
contigElements =
moore::VariableOp::create(builder, loc, queueRefType, {}, {});
}
moore::QueuePushBackOp::create(builder, loc, contigElements, value);
continue;
}
// Otherwise, the value should be directly convertible to a queue type.
// If the type is a queue type with the same element type, skip this step,
// since we don't need to cast things like queue<T, 10> to queue<T, 0>,
// - QueueConcatOp doesn't mind the queue bounds.
if (!(isa<moore::QueueType>(value.getType()) &&
cast<moore::QueueType>(value.getType()).getElementType() ==
elementType)) {
value = context.materializeConversion(queueType, value, false,
value.getLoc());
}
operands.push_back(value);
}
if (contigElements) {
operands.push_back(moore::ReadOp::create(builder, loc, contigElements));
}
return moore::QueueConcatOp::create(builder, loc, queueType, operands);
}
/// Handle member accesses.
Value visit(const slang::ast::MemberAccessExpression &expr) {
auto type = context.convertType(*expr.type);
if (!type)
return {};
auto *valueType = expr.value().type.get();
auto memberName = builder.getStringAttr(expr.member.name);
// Handle virtual interfaces. We represent virtual interface handles as a
// Moore struct containing references to interface members. Member access
// returns the stored reference directly (for lvalues) or reads it (for
// rvalues).
if (valueType->isVirtualInterface()) {
auto memberType = dyn_cast<moore::UnpackedType>(type);
if (!memberType) {
mlir::emitError(loc)
<< "unsupported virtual interface member type: " << type;
return {};
}
auto resultRefType = moore::RefType::get(memberType);
// Always use the rvalue of the base handle to avoid creating
// ref<ref<T>> for lvalue member access.
Value base = context.convertRvalueExpression(expr.value());
if (!base)
return {};
auto memberRef = moore::StructExtractOp::create(
builder, loc, resultRefType, memberName, base);
if (isLvalue)
return memberRef;
return moore::ReadOp::create(builder, loc, memberRef);
}
// Handle structs.
if (valueType->isStruct()) {
auto resultType =
isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
: type;
auto value = convertLvalueOrRvalueExpression(expr.value());
if (!value)
return {};
if (isLvalue)
return moore::StructExtractRefOp::create(builder, loc, resultType,
memberName, value);
return moore::StructExtractOp::create(builder, loc, resultType,
memberName, value);
}
// Handle unions.
if (valueType->isPackedUnion() || valueType->isUnpackedUnion()) {
auto resultType =
isLvalue ? moore::RefType::get(cast<moore::UnpackedType>(type))
: type;
auto value = convertLvalueOrRvalueExpression(expr.value());
if (!value)
return {};
if (isLvalue)
return moore::UnionExtractRefOp::create(builder, loc, resultType,
memberName, value);
return moore::UnionExtractOp::create(builder, loc, type, memberName,
value);
}
// Handle classes.
if (valueType->isClass()) {
auto valTy = context.convertType(*valueType);
if (!valTy)
return {};
auto targetTy = cast<moore::ClassHandleType>(valTy);
// `MemberAccessExpression`s may refer to either variables that may or may
// not be compile time constants, or to class parameters which are always
// elaboration-time constant.
//
// We distinguish these cases, and materialize a runtime member access
// for variables, but force constant conversion for parameter accesses.
//
// Also see this discussion:
// https://github.com/MikePopoloski/slang/issues/1641
if (expr.member.kind != slang::ast::SymbolKind::Parameter) {
// We need to pick the closest ancestor that declares a property with
// the relevant name. System Verilog explicitly enforces lexical
// shadowing, as shown in IEEE 1800-2023 Section 8.14 "Overridden
// members".
moore::ClassHandleType upcastTargetTy =
context.getAncestorClassWithProperty(targetTy, expr.member.name,
loc);
if (!upcastTargetTy)
return {};
// Convert the class handle to the required target type for property
// shadowing purposes.
Value baseVal =
context.convertRvalueExpression(expr.value(), upcastTargetTy);
if (!baseVal)
return {};
// @field and result type !moore.ref<T>.
auto fieldSym = mlir::FlatSymbolRefAttr::get(builder.getContext(),
expr.member.name);
auto fieldRefTy = moore::RefType::get(cast<moore::UnpackedType>(type));
// Produce a ref to the class property from the (possibly upcast)
// handle.
Value fieldRef = moore::ClassPropertyRefOp::create(
builder, loc, fieldRefTy, baseVal, fieldSym);
// If we need an RValue, read the reference, otherwise return
return isLvalue ? fieldRef
: moore::ReadOp::create(builder, loc, fieldRef);
}
slang::ConstantValue constVal;
if (auto param = expr.member.as_if<slang::ast::ParameterSymbol>()) {
constVal = param->getValue();
if (auto value = context.materializeConstant(constVal, *expr.type, loc))
return value;
}
mlir::emitError(loc) << "Parameter " << expr.member.name
<< " has no constant value";
return {};
}
mlir::emitError(loc, "expression of type ")
<< valueType->toString() << " has no member fields";
return {};
}
};
} // namespace
//===----------------------------------------------------------------------===//
// Rvalue Conversion
//===----------------------------------------------------------------------===//
// NOLINTBEGIN(misc-no-recursion)
namespace {
struct RvalueExprVisitor : public ExprVisitor {
RvalueExprVisitor(Context &context, Location loc)
: ExprVisitor(context, loc, /*isLvalue=*/false) {}
using ExprVisitor::visit;
// Handle references to the left-hand side of a parent assignment.
Value visit(const slang::ast::LValueReferenceExpression &expr) {
assert(!context.lvalueStack.empty() && "parent assignments push lvalue");
auto lvalue = context.lvalueStack.back();
return moore::ReadOp::create(builder, loc, lvalue);
}
// Handle named values, such as references to declared variables.
Value visit(const slang::ast::NamedValueExpression &expr) {
// Handle local variables.
if (auto value = context.valueSymbols.lookup(&expr.symbol)) {
if (isa<moore::RefType>(value.getType())) {
auto readOp = moore::ReadOp::create(builder, loc, value);
if (context.rvalueReadCallback)
context.rvalueReadCallback(readOp);
value = readOp.getResult();
}
return value;
}
// Handle global variables.
if (auto globalOp = context.globalVariables.lookup(&expr.symbol)) {
auto value = moore::GetGlobalVariableOp::create(builder, loc, globalOp);
return moore::ReadOp::create(builder, loc, value);
}
// We're reading a class property.
if (auto *const property =
expr.symbol.as_if<slang::ast::ClassPropertySymbol>()) {
auto fieldRef = visitClassProperty(context, *property);
return moore::ReadOp::create(builder, loc, fieldRef).getResult();
}
// Slang may resolve `vif.member` accesses (with `vif` being a virtual
// interface handle) directly to a NamedValueExpression for `member`.
// Reconstruct the virtual interface access by consulting the mapping
// populated at declaration sites.
if (auto access = context.virtualIfaceMembers.lookup(&expr.symbol);
access.base) {
auto type = context.convertType(*expr.type);
if (!type)
return {};
auto memberType = dyn_cast<moore::UnpackedType>(type);
if (!memberType) {
mlir::emitError(loc)
<< "unsupported virtual interface member type: " << type;
return {};
}
Value base = materializeSymbolRvalue(*access.base);
if (!base) {
auto d = mlir::emitError(loc, "unknown name `")
<< access.base->name << "`";
d.attachNote(context.convertLocation(access.base->location))
<< "no rvalue generated for virtual interface base";
return {};
}
auto fieldName = access.fieldName
? access.fieldName
: builder.getStringAttr(expr.symbol.name);
auto memberRefType = moore::RefType::get(memberType);
auto memberRef = moore::StructExtractOp::create(
builder, loc, memberRefType, fieldName, base);
auto readOp = moore::ReadOp::create(builder, loc, memberRef);
if (context.rvalueReadCallback)
context.rvalueReadCallback(readOp);
return readOp.getResult();
}
// Try to materialize constant values directly.
auto constant = context.evaluateConstant(expr);
if (auto value = context.materializeConstant(constant, *expr.type, loc))
return value;
// Otherwise some other part of ImportVerilog should have added an MLIR
// value for this expression's symbol to the `context.valueSymbols` table.
auto d = mlir::emitError(loc, "unknown name `") << expr.symbol.name << "`";
d.attachNote(context.convertLocation(expr.symbol.location))
<< "no rvalue generated for " << slang::ast::toString(expr.symbol.kind);
return {};
}
// Handle hierarchical values, such as `x = Top.sub.var`.
Value visit(const slang::ast::HierarchicalValueExpression &expr) {
auto hierLoc = context.convertLocation(expr.symbol.location);
if (auto value = context.valueSymbols.lookup(&expr.symbol)) {
if (isa<moore::RefType>(value.getType())) {
auto readOp = moore::ReadOp::create(builder, hierLoc, value);
if (context.rvalueReadCallback)
context.rvalueReadCallback(readOp);
value = readOp.getResult();
}
return value;
}
// Emit an error for those hierarchical values not recorded in the
// `valueSymbols`.
auto d = mlir::emitError(loc, "unknown hierarchical name `")
<< expr.symbol.name << "`";
d.attachNote(hierLoc) << "no rvalue generated for "
<< slang::ast::toString(expr.symbol.kind);
return {};
}
// Handle arbitrary symbol references. Slang uses this expression to represent
// "real" interface instances in virtual interface assignments.
Value visit(const slang::ast::ArbitrarySymbolExpression &expr) {
const auto &canonTy = expr.type->getCanonicalType();
if (const auto *vi = canonTy.as_if<slang::ast::VirtualInterfaceType>()) {
auto value = context.materializeVirtualInterfaceValue(*vi, loc);
if (failed(value))
return {};
return *value;
}
mlir::emitError(loc) << "unsupported arbitrary symbol expression of type "
<< expr.type->toString();
return {};
}
// Handle type conversions (explicit and implicit).
Value visit(const slang::ast::ConversionExpression &expr) {
auto type = context.convertType(*expr.type);
if (!type)
return {};
return context.convertRvalueExpression(expr.operand(), type);
}
// Handle blocking and non-blocking assignments.
Value visit(const slang::ast::AssignmentExpression &expr) {
auto lhs = context.convertLvalueExpression(expr.left());
if (!lhs)
return {};
// Determine the right-hand side value of the assignment.
context.lvalueStack.push_back(lhs);
auto rhs = context.convertRvalueExpression(
expr.right(), cast<moore::RefType>(lhs.getType()).getNestedType());
context.lvalueStack.pop_back();
if (!rhs)
return {};
// If this is a blocking assignment, we can insert the delay/wait ops of the
// optional timing control directly in between computing the RHS and
// executing the assignment.
if (!expr.isNonBlocking()) {
if (expr.timingControl)
if (failed(context.convertTimingControl(*expr.timingControl)))
return {};
auto assignOp = moore::BlockingAssignOp::create(builder, loc, lhs, rhs);
if (context.variableAssignCallback)
context.variableAssignCallback(assignOp);
return rhs;
}
// For non-blocking assignments, we only support time delays for now.
if (expr.timingControl) {
// Handle regular time delays.
if (auto *ctrl = expr.timingControl->as_if<slang::ast::DelayControl>()) {
auto delay = context.convertRvalueExpression(
ctrl->expr, moore::TimeType::get(builder.getContext()));
if (!delay)
return {};
auto assignOp = moore::DelayedNonBlockingAssignOp::create(
builder, loc, lhs, rhs, delay);
if (context.variableAssignCallback)
context.variableAssignCallback(assignOp);
return rhs;
}
// All other timing controls are not supported.
auto loc = context.convertLocation(expr.timingControl->sourceRange);
mlir::emitError(loc)
<< "unsupported non-blocking assignment timing control: "
<< slang::ast::toString(expr.timingControl->kind);
return {};
}
auto assignOp = moore::NonBlockingAssignOp::create(builder, loc, lhs, rhs);
if (context.variableAssignCallback)
context.variableAssignCallback(assignOp);
return rhs;
}
// Helper function to convert an argument to a simple bit vector type, pass it
// to a reduction op, and optionally invert the result.
template <class ConcreteOp>
Value createReduction(Value arg, bool invert) {
arg = context.convertToSimpleBitVector(arg);