-
Notifications
You must be signed in to change notification settings - Fork 277
/
FIRRTLExpressions.td
1362 lines (1159 loc) · 47.8 KB
/
FIRRTLExpressions.td
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
//===- FIRRTLExpressions.td - FIRRTL expression ops --------*- tablegen -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This describes the MLIR ops for FIRRTL expressions.
//
//===----------------------------------------------------------------------===//
#ifndef CIRCT_DIALECT_FIRRTL_FIRRTLEXPRESSIONS_TD
#define CIRCT_DIALECT_FIRRTL_FIRRTLEXPRESSIONS_TD
include "FIRRTLDialect.td"
include "FIRRTLTypes.td"
include "FIRRTLEnums.td"
include "circt/Dialect/HW/HWAttributesNaming.td"
include "circt/Dialect/HW/HWOpInterfaces.td"
include "circt/Dialect/HW/HWTypes.td"
include "circt/Types.td"
include "mlir/Interfaces/InferTypeOpInterface.td"
include "mlir/Interfaces/SideEffectInterfaces.td"
def SameOperandsIntTypeKind : NativeOpTrait<"SameOperandsIntTypeKind"> {
let cppNamespace = "::circt::firrtl";
}
// A common base class for operations that implement type inference and parsed
// argument validation.
class FIRRTLExprOp<string mnemonic, list<Trait> traits = []> :
FIRRTLOp<mnemonic, traits # [HasCustomSSAName, InferTypeOpInterface, Pure]> {
// The narrow operation-specific type inference method. Operations can
// override this with an inline declaration for the class header, or just
// leave it as is and implement the function in a cpp file.
code inferTypeDecl = [{
/// Infer the return type of this operation.
static FIRRTLType inferReturnType(ValueRange operands,
ArrayRef<NamedAttribute> attrs,
std::optional<Location> loc);
}];
// The operation-specific validator for a parsed list of operands and
// constants. Operations can override this with an inline declaration for the
// class header, or just leave it as is and implement the function in a cpp
// file.
code parseValidator = "";
code parseValidatorDecl = [{
/// Check that the parser has consumed the correct number of operands and
/// constants.
static LogicalResult validateArguments(ValueRange operands,
ArrayRef<NamedAttribute> attrs,
Location loc)
}] # !if(!empty(parseValidator), ";", !subst("$_impl", parseValidator, [{ {
return $_impl(operands, attrs, loc);
} }]));
// Additional class declarations to emit alongside the type inference.
code firrtlExtraClassDeclaration = "";
let extraClassDeclaration = firrtlExtraClassDeclaration # inferTypeDecl #
parseValidatorDecl # [{
/// Infer the return types of this operation. This is called by the
/// `InferTypeOpInterface`. We simply forward to a narrower
/// operation-specific implementation which is sufficient for FIRRTL ops.
static LogicalResult inferReturnTypes(MLIRContext *context,
std::optional<Location> loc,
ValueRange operands,
DictionaryAttr attrs,
mlir::OpaqueProperties properties,
mlir::RegionRange regions,
SmallVectorImpl<Type> &results) {
return impl::inferReturnTypes(context, loc, operands, attrs, properties,
regions, results, &inferReturnType);
}
/// Check that the parser has consumed the correct number of operands and
/// constants, and infer the appropriate return type for the operation.
static FIRRTLType validateAndInferReturnType(ValueRange operands,
ArrayRef<NamedAttribute> attrs,
Location loc) {
if (failed(validateArguments(operands, attrs, loc)))
return {};
return inferReturnType(operands, attrs, loc);
}
// Returns when two result types are compatible for this op; method used by
// InferTypeOpInterface.
static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) {
if (l.size () != r.size())
return false;
for (auto [l, r] : llvm::zip(l, r)) {
if (!areAnonymousTypesEquivalent(l, r))
return false;
}
return true;
}
}];
}
def ConstantOp : FIRRTLOp<"constant",
[Pure, ConstantLike, FirstAttrDerivedResultType,
HasCustomSSAName]> {
let summary = "Produce a constant value";
let description = [{
The constant operation produces a constant value of SInt or UInt type, it
never produces a zero bit wide result.
```
%result = firrtl.constant 42 : t1
```
}];
let arguments = (ins APSIntAttr:$value);
let results = (outs IntType:$result);
let hasCustomAssemblyFormat = 1;
let builders = [
OpBuilder<(ins "IntType":$type, "const APInt &":$value)>,
OpBuilder<(ins "const APSInt &":$value)>
];
let hasFolder = 1;
let hasVerifier = 1;
}
def SpecialConstantOp : FIRRTLOp<"specialconstant",
[Pure, ConstantLike, HasCustomSSAName]> {
let summary = "Produce a constant Reset or Clock value";
let description = [{
The constant operation produces a constant value of Reset, AsyncReset, or
Clock type. The value can only be 0 or 1.
```
%result = firrtl.specialconstant 1 : !firrtl.clock
```
}];
let arguments = (ins BoolAttr:$value);
let results = (outs
AnyTypeOf<[ClockType, ResetType, AsyncResetType]>:$result);
let hasCustomAssemblyFormat = 1;
let hasFolder = 1;
}
def AggregateConstantOp : FIRRTLOp<"aggregateconstant", [Pure, ConstantLike]> {
let summary = "Produce a constant of a passive aggregate value";
let description = [{
The constant operation produces a constant value of an aggregate type. The
type must be passive. Clock and reset values are supported.
For nested aggregates, embedded arrays are used.
```
%result = firrtl.aggregateconstant [1, 2, 3] : !firrtl.bundle<a: uint<8>, b: uint<5>, c: uint<4>>
%result = firrtl.aggregateconstant [1, 2, 3] : !firrtl.vector<uint<8>, 3>
%result = firrtl.aggregateconstant [[1, 2], [3, 5]] : !firrtl.vector<!firrtl.bundle<a: uint<8>, b: uint<5>>, 2>
```
}];
let extraClassDeclaration = [{
Attribute getAttributeFromFieldID(uint64_t fieldID);
}];
let arguments = (ins ArrayAttr:$fields);
let results = (outs AggregateType:$result);
let assemblyFormat = "$fields attr-dict `:` type($result)";
let hasFolder = 1;
let hasVerifier = 1;
}
def BundleCreateOp : FIRRTLOp<"bundlecreate"> {
let summary = "Produce a bundle value";
let description = [{
Create an bundle from component values. This is equivalent in terms of
flow to creating a node.
```
%result = firrtl.bundlecreate %1, %2, %3 : !firrtl.bundle<a: uint<8>, b: uint<5>, c: uint<4>>
```
}];
let arguments = (ins Variadic<FIRRTLBaseType>:$fields);
let results = (outs BundleType:$result);
let assemblyFormat = "$fields attr-dict `:` functional-type($fields, $result)";
let hasVerifier = 1;
let hasFolder = 1;
}
def VectorCreateOp : FIRRTLOp<"vectorcreate"> {
let summary = "Produce a vector value";
let description = [{
Create a vector from component values. This is equivalent in terms of
flow to creating a node. The first operand indicates 0-th element of
the result.
```
%result = firrtl.vectorcreate %1, %2, %3 : !firrtl.vector<uint<8>, 3>
```
}];
let arguments = (ins Variadic<FIRRTLBaseType>:$fields);
let results = (outs FVectorType:$result);
let assemblyFormat = "$fields attr-dict `:` functional-type($fields, $result)";
let hasVerifier = 1;
let hasFolder = 1;
}
def FEnumCreateOp : FIRRTLOp<"enumcreate"> {
let summary = "Produce a enum value";
let description = [{
Create an enum from tag and value.
```mlir
%result = firrtl.enumcreate field-name(%input) : !firrtl.enum<None: uint<0>, Some: uint<8>>
```
}];
let arguments = (ins I32Attr:$fieldIndex, FIRRTLBaseType:$input);
let results = (outs FEnumType:$result);
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
let builders = [
OpBuilder<(ins "FEnumType":$resultType, "StringRef":$fieldName, "Value":$input), [{
auto fieldIndex = resultType.getElementIndex(fieldName);
assert(fieldIndex.has_value() && "invalid type constructor");
return build($_builder, $_state, resultType, (uint32_t)*fieldIndex, input);
}]>
];
let extraClassDeclaration = [{
/// Return the name attribute of the accessed field.
StringAttr getFieldNameAttr() {
return getResult().getType().base().getElementNameAttr(getFieldIndex());
}
/// Return the name of the accessed field.
StringRef getFieldName() {
return getFieldNameAttr().getValue();
}
}];
}
def InvalidValueOp : FIRRTLOp<"invalidvalue",
[MemoryEffects<[MemAlloc]>, HasCustomSSAName]> {
let summary = "InvalidValue primitive";
let description = [{
The InvalidValue operation returns an invalid value of a specified type:
```
%result = firrtl.invalid : !firrtl.uint<1>
```
This corresponds to the FIRRTL invalidate operation without the implicit
connect semantics. Each invalid op produces a unique invalid value.
InvalidOp is not constant-like
}];
let arguments = (ins);
let results = (outs FIRRTLBaseType:$result);
let hasCanonicalizeMethod = 1;
let assemblyFormat = "attr-dict `:` qualified(type($result))";
}
class BaseSubfieldOp<string name, Type btype, Type rtype> : FIRRTLExprOp<name> {
let summary = "Extract a subfield of another value";
let description = [{
The subfield expression refers to a subelement of an expression with a
bundle type.
```
%result = firrtl.}] # name # [{ %input[field-name] : !input-type
```
}];
let arguments = (ins btype:$input, I32Attr:$fieldIndex);
let results = (outs rtype:$result);
let hasVerifier = 1;
let hasCustomAssemblyFormat = 1;
let builders = [
OpBuilder<(ins "Value":$input, "StringRef":$fieldName), [{
auto bundleType = firrtl::type_cast<}] # btype # [{>(input.getType());
auto fieldIndex = bundleType.getElementIndex(fieldName);
assert(fieldIndex.has_value() && "subfield operation to unknown field");
return build($_builder, $_state, input, *fieldIndex);
}]>
];
let firrtlExtraClassDeclaration = [{
using InputType = }] # btype # [{;
/// Return true if the specified field is flipped.
bool isFieldFlipped();
/// Return a `FieldRef` to the accessed field.
FieldRef getAccessedField() {
return FieldRef(getInput(), firrtl::type_cast<InputType>(getInput().getType())
.getFieldID(getFieldIndex()));
}
/// Return the name of the accessed field.
StringRef getFieldName() {
return firrtl::type_cast<InputType>(getInput().getType()).getElementName(getFieldIndex());
}
}];
}
def SubfieldOp : BaseSubfieldOp<"subfield", BundleType, FIRRTLBaseType> {
let hasFolder = 1;
let hasCanonicalizer = 1;
}
def OpenSubfieldOp : BaseSubfieldOp<"opensubfield", OpenBundleType, FIRRTLType>;
def SubindexOp : FIRRTLExprOp<"subindex"> {
let summary = "Extract an element of a vector value";
let description = [{
The subindex expression statically refers, by index, to a subelement
of an expression with a vector type. The index must be a non-negative
integer and cannot be equal to or exceed the length of the vector it
indexes.
```
%result = firrtl.subindex %input[index] : t1
```
}];
let arguments = (ins FVectorType:$input, I32Attr:$index);
let results = (outs FIRRTLBaseType:$result);
let hasFolder = 1;
let hasCanonicalizer = 1;
let assemblyFormat =
"$input `[` $index `]` attr-dict `:` qualified(type($input))";
let firrtlExtraClassDeclaration = [{
/// Return a `FieldRef` to the accessed field.
FieldRef getAccessedField() {
return FieldRef(getInput(), getInput().getType().base().getFieldID(getIndex()));
}
using InputType = FVectorType;
}];
}
def OpenSubindexOp : FIRRTLExprOp<"opensubindex"> {
let summary = "Extract an element of a vector value";
let description = [{
The subindex expression statically refers, by index, to a subelement
of an expression with a vector type. The index must be a non-negative
integer and cannot be equal to or exceed the length of the vector it
indexes.
```
%result = firrtl.opensubindex %input[index] : t1
```
}];
let arguments = (ins OpenVectorType:$input, I32Attr:$index);
let results = (outs FIRRTLType:$result);
let assemblyFormat =
"$input `[` $index `]` attr-dict `:` qualified(type($input))";
let firrtlExtraClassDeclaration = [{
/// Return a `FieldRef` to the accessed field.
FieldRef getAccessedField() {
return FieldRef(getInput(), getInput().getType().getFieldID(getIndex()));
}
using InputType = OpenVectorType;
}];
}
def SubaccessOp : FIRRTLExprOp<"subaccess"> {
let summary = "Extract a dynamic element of a vector value";
let description = [{
The subaccess expression dynamically refers to a subelement of a
vector-typed expression using a calculated index. The index must be an
expression with an unsigned integer type.
```
%result = firrtl.subaccess %input[%idx] : t1, t2
```
}];
let arguments = (ins FVectorType:$input, UIntType:$index);
let results = (outs FIRRTLBaseType:$result);
let assemblyFormat =
"$input `[` $index `]` attr-dict `:` qualified(type($input)) `,` qualified(type($index))";
let hasCanonicalizer = true;
}
def IsTagOp : FIRRTLExprOp<"istag"> {
let summary = "Test the active variant of an enumeration";
let description = [{
This operation is used to test the active variant of an enumeration. The
tag tested for must be one of the possible variants of the input type. If
the tag is the currently active variant the result will be 1, otherwise the
result will be 0.
Example:
```mlir
%0 = firrtl.istag A %v : !firrtl.enum<A: UInt<0>, B: UInt<0>>
```
}];
let arguments = (ins FEnumType:$input, I32Attr:$fieldIndex);
let results = (outs UInt1Type:$result);
let hasVerifier = 1;
let hasCustomAssemblyFormat = 1;
let builders = [
OpBuilder<(ins "Value":$input, "StringRef":$fieldName), [{
auto enumType = firrtl::type_cast<FEnumType>(input.getType());
auto fieldIndex = enumType.getElementIndex(fieldName);
assert(fieldIndex.has_value() && "subtag operation to unknown field");
return build($_builder, $_state, input, *fieldIndex);
}]>
];
let firrtlExtraClassDeclaration = [{
/// Return a `FieldRef` to the accessed field.
FieldRef getAccessedField() {
return FieldRef(getInput(), firrtl::type_cast<FEnumType>(getInput().getType())
.getFieldID(getFieldIndex()));
}
/// Return the name of the accessed field.
StringAttr getFieldNameAttr() {
return firrtl::type_cast<FEnumType>(getInput().getType())
.getElementNameAttr(getFieldIndex());
}
/// Return the name of the accessed field.
StringRef getFieldName() {
return getFieldNameAttr().getValue();
}
}];
}
def SubtagOp : FIRRTLExprOp<"subtag"> {
let summary = "Extract an element of a enum value";
let description = [{
The subtag expression refers to a subelement of a
enum-typed expression.
```
%result = firrtl.subtag %input[field-name] : !input-type
```
}];
let arguments = (ins FEnumType:$input, I32Attr:$fieldIndex);
let results = (outs FIRRTLBaseType:$result);
let hasVerifier = 1;
let hasCustomAssemblyFormat = 1;
let builders = [
OpBuilder<(ins "Value":$input, "StringRef":$fieldName), [{
auto enumType = firrtl::type_cast<FEnumType>(input.getType());
auto fieldIndex = enumType.getElementIndex(fieldName);
assert(fieldIndex.has_value() && "subtag operation to unknown field");
return build($_builder, $_state, input, *fieldIndex);
}]>
];
let firrtlExtraClassDeclaration = [{
/// Return a `FieldRef` to the accessed field.
FieldRef getAccessedField() {
return FieldRef(getInput(), getInput().getType().base()
.getFieldID(getFieldIndex()));
}
/// Return the name of the accessed field.
StringAttr getFieldNameAttr() {
return getInput().getType().base().getElementNameAttr(getFieldIndex());
}
/// Return the name of the accessed field.
StringRef getFieldName() {
return getFieldNameAttr().getValue();
}
}];
}
def TagExtractOp : FIRRTLExprOp<"tagextract", [InferTypeOpInterface]> {
let summary = "Extract the tag from a value";
let description = [{
The tagextract expression returns the binary value of the current tag of an
enum value.
```
%result = firrtl.tagextract %input : !input-type
```
}];
let arguments = (ins FEnumType:$input);
let results = (outs UIntType:$result);
let assemblyFormat = "$input attr-dict `:` qualified(type($input))";
}
def MultibitMuxOp : FIRRTLExprOp<"multibit_mux"> {
let summary = "Multibit multiplexer";
let description = [{
The multibit mux expression dynamically selects operands. The
index must be an expression with an unsigned integer type.
```
%result = firrtl.multibit_mux %index,
%v_{n-1}, ..., %v_2, %v_1, %v_0 : t1, t2
```
The order of operands is defined in the same way as hw dialect.
For the example above, if `%index` is 0, then the value is `%v_0`.
}];
let arguments = (ins UIntType:$index, Variadic<FIRRTLBaseType>:$inputs);
let results = (outs FIRRTLBaseType:$result);
let hasCustomAssemblyFormat = 1;
let hasFolder = true;
let hasCanonicalizeMethod = true;
}
//===----------------------------------------------------------------------===//
// Primitive Operations
//===----------------------------------------------------------------------===//
/// PrimOp is a FIRRTLOp without side effects.
class PrimOp<string mnemonic, list<Trait> traits = []> :
FIRRTLExprOp<mnemonic, traits> {
let hasFolder = 1;
}
//===----------------------------------------------------------------------===//
// Binary Operations
//===----------------------------------------------------------------------===//
// Base class for binary primitive operators.
class BinaryPrimOp<string mnemonic, Type lhsType, Type rhsType, Type resultType,
list<Trait> traits = []> : PrimOp<mnemonic, traits> {
let arguments = (ins lhsType:$lhs, rhsType:$rhs);
let results = (outs resultType:$result);
let assemblyFormat = [{
$lhs `,` $rhs attr-dict `:`
`(` qualified(type($lhs)) `,` qualified(type($rhs)) `)` `->` qualified(type($result))
}];
// Give concrete operations a chance to set a type inference callback. If left
// empty, a declaration for `inferBinaryReturnType` will be emitted that the
// operation is expected to implement.
code inferType = "";
let inferTypeDecl = !if(!empty(inferType), [{
/// Infer the return type of this binary operation.
static FIRRTLType inferBinaryReturnType(FIRRTLType lhs, FIRRTLType rhs,
std::optional<Location> loc);
}], "") # !subst("$_infer", !if(!empty(inferType), "inferBinaryReturnType",
inferType), [{
/// Infer the return type of this operation.
static FIRRTLType inferReturnType(ValueRange operands,
ArrayRef<NamedAttribute> attrs,
std::optional<Location> loc) {
return $_infer(firrtl::type_cast<FIRRTLType>(operands[0].getType()),
firrtl::type_cast<FIRRTLType>(operands[1].getType()),
loc);
}
}]);
let parseValidator = "impl::validateBinaryOpArguments";
}
// A binary operation on two integer-typed arguments of the same kind.
class IntBinaryPrimOp<string mnemonic, Type resultType,
list<Trait> traits = []> :
BinaryPrimOp<mnemonic, IntType, IntType, resultType,
traits # [SameOperandsIntTypeKind]>;
let inferType = "impl::inferAddSubResult" in {
let hasCanonicalizer = true in {
def AddPrimOp : IntBinaryPrimOp<"add", IntType, [Commutative]>;
def SubPrimOp : IntBinaryPrimOp<"sub", IntType>;
}
}
def MulPrimOp : IntBinaryPrimOp<"mul", IntType, [Commutative]>;
def DivPrimOp : IntBinaryPrimOp<"div", IntType> {
let description = [{
Divides the first argument (the numerator) by the second argument
(the denominator) truncating the result (rounding towards zero).
**If the denominator is zero, the result is undefined.**
The compiler may optimize this undefined behavior in any way it
wants. Notably `div(a, a)` will be optimized to `1`. This may cause
erroneous formal equivalence mismatches between unoptimized and
optimized FIRRTL dialects that are separately converted to Verilog.
}];
}
def RemPrimOp : IntBinaryPrimOp<"rem", IntType>;
let inferType = "impl::inferBitwiseResult" in {
let hasCanonicalizer = true in {
def AndPrimOp : IntBinaryPrimOp<"and", UIntType, [Commutative]>;
def OrPrimOp : IntBinaryPrimOp<"or", UIntType, [Commutative]>;
def XorPrimOp : IntBinaryPrimOp<"xor", UIntType, [Commutative]>;
}
}
// Element-wise and/or/xor operations whose result and operands are 1d vectors with
// a same type. Apply bitwise operation to each element.
let inferType = "impl::inferElementwiseResult" in
let hasFolder = 0 in {
def ElementwiseAndPrimOp : BinaryPrimOp<"elementwise_and", 1DVecIntType,
1DVecIntType, 1DVecUIntType, [Commutative]>;
def ElementwiseOrPrimOp : BinaryPrimOp<"elementwise_or", 1DVecIntType,
1DVecIntType, 1DVecUIntType, [Commutative]>;
def ElementwiseXorPrimOp : BinaryPrimOp<"elementwise_xor", 1DVecUIntType,
1DVecIntType, 1DVecUIntType, [Commutative]>;
}
// Comparison Operations
let inferType = "impl::inferComparisonResult" in {
let hasCanonicalizer = true in {
def LEQPrimOp : IntBinaryPrimOp<"leq", UInt1Type>;
def LTPrimOp : IntBinaryPrimOp<"lt", UInt1Type>;
def GEQPrimOp : IntBinaryPrimOp<"geq", UInt1Type>;
def GTPrimOp : IntBinaryPrimOp<"gt", UInt1Type>;
}
let hasCanonicalizeMethod = true in {
def EQPrimOp : IntBinaryPrimOp<"eq", UInt1Type, [Commutative]>;
def NEQPrimOp : IntBinaryPrimOp<"neq", UInt1Type, [Commutative]>;
}
}
def CatPrimOp : IntBinaryPrimOp<"cat", UIntType> {
let hasCanonicalizer = true;
}
def DShlPrimOp : BinaryPrimOp<"dshl", IntType, UIntType, IntType> {
let description = [{
A dynamic shift left operation. The width of `$result` is expanded to
`width($lhs) + 1 << width($rhs) - 1`.
}];
let hasCanonicalizer = true;
}
def DShlwPrimOp : BinaryPrimOp<"dshlw", IntType, UIntType, IntType> {
let description = [{
A dynamic shift left operation same as 'dshl' but with different width rule.
The width of `$result` is equal to `$lhs`.
}];
}
def DShrPrimOp : BinaryPrimOp<"dshr", IntType, UIntType, IntType> {
let hasCanonicalizer = true;
}
//===----------------------------------------------------------------------===//
// Unary Operations
//===----------------------------------------------------------------------===//
// Base class for binary primitive operators.
class UnaryPrimOp<string mnemonic, Type srcType, Type resultType,
list<Trait> traits = []> : PrimOp<mnemonic, traits> {
let arguments = (ins srcType:$input);
let results = (outs resultType:$result);
let assemblyFormat =
"$input attr-dict `:` functional-type($input, $result)";
// Give concrete operations a chance to set a type inference callback. If left
// empty, a declaration for `inferUnaryReturnType` will be emitted that the
// operation is expected to implement.
code inferType = "";
let inferTypeDecl = !if(!empty(inferType), [{
/// Infer the return type of this unary operation.
static FIRRTLType inferUnaryReturnType(FIRRTLType input,
std::optional<Location> loc);
}], "") # !subst("$_infer", !if(!empty(inferType), "inferUnaryReturnType",
inferType), [{
/// Infer the return type of this operation.
static FIRRTLType inferReturnType(ValueRange operands,
ArrayRef<NamedAttribute> attrs,
std::optional<Location> loc) {
return $_infer(firrtl::type_cast<FIRRTLType>(operands[0].getType()), loc);
}
}]);
let parseValidator = "impl::validateUnaryOpArguments";
}
def SizeOfIntrinsicOp : UnaryPrimOp<"int.sizeof", FIRRTLBaseType, UInt32Type>;
let hasCanonicalizer=1 in {
def AsSIntPrimOp : UnaryPrimOp<"asSInt", FIRRTLBaseType, SIntType>;
def AsUIntPrimOp : UnaryPrimOp<"asUInt", FIRRTLBaseType, UIntType>;
def CvtPrimOp : UnaryPrimOp<"cvt", IntType, SIntType>;
}
def AsAsyncResetPrimOp
: UnaryPrimOp<"asAsyncReset", OneBitCastableType, AsyncResetType>;
def AsClockPrimOp : UnaryPrimOp<"asClock", OneBitCastableType, ClockType>;
def NegPrimOp : UnaryPrimOp<"neg", IntType, SIntType>;
let hasCanonicalizer = true in
def NotPrimOp : UnaryPrimOp<"not", IntType, UIntType>;
let inferType = "impl::inferReductionResult" in {
let hasCanonicalizer = 1 in {
def AndRPrimOp : UnaryPrimOp<"andr", IntType, UInt1Type> {
let description = [{
Horizontally reduce a value to one bit, using the 'and' operation to merge
bits. `andr(x)` is equivalent to `concat(x, 1b1) == ~0`. As such, it
returns 1 for zero-bit-wide operands.
}];
}
def OrRPrimOp : UnaryPrimOp<"orr", IntType, UInt1Type> {
let description = [{
Horizontally reduce a value to one bit, using the 'or' operation to merge
bits. `orr(x)` is equivalent to `concat(x, 1b0) != 0`. As such, it
returns 0 for zero-bit-wide operands.
}];
}
def XorRPrimOp : UnaryPrimOp<"xorr", IntType, UInt1Type> {
let description = [{
Horizontally reduce a value to one bit, using the 'xor' operation to merge
bits. `xorr(x)` is equivalent to `popcount(concat(x, 1b0)) & 1`. As
such, it returns 0 for zero-bit-wide operands.
}];
}
}
}
//===----------------------------------------------------------------------===//
// Other Operations
//===----------------------------------------------------------------------===//
def BitsPrimOp : PrimOp<"bits"> {
let arguments = (ins IntType:$input, I32Attr:$hi, I32Attr:$lo);
let results = (outs UIntType:$result);
let assemblyFormat =
"$input $hi `to` $lo attr-dict `:` functional-type($input, $result)";
let description = [{
The `bits` operation extracts the bits between `hi` (inclusive) and `lo`
(inclusive) from `input`. `hi` must be greater than or equal to `lo`. Both
`hi` and `lo` must be non-negative and less than the bit width of `input`.
The result is `hi - lo + 1` bits wide.
}];
let hasCanonicalizer = true;
}
def HeadPrimOp : PrimOp<"head"> {
let arguments = (ins IntType:$input, I32Attr:$amount);
let results = (outs UIntType:$result);
let assemblyFormat =
"$input `,` $amount attr-dict `:` functional-type($input, $result)";
let hasCanonicalizeMethod = true;
let parseValidator = "impl::validateOneOperandOneConst";
}
def MuxPrimOp : PrimOp<"mux"> {
let arguments = (ins UInt1OrUnsizedType:$sel, PassiveType:$high,
PassiveType:$low);
let results = (outs PassiveType:$result);
let assemblyFormat =
"`(` operands `)` attr-dict `:` functional-type(operands, $result)";
let hasCanonicalizer = true;
}
def PadPrimOp : PrimOp<"pad"> {
let arguments = (ins IntType:$input, I32Attr:$amount);
let results = (outs IntType:$result);
let assemblyFormat =
"$input `,` $amount attr-dict `:` functional-type($input, $result)";
let description = [{
Pad the input out to an `amount` wide integer, sign extending or zero
extending according to `input`s type. If `amount` is less than the existing
width of `input`, then input is unmodified.
}];
let parseValidator = "impl::validateOneOperandOneConst";
}
class ShiftPrimOp<string mnemonic> : PrimOp<mnemonic> {
let arguments = (ins IntType:$input, I32Attr:$amount);
let results = (outs IntType:$result);
let assemblyFormat =
"$input `,` $amount attr-dict `:` functional-type($input, $result)";
let parseValidator = "impl::validateOneOperandOneConst";
}
def ShlPrimOp : ShiftPrimOp<"shl"> {
let description = [{
The `shl` operation concatenates `amount` zero bits to the least significant
end of `input`. `amount` must be non-negative.
}];
}
def ShrPrimOp : ShiftPrimOp<"shr"> {
let description = [{
The `shr` operation truncates least significant `amount` bits from `input`.
If `amount` is greater than of equal to `width(input)`, the value will be
zero for unsigned types and the sign bit for signed types. `amount` must be
non-negative.
}];
let hasCanonicalizeMethod = true;
}
def TailPrimOp : PrimOp<"tail"> {
let arguments = (ins IntType:$input, I32Attr:$amount);
let results = (outs UIntType:$result);
let assemblyFormat =
"$input `,` $amount attr-dict `:` functional-type($input, $result)";
let description = [{
The `tail` operation truncates the `amount` most significant bits from
`input`. `amount` must be non-negative and less than or equal to the bit
width of e. The result is `width(input)-amount` bits wide.
}];
let hasCanonicalizeMethod = true;
let parseValidator = "impl::validateOneOperandOneConst";
}
//===----------------------------------------------------------------------===//
// Target Specific Intrinsics
//===----------------------------------------------------------------------===//
def Mux2CellIntrinsicOp : PrimOp<"int.mux2cell"> {
let summary = [{
an intrinsic lowered into 2-to-1 MUX cell in synthesis tools.
}];
let description = [{
This intrinsic exposes a low-level API to use 2-to-1 MUX cell in backend
synthesis tool. At FIRRTL level, this operation participates
the inference process in the same way as a normal mux operation.
}];
let arguments = (ins UInt1OrUnsizedType:$sel, PassiveType:$high,
PassiveType:$low);
let results = (outs PassiveType:$result);
let assemblyFormat =
"`(` operands `)` attr-dict `:` functional-type(operands, $result)";
}
def Mux4CellIntrinsicOp : PrimOp<"int.mux4cell"> {
let summary = [{
an intrinsic lowered into 4-to-1 MUX cell in synthesis tools.
}];
let description = [{
This intrinsic exposes a low-level API to use 4-to-1 MUX cell in backend
synthesis tool. At FIRRTL level, this operation participates
the inference process as a sugar of mux operation chains.
}];
let arguments = (ins UInt2OrUnsizedType:$sel, PassiveType:$v3,
PassiveType:$v2, PassiveType:$v1,
PassiveType:$v0);
let results = (outs PassiveType:$result);
let assemblyFormat =
"`(` operands `)` attr-dict `:` functional-type(operands, $result)";
}
//===----------------------------------------------------------------------===//
// Verbatim
//===----------------------------------------------------------------------===//
def VerbatimExprOp : FIRRTLOp<"verbatim.expr",
[Pure, HasCustomSSAName]> {
let summary = "Expression that expands to a value given SystemVerilog text";
let description = [{
This operation produces a typed value expressed by a string of
SystemVerilog. This can be used to access macros and other values that are
only sensible as Verilog text.
The text string is expected to have the highest precedence, so you should
include parentheses in the string if it isn't a single token. This is also
assumed to not have side effects (use `sv.verbatim` if you need them).
`firrtl.verbatim.expr` allows operand substitutions with `{{0}}` syntax.
}];
let arguments = (ins StrAttr:$text, Variadic<AnyType>:$substitutions,
DefaultValuedAttr<NameRefArrayAttr,"{}">:$symbols);
let results = (outs FIRRTLBaseType:$result);
let assemblyFormat = [{
$text (`(` $substitutions^ `)`)?
`:` functional-type($substitutions, $result) attr-dict
}];
let builders = [
OpBuilder<(ins "Type":$resultType, "Twine":$text,
CArg<"ValueRange", "{}">:$substitutions,
CArg<"ArrayRef<Attribute>", "{}">:$symbols), [{
build(odsBuilder, odsState, resultType, odsBuilder.getStringAttr(text),
substitutions, odsBuilder.getArrayAttr(symbols));
}]>
];
}
def VerbatimWireOp : FIRRTLOp<"verbatim.wire",
[Pure, HasCustomSSAName]> {
let summary = "Expression with wire semantics that expands to a value given "
"SystemVerilog text";
let description = [{
This operation produces a typed value with wire semantics, expressed by a
string of SystemVerilog. This can be used to access macros and other values
that are only sensible as Verilog text.
The text string is expected to have the highest precedence, so you should
include parentheses in the string if it isn't a single token. This is also
assumed to not have side effects (use `sv.verbatim` if you need them).
`firrtl.verbatim.wire` allows operand substitutions with `{{0}}` syntax.
}];
let arguments = (ins StrAttr:$text, Variadic<AnyType>:$substitutions,
DefaultValuedAttr<NameRefArrayAttr,"{}">:$symbols);
let results = (outs FIRRTLBaseType:$result);
let assemblyFormat = [{
$text (`(` $substitutions^ `)`)?
`:` functional-type($substitutions, $result) attr-dict
}];
let builders = [
OpBuilder<(ins "Type":$resultType, "Twine":$text,
CArg<"ValueRange", "{}">:$substitutions,
CArg<"ArrayRef<Attribute>", "{}">:$symbols), [{
build(odsBuilder, odsState, resultType, odsBuilder.getStringAttr(text),
substitutions, odsBuilder.getArrayAttr(symbols));
}]>
];
}
//===----------------------------------------------------------------------===//
// Special inference Operations
//===----------------------------------------------------------------------===//
// This assumes operands are ground types without explicitly checking
class SameGroundTypeOperandConstness<string a, string b>
: PredOpTrait<
"operand constness must match",
CPred<"isConst($" # a # ".getType()) == isConst($" # b # ".getType())">>;
def UninferredResetCastOp : FIRRTLOp<"resetCast", [HasCustomSSAName, Pure, SameGroundTypeOperandConstness<"input", "result">]> {
let description = [{
Cast between reset types. This is used to enable strictconnects early in
the pipeline by isolating all uninferred reset connections to a single op.
}];
let arguments = (ins AnyResetType:$input);
let results = (outs AnyResetType:$result);
let hasFolder = 1;
let assemblyFormat =
"$input attr-dict `:` functional-type($input, $result)";
}
def ConstCastOp : FIRRTLOp<"constCast", [HasCustomSSAName, Pure]> {
let description = [{
Cast from a 'const' to a non-'const' type.
```
%result = firrtl.constCast %in : (!firrtl.const.t1) -> !firrtl.t1
```
}];
let arguments = (ins PassiveType:$input);
let results = (outs PassiveType:$result);
let hasVerifier = 1;
let assemblyFormat =
"$input attr-dict `:` functional-type($input, $result)";
}
//===----------------------------------------------------------------------===//
// Conversions to/from fixed-width signless integer types in standard dialect.
//===----------------------------------------------------------------------===//
// This operation converts from a struct to a bundle
// type, or visa-versa. FIRRTL source/destination types must be passive.
def HWStructCastOp : FIRRTLOp<"hwStructCast", [Pure]> {
let arguments = (ins AnyType:$input);
let results = (outs AnyType:$result);
let assemblyFormat =
"$input attr-dict `:` functional-type($input, $result)";
let hasVerifier = 1;
}
def BitCastOp: FIRRTLOp<"bitcast", [Pure]> {
let summary = [{
Reinterpret one value to another value of the same size and
potentially different type. This op is lowered to hw::BitCastOp.
}];
let arguments = (ins FIRRTLBaseType:$input);
let results = (outs PassiveType:$result);
let hasVerifier = 1;
let hasFolder = 1;