-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathriscv.py
4056 lines (3079 loc) · 115 KB
/
riscv.py
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
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Sequence, Set
from io import StringIO
from itertools import chain
from typing import IO, Annotated, Generic, Literal, TypeAlias, TypeVar
from typing_extensions import Self, assert_never
from xdsl.backend.register_allocatable import (
HasRegisterConstraints,
RegisterConstraints,
)
from xdsl.backend.register_type import RegisterType
from xdsl.dialects.builtin import (
AnyIntegerAttr,
IndexType,
IntegerAttr,
IntegerType,
ModuleOp,
Signedness,
StringAttr,
UnitAttr,
i32,
)
from xdsl.dialects.utils import FastMathAttrBase, FastMathFlag
from xdsl.ir import (
Attribute,
Block,
Data,
Dialect,
Operation,
Region,
SSAValue,
)
from xdsl.irdl import (
IRDLOperation,
OptSingleBlockRegion,
attr_def,
base,
irdl_attr_definition,
irdl_op_definition,
operand_def,
opt_attr_def,
region_def,
result_def,
traits_def,
var_operand_def,
var_result_def,
)
from xdsl.parser import AttrParser, Parser, UnresolvedOperand
from xdsl.pattern_rewriter import RewritePattern
from xdsl.printer import Printer
from xdsl.traits import (
ConstantLike,
EffectInstance,
HasCanonicalizationPatternsTrait,
IsolatedFromAbove,
IsTerminator,
MemoryEffect,
MemoryEffectKind,
NoTerminator,
Pure,
)
from xdsl.utils.exceptions import VerifyException
from xdsl.utils.hints import isa
@irdl_attr_definition
class FastMathFlagsAttr(FastMathAttrBase):
"""
riscv.fastmath is a mirror of LLVMs fastmath flags.
"""
name = "riscv.fastmath"
def __init__(self, flags: None | Sequence[FastMathFlag] | Literal["none", "fast"]):
# irdl_attr_definition defines an __init__ if none is defined, so we need to
# explicitely define one here.
super().__init__(flags)
class RISCVRegisterType(RegisterType):
"""
A RISC-V register type.
"""
@classmethod
def parse_parameters(cls, parser: AttrParser) -> Sequence[Attribute]:
if parser.parse_optional_punctuation("<") is not None:
name = parser.parse_identifier()
parser.parse_punctuation(">")
if not name.startswith("j"):
assert name in cls.abi_index_by_name(), f"{name}"
else:
name = ""
return cls._parameters_from_spelling(name)
def verify(self) -> None:
name = self.spelling.data
if not self.is_allocated or name.startswith("j"):
return
if name not in type(self).abi_index_by_name():
raise VerifyException(f"{name} not in {self.instruction_set_name()}")
@classmethod
@abstractmethod
def a_register(cls, index: int) -> Self:
raise NotImplementedError()
RV32I_INDEX_BY_NAME = {
"zero": 0,
"ra": 1,
"sp": 2,
"gp": 3,
"tp": 4,
"t0": 5,
"t1": 6,
"t2": 7,
"fp": 8,
"s0": 8,
"s1": 9,
"a0": 10,
"a1": 11,
"a2": 12,
"a3": 13,
"a4": 14,
"a5": 15,
"a6": 16,
"a7": 17,
"s2": 18,
"s3": 19,
"s4": 20,
"s5": 21,
"s6": 22,
"s7": 23,
"s8": 24,
"s9": 25,
"s10": 26,
"s11": 27,
"t3": 28,
"t4": 29,
"t5": 30,
"t6": 31,
}
@irdl_attr_definition
class IntRegisterType(RISCVRegisterType):
"""
A RISC-V register type.
"""
name = "riscv.reg"
@classmethod
def unallocated(cls) -> IntRegisterType:
return Registers.UNALLOCATED_INT
@classmethod
def instruction_set_name(cls) -> str:
return "RV32I"
@classmethod
def abi_index_by_name(cls) -> dict[str, int]:
return RV32I_INDEX_BY_NAME
@classmethod
def a_register(cls, index: int) -> IntRegisterType:
return Registers.A[index]
RV32F_INDEX_BY_NAME = {
"ft0": 0,
"ft1": 1,
"ft2": 2,
"ft3": 3,
"ft4": 4,
"ft5": 5,
"ft6": 6,
"ft7": 7,
"fs0": 8,
"fs1": 9,
"fa0": 10,
"fa1": 11,
"fa2": 12,
"fa3": 13,
"fa4": 14,
"fa5": 15,
"fa6": 16,
"fa7": 17,
"fs2": 18,
"fs3": 19,
"fs4": 20,
"fs5": 21,
"fs6": 22,
"fs7": 23,
"fs8": 24,
"fs9": 25,
"fs10": 26,
"fs11": 27,
"ft8": 28,
"ft9": 29,
"ft10": 30,
"ft11": 31,
}
@irdl_attr_definition
class FloatRegisterType(RISCVRegisterType):
"""
A RISC-V register type.
"""
name = "riscv.freg"
@classmethod
def unallocated(cls) -> FloatRegisterType:
return Registers.UNALLOCATED_FLOAT
@classmethod
def instruction_set_name(cls) -> str:
return "RV32F"
@classmethod
def abi_index_by_name(cls) -> dict[str, int]:
return RV32F_INDEX_BY_NAME
@classmethod
def a_register(cls, index: int) -> FloatRegisterType:
return Registers.FA[index]
RDInvT = TypeVar("RDInvT", bound=RISCVRegisterType)
RSInvT = TypeVar("RSInvT", bound=RISCVRegisterType)
RS1InvT = TypeVar("RS1InvT", bound=RISCVRegisterType)
RS2InvT = TypeVar("RS2InvT", bound=RISCVRegisterType)
class Registers(ABC):
"""Namespace for named register constants."""
UNALLOCATED_INT = IntRegisterType("")
ZERO = IntRegisterType("zero")
RA = IntRegisterType("ra")
SP = IntRegisterType("sp")
GP = IntRegisterType("gp")
TP = IntRegisterType("tp")
T0 = IntRegisterType("t0")
T1 = IntRegisterType("t1")
T2 = IntRegisterType("t2")
FP = IntRegisterType("fp")
S0 = IntRegisterType("s0")
S1 = IntRegisterType("s1")
A0 = IntRegisterType("a0")
A1 = IntRegisterType("a1")
A2 = IntRegisterType("a2")
A3 = IntRegisterType("a3")
A4 = IntRegisterType("a4")
A5 = IntRegisterType("a5")
A6 = IntRegisterType("a6")
A7 = IntRegisterType("a7")
S2 = IntRegisterType("s2")
S3 = IntRegisterType("s3")
S4 = IntRegisterType("s4")
S5 = IntRegisterType("s5")
S6 = IntRegisterType("s6")
S7 = IntRegisterType("s7")
S8 = IntRegisterType("s8")
S9 = IntRegisterType("s9")
S10 = IntRegisterType("s10")
S11 = IntRegisterType("s11")
T3 = IntRegisterType("t3")
T4 = IntRegisterType("t4")
T5 = IntRegisterType("t5")
T6 = IntRegisterType("t6")
UNALLOCATED_FLOAT = FloatRegisterType("")
FT0 = FloatRegisterType("ft0")
FT1 = FloatRegisterType("ft1")
FT2 = FloatRegisterType("ft2")
FT3 = FloatRegisterType("ft3")
FT4 = FloatRegisterType("ft4")
FT5 = FloatRegisterType("ft5")
FT6 = FloatRegisterType("ft6")
FT7 = FloatRegisterType("ft7")
FS0 = FloatRegisterType("fs0")
FS1 = FloatRegisterType("fs1")
FA0 = FloatRegisterType("fa0")
FA1 = FloatRegisterType("fa1")
FA2 = FloatRegisterType("fa2")
FA3 = FloatRegisterType("fa3")
FA4 = FloatRegisterType("fa4")
FA5 = FloatRegisterType("fa5")
FA6 = FloatRegisterType("fa6")
FA7 = FloatRegisterType("fa7")
FS2 = FloatRegisterType("fs2")
FS3 = FloatRegisterType("fs3")
FS4 = FloatRegisterType("fs4")
FS5 = FloatRegisterType("fs5")
FS6 = FloatRegisterType("fs6")
FS7 = FloatRegisterType("fs7")
FS8 = FloatRegisterType("fs8")
FS9 = FloatRegisterType("fs9")
FS10 = FloatRegisterType("fs10")
FS11 = FloatRegisterType("fs11")
FT8 = FloatRegisterType("ft8")
FT9 = FloatRegisterType("ft9")
FT10 = FloatRegisterType("ft10")
FT11 = FloatRegisterType("ft11")
# register classes:
A = (A0, A1, A2, A3, A4, A5, A6, A7)
T = (T0, T1, T2, T3, T4, T5, T6)
S = (S0, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11)
FA = (FA0, FA1, FA2, FA3, FA4, FA5, FA6, FA7)
FT = (FT0, FT1, FT2, FT3, FT4, FT5, FT6, FT7, FT8, FT9, FT10, FT11)
FS = (FS0, FS1, FS2, FS3, FS4, FS5, FS6, FS7, FS8, FS9, FS10, FS11)
ui5 = IntegerType(5, Signedness.UNSIGNED)
si20 = IntegerType(20, Signedness.SIGNED)
si12 = IntegerType(12, Signedness.SIGNED)
i12 = IntegerType(12, Signedness.SIGNLESS)
i20 = IntegerType(20, Signedness.SIGNLESS)
UImm5Attr = IntegerAttr[Annotated[IntegerType, ui5]]
SImm12Attr = IntegerAttr[Annotated[IntegerType, si12]]
SImm20Attr = IntegerAttr[Annotated[IntegerType, si20]]
Imm12Attr = IntegerAttr[Annotated[IntegerType, i12]]
Imm20Attr = IntegerAttr[Annotated[IntegerType, i20]]
Imm32Attr = IntegerAttr[Annotated[IntegerType, i32]]
@irdl_attr_definition
class LabelAttr(Data[str]):
name = "riscv.label"
@classmethod
def parse_parameter(cls, parser: AttrParser) -> str:
with parser.in_angle_brackets():
return parser.parse_str_literal()
def print_parameter(self, printer: Printer) -> None:
with printer.in_angle_brackets():
printer.print_string_literal(self.data)
class RISCVAsmOperation(HasRegisterConstraints, IRDLOperation, ABC):
"""
Base class for operations that can be a part of RISC-V assembly printing.
"""
def get_register_constraints(self) -> RegisterConstraints:
return RegisterConstraints(self.operands, self.results, ())
@abstractmethod
def assembly_line(self) -> str | None:
raise NotImplementedError()
class RISCVCustomFormatOperation(IRDLOperation, ABC):
"""
Base class for RISC-V operations that specialize their custom format.
"""
@classmethod
def parse(cls, parser: Parser) -> Self:
args = cls.parse_unresolved_operands(parser)
custom_attributes = cls.custom_parse_attributes(parser)
remaining_attributes = parser.parse_optional_attr_dict()
# TODO ensure distinct keys for attributes
attributes = custom_attributes | remaining_attributes
regions = parser.parse_region_list()
pos = parser.pos
operand_types, result_types = cls.parse_op_type(parser)
operands = parser.resolve_operands(args, operand_types, pos)
return cls.create(
operands=operands,
result_types=result_types,
attributes=attributes,
regions=regions,
)
@classmethod
def parse_unresolved_operands(cls, parser: Parser) -> list[UnresolvedOperand]:
"""
Parse a list of comma separated unresolved operands.
Notice that this method will consume trailing comma.
"""
if operand := parser.parse_optional_unresolved_operand():
operands = [operand]
while parser.parse_optional_punctuation(",") and (
operand := parser.parse_optional_unresolved_operand()
):
operands.append(operand)
return operands
return []
@classmethod
def custom_parse_attributes(cls, parser: Parser) -> dict[str, Attribute]:
"""
Parse attributes with custom syntax. Subclasses may override this method.
"""
return parser.parse_optional_attr_dict()
@classmethod
def parse_op_type(
cls, parser: Parser
) -> tuple[Sequence[Attribute], Sequence[Attribute]]:
parser.parse_punctuation(":")
func_type = parser.parse_function_type()
return func_type.inputs.data, func_type.outputs.data
def print(self, printer: Printer) -> None:
if self.operands:
printer.print(" ")
printer.print_list(self.operands, printer.print_operand)
printed_attributes = self.custom_print_attributes(printer)
unprinted_attributes = {
name: attr
for name, attr in self.attributes.items()
if name not in printed_attributes
}
printer.print_op_attributes(unprinted_attributes)
printer.print_regions(self.regions)
self.print_op_type(printer)
def custom_print_attributes(self, printer: Printer) -> Set[str]:
"""
Print attributes with custom syntax. Return the names of the attributes printed. Subclasses may override this method.
"""
printer.print_op_attributes(self.attributes)
return self.attributes.keys()
def print_op_type(self, printer: Printer) -> None:
printer.print(" : ")
printer.print_operation_type(self)
AssemblyInstructionArg: TypeAlias = (
AnyIntegerAttr | LabelAttr | SSAValue | IntRegisterType | str | int
)
class RISCVInstruction(RISCVAsmOperation, ABC):
"""
Base class for operations that can be a part of RISC-V assembly printing. Must
represent an instruction in the RISC-V instruction set, and have the following format:
name arg0, arg1, arg2 # comment
The name of the operation will be used as the RISC-V assembly instruction name.
"""
comment = opt_attr_def(StringAttr)
"""
An optional comment that will be printed along with the instruction.
"""
@abstractmethod
def assembly_line_args(self) -> tuple[AssemblyInstructionArg | None, ...]:
"""
The arguments to the instruction, in the order they should be printed in the
assembly.
"""
raise NotImplementedError()
def assembly_instruction_name(self) -> str:
"""
By default, the name of the instruction is the same as the name of the operation.
"""
return Dialect.split_name(self.name)[1]
def assembly_line(self) -> str | None:
# default assembly code generator
instruction_name = self.assembly_instruction_name()
arg_str = ", ".join(
_assembly_arg_str(arg)
for arg in self.assembly_line_args()
if arg is not None
)
return _assembly_line(instruction_name, arg_str, self.comment)
# region Assembly printing
def _append_comment(line: str, comment: StringAttr | None) -> str:
if comment is None:
return line
padding = " " * max(0, 48 - len(line))
return f"{line}{padding} # {comment.data}"
def _assembly_arg_str(arg: AssemblyInstructionArg) -> str:
if isa(arg, AnyIntegerAttr):
return f"{arg.value.data}"
elif isinstance(arg, int):
return f"{arg}"
elif isinstance(arg, LabelAttr):
return arg.data
elif isinstance(arg, str):
return arg
elif isinstance(arg, IntRegisterType):
return arg.register_name
elif isinstance(arg, FloatRegisterType):
return arg.register_name
else:
if isinstance(arg.type, IntRegisterType):
reg = arg.type.register_name
return reg
elif isinstance(arg.type, FloatRegisterType):
reg = arg.type.register_name
return reg
else:
raise ValueError(f"Unexpected register type {arg.type}")
assert_never(arg)
def _assembly_line(
name: str,
arg_str: str,
comment: StringAttr | None = None,
is_indented: bool = True,
) -> str:
code = " " if is_indented else ""
code += name
if arg_str:
code += f" {arg_str}"
code = _append_comment(code, comment)
return code
def print_assembly(module: ModuleOp, output: IO[str]) -> None:
for op in module.body.walk():
assert isinstance(op, RISCVAsmOperation), f"{op}"
asm = op.assembly_line()
if asm is not None:
print(asm, file=output)
def riscv_code(module: ModuleOp) -> str:
stream = StringIO()
print_assembly(module, stream)
return stream.getvalue()
# endregion
# region Base Operation classes
class RdRsRsOperation(
Generic[RDInvT, RS1InvT, RS2InvT], RISCVCustomFormatOperation, RISCVInstruction, ABC
):
"""
A base class for RISC-V operations that have one destination register, and two source
registers.
This is called R-Type in the RISC-V specification.
"""
rd = result_def(RDInvT)
rs1 = operand_def(RS1InvT)
rs2 = operand_def(RS2InvT)
def __init__(
self,
rs1: Operation | SSAValue,
rs2: Operation | SSAValue,
*,
rd: RDInvT,
comment: str | StringAttr | None = None,
):
if isinstance(comment, str):
comment = StringAttr(comment)
super().__init__(
operands=[rs1, rs2],
attributes={
"comment": comment,
},
result_types=[rd],
)
def assembly_line_args(self) -> tuple[AssemblyInstructionArg, ...]:
return self.rd, self.rs1, self.rs2
class RdRsRsFloatOperationWithFastMath(
RISCVCustomFormatOperation, RISCVInstruction, ABC
):
"""
A base class for RISC-V operations that have one destination floating-point register,
and two source floating-point registers and can be annotated with fastmath flags.
This is called R-Type in the RISC-V specification.
"""
rd = result_def(FloatRegisterType)
rs1 = operand_def(FloatRegisterType)
rs2 = operand_def(FloatRegisterType)
fastmath = opt_attr_def(FastMathFlagsAttr)
def __init__(
self,
rs1: Operation | SSAValue,
rs2: Operation | SSAValue,
*,
rd: FloatRegisterType,
fastmath: FastMathFlagsAttr | None = None,
comment: str | StringAttr | None = None,
):
if isinstance(comment, str):
comment = StringAttr(comment)
super().__init__(
operands=[rs1, rs2],
attributes={
"fastmath": fastmath,
"comment": comment,
},
result_types=[rd],
)
def assembly_line_args(self) -> tuple[AssemblyInstructionArg, ...]:
return self.rd, self.rs1, self.rs2
@classmethod
def custom_parse_attributes(cls, parser: Parser) -> dict[str, Attribute]:
attributes = dict[str, Attribute]()
flags = FastMathFlagsAttr("none")
if parser.parse_optional_keyword("fastmath") is not None:
flags = FastMathFlagsAttr(FastMathFlagsAttr.parse_parameter(parser))
attributes["fastmath"] = flags
return attributes
def custom_print_attributes(self, printer: Printer) -> Set[str]:
if self.fastmath is not None and self.fastmath != FastMathFlagsAttr("none"):
printer.print(" fastmath")
self.fastmath.print_parameter(printer)
return {"fastmath"}
class RdImmIntegerOperation(RISCVCustomFormatOperation, RISCVInstruction, ABC):
"""
A base class for RISC-V operations that have one destination register, and one
immediate operand (e.g. U-Type and J-Type instructions in the RISC-V spec).
"""
rd = result_def(IntRegisterType)
immediate = attr_def(base(Imm20Attr) | base(LabelAttr))
def __init__(
self,
immediate: int | AnyIntegerAttr | str | LabelAttr,
*,
rd: IntRegisterType | str | None = None,
comment: str | StringAttr | None = None,
):
if isinstance(immediate, int):
immediate = IntegerAttr(immediate, i20)
elif isinstance(immediate, str):
immediate = LabelAttr(immediate)
if rd is None:
rd = IntRegisterType.unallocated()
elif isinstance(rd, str):
rd = IntRegisterType(rd)
if isinstance(comment, str):
comment = StringAttr(comment)
super().__init__(
result_types=[rd],
attributes={
"immediate": immediate,
"comment": comment,
},
)
def assembly_line_args(self) -> tuple[AssemblyInstructionArg, ...]:
return self.rd, self.immediate
@classmethod
def custom_parse_attributes(cls, parser: Parser) -> dict[str, Attribute]:
attributes = dict[str, Attribute]()
attributes["immediate"] = parse_immediate_value(parser, i20)
return attributes
def custom_print_attributes(self, printer: Printer) -> Set[str]:
printer.print(" ")
print_immediate_value(printer, self.immediate)
return {"immediate"}
class RdImmJumpOperation(RISCVCustomFormatOperation, RISCVInstruction, ABC):
"""
In the RISC-V spec, this is the same as `RdImmOperation`. For jumps, the `rd` register
is neither an operand, because the stored value is overwritten, nor a result value,
because the value in `rd` is not defined after the jump back. So the `rd` makes the
most sense as an attribute.
"""
rd = opt_attr_def(IntRegisterType)
"""
The rd register here is not a register storing the result, rather the register where
the program counter is stored before jumping.
"""
immediate = attr_def(base(SImm20Attr) | base(LabelAttr))
def __init__(
self,
immediate: int | SImm20Attr | str | LabelAttr,
*,
rd: IntRegisterType | str | None = None,
comment: str | StringAttr | None = None,
):
if isinstance(immediate, int):
immediate = IntegerAttr(immediate, si20)
elif isinstance(immediate, str):
immediate = LabelAttr(immediate)
if isinstance(rd, str):
rd = IntRegisterType(rd)
if isinstance(comment, str):
comment = StringAttr(comment)
super().__init__(
attributes={
"immediate": immediate,
"rd": rd,
"comment": comment,
}
)
def assembly_line_args(self) -> tuple[AssemblyInstructionArg | None, ...]:
return self.rd, self.immediate
@classmethod
def custom_parse_attributes(cls, parser: Parser) -> dict[str, Attribute]:
attributes = dict[str, Attribute]()
attributes["immediate"] = parse_immediate_value(parser, si20)
if parser.parse_optional_punctuation(","):
attributes["rd"] = parser.parse_attribute()
return attributes
def custom_print_attributes(self, printer: Printer) -> Set[str]:
printer.print(" ")
print_immediate_value(printer, self.immediate)
if self.rd is not None:
printer.print(", ")
printer.print_attribute(self.rd)
return {"immediate", "rd"}
def print_op_type(self, printer: Printer) -> None:
return
@classmethod
def parse_op_type(
cls, parser: Parser
) -> tuple[Sequence[Attribute], Sequence[Attribute]]:
return (), ()
class RdRsImmIntegerOperation(RISCVCustomFormatOperation, RISCVInstruction, ABC):
"""
A base class for RISC-V operations that have one destination register, one source
register and one immediate operand.
This is called I-Type in the RISC-V specification.
"""
rd = result_def(IntRegisterType)
rs1 = operand_def(IntRegisterType)
immediate = attr_def(base(SImm12Attr) | base(LabelAttr))
def __init__(
self,
rs1: Operation | SSAValue,
immediate: int | SImm12Attr | str | LabelAttr,
*,
rd: IntRegisterType | str | None = None,
comment: str | StringAttr | None = None,
):
if isinstance(immediate, int):
immediate = IntegerAttr(immediate, si12)
elif isinstance(immediate, str):
immediate = LabelAttr(immediate)
if rd is None:
rd = IntRegisterType.unallocated()
elif isinstance(rd, str):
rd = IntRegisterType(rd)
if isinstance(comment, str):
comment = StringAttr(comment)
super().__init__(
operands=[rs1],
result_types=[rd],
attributes={
"immediate": immediate,
"comment": comment,
},
)
def assembly_line_args(self) -> tuple[AssemblyInstructionArg, ...]:
return self.rd, self.rs1, self.immediate
@classmethod
def custom_parse_attributes(cls, parser: Parser) -> dict[str, Attribute]:
attributes = dict[str, Attribute]()
attributes["immediate"] = parse_immediate_value(parser, si12)
return attributes
def custom_print_attributes(self, printer: Printer) -> Set[str]:
printer.print(", ")
print_immediate_value(printer, self.immediate)
return {"immediate"}
class RdRsImmShiftOperation(RISCVCustomFormatOperation, RISCVInstruction, ABC):
"""
A base class for RISC-V operations that have one destination register, one source
register and one immediate operand.
This is called I-Type in the RISC-V specification.
Shifts by a constant are encoded as a specialization of the I-type format.
The shift amount is encoded in the lower 5 bits of the I-immediate field for RV32
For RV32I, SLLI, SRLI, and SRAI generate an illegal instruction exception if
imm[5] 6 != 0 but the shift amount is encoded in the lower 6 bits of the I-immediate field for RV64I.
"""
rd = result_def(IntRegisterType)
rs1 = operand_def(IntRegisterType)
immediate = attr_def(base(UImm5Attr) | base(LabelAttr))
def __init__(
self,
rs1: Operation | SSAValue,
immediate: int | UImm5Attr | str | LabelAttr,
*,
rd: IntRegisterType | str | None = None,
comment: str | StringAttr | None = None,
):
if isinstance(immediate, int):
immediate = IntegerAttr(immediate, ui5)
elif isinstance(immediate, str):
immediate = LabelAttr(immediate)
if rd is None:
rd = IntRegisterType.unallocated()
elif isinstance(rd, str):
rd = IntRegisterType(rd)
if isinstance(comment, str):
comment = StringAttr(comment)
super().__init__(
operands=[rs1],
result_types=[rd],
attributes={
"immediate": immediate,
"comment": comment,
},
)
def assembly_line_args(self) -> tuple[AssemblyInstructionArg, ...]:
return self.rd, self.rs1, self.immediate
@classmethod
def custom_parse_attributes(cls, parser: Parser) -> dict[str, Attribute]:
attributes = dict[str, Attribute]()
attributes["immediate"] = parse_immediate_value(parser, ui5)
return attributes
def custom_print_attributes(self, printer: Printer) -> Set[str]:
printer.print(", ")
print_immediate_value(printer, self.immediate)
return {"immediate"}
class RdRsImmJumpOperation(RISCVCustomFormatOperation, RISCVInstruction, ABC):
"""
A base class for RISC-V operations that have one destination register, one source
register and one immediate operand.
This is called I-Type in the RISC-V specification.
In the RISC-V spec, this is the same as `RdRsImmOperation`. For jumps, the `rd` register
is neither an operand, because the stored value is overwritten, nor a result value,
because the value in `rd` is not defined after the jump back. So the `rd` makes the
most sense as an attribute.
"""
rs1 = operand_def(IntRegisterType)
rd = opt_attr_def(IntRegisterType)
"""
The rd register here is not a register storing the result, rather the register where
the program counter is stored before jumping.
"""
immediate = attr_def(base(SImm12Attr) | base(LabelAttr))
def __init__(
self,
rs1: Operation | SSAValue,
immediate: int | SImm12Attr | str | LabelAttr,
*,
rd: IntRegisterType | str | None = None,
comment: str | StringAttr | None = None,
):
if isinstance(immediate, int):
immediate = IntegerAttr(immediate, si12)
elif isinstance(immediate, str):
immediate = LabelAttr(immediate)
if isinstance(rd, str):
rd = IntRegisterType(rd)
if isinstance(comment, str):
comment = StringAttr(comment)
super().__init__(
operands=[rs1],
attributes={
"immediate": immediate,
"rd": rd,
"comment": comment,
},
)
def assembly_line_args(self) -> tuple[AssemblyInstructionArg | None, ...]:
return self.rd, self.rs1, self.immediate
@classmethod
def custom_parse_attributes(cls, parser: Parser) -> dict[str, Attribute]:
attributes = dict[str, Attribute]()
attributes["immediate"] = parse_immediate_value(parser, si12)
if parser.parse_optional_punctuation(","):
attributes["rd"] = parser.parse_attribute()
return attributes
def custom_print_attributes(self, printer: Printer) -> Set[str]:
printer.print(", ")
print_immediate_value(printer, self.immediate)
if self.rd is not None:
printer.print(", ")
printer.print_attribute(self.rd)
return {"immediate", "rd"}
class RdRsOperation(
Generic[RDInvT, RSInvT], RISCVCustomFormatOperation, RISCVInstruction, ABC
):
"""
A base class for RISC-V pseudo-instructions that have one destination register and one
source register.
"""
rd = result_def(RDInvT)
rs = operand_def(RSInvT)
def __init__(
self,
rs: Operation | SSAValue,
*,
rd: RDInvT,
comment: str | StringAttr | None = None,
):
if isinstance(comment, str):
comment = StringAttr(comment)
super().__init__(
operands=[rs],
result_types=[rd],
attributes={"comment": comment},
)
def assembly_line_args(self) -> tuple[AssemblyInstructionArg, ...]:
return self.rd, self.rs
class RsRsOffIntegerOperation(RISCVCustomFormatOperation, RISCVInstruction, ABC):
"""
A base class for RISC-V operations that have one source register and a destination
register, and an offset.
This is called B-Type in the RISC-V specification.
"""
rs1 = operand_def(IntRegisterType)
rs2 = operand_def(IntRegisterType)
offset = attr_def(base(SImm12Attr) | base(LabelAttr))
def __init__(
self,
rs1: Operation | SSAValue,
rs2: Operation | SSAValue,