codecin 7.22.10__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codecin/__init__.py +27 -0
- codecin/aot.py +1057 -0
- codecin/assembler.py +619 -0
- codecin/cbackend.py +3024 -0
- codecin/cin.py +4265 -0
- codecin/cli.py +670 -0
- codecin/codecin_native.dll +0 -0
- codecin/config.py +50 -0
- codecin/console.py +183 -0
- codecin/cpu.py +312 -0
- codecin/crom.py +449 -0
- codecin/cvm.py +708 -0
- codecin/disasm.py +149 -0
- codecin/environment.py +176 -0
- codecin/errors.py +54 -0
- codecin/isa.py +560 -0
- codecin/lib/array/pic.toml +10 -0
- codecin/lib/array/src/array.cin +103 -0
- codecin/lib/bigint/pic.toml +10 -0
- codecin/lib/bigint/src/bigint.cin +589 -0
- codecin/lib/bits/pic.toml +10 -0
- codecin/lib/bits/src/bits.cin +143 -0
- codecin/lib/bitset/pic.toml +10 -0
- codecin/lib/bitset/src/bitset.cin +374 -0
- codecin/lib/codec/pic.toml +10 -0
- codecin/lib/codec/src/codec.cin +563 -0
- codecin/lib/combin/pic.toml +10 -0
- codecin/lib/combin/src/combin.cin +414 -0
- codecin/lib/conv/pic.toml +10 -0
- codecin/lib/conv/src/conv.cin +151 -0
- codecin/lib/cppstd/pic.toml +10 -0
- codecin/lib/cppstd/src/cppstd.cin +418 -0
- codecin/lib/cstd/pic.toml +10 -0
- codecin/lib/cstd/src/cstd.cin +424 -0
- codecin/lib/csv/pic.toml +10 -0
- codecin/lib/csv/src/csv.cin +405 -0
- codecin/lib/dp/pic.toml +10 -0
- codecin/lib/dp/src/dp.cin +325 -0
- codecin/lib/ffi/pic.toml +10 -0
- codecin/lib/ffi/src/ffi.cin +163 -0
- codecin/lib/fmt/pic.toml +10 -0
- codecin/lib/fmt/src/fmt.cin +325 -0
- codecin/lib/frac/pic.toml +10 -0
- codecin/lib/frac/src/frac.cin +252 -0
- codecin/lib/gostd/pic.toml +10 -0
- codecin/lib/gostd/src/gostd.cin +415 -0
- codecin/lib/graph/pic.toml +10 -0
- codecin/lib/graph/src/graph.cin +367 -0
- codecin/lib/gui/pic.toml +10 -0
- codecin/lib/gui/src/gui.cin +218 -0
- codecin/lib/hash/pic.toml +10 -0
- codecin/lib/hash/src/hash.cin +67 -0
- codecin/lib/heap/pic.toml +10 -0
- codecin/lib/heap/src/heap.cin +199 -0
- codecin/lib/io/pic.toml +10 -0
- codecin/lib/io/src/io.cin +141 -0
- codecin/lib/json/pic.toml +10 -0
- codecin/lib/json/src/json.cin +84 -0
- codecin/lib/key/pic.toml +10 -0
- codecin/lib/key/src/key.cin +78 -0
- codecin/lib/math/pic.toml +10 -0
- codecin/lib/math/src/math.cin +50 -0
- codecin/lib/matrix/pic.toml +10 -0
- codecin/lib/matrix/src/matrix.cin +155 -0
- codecin/lib/net/pic.toml +10 -0
- codecin/lib/net/src/net.cin +171 -0
- codecin/lib/path/pic.toml +10 -0
- codecin/lib/path/src/path.cin +372 -0
- codecin/lib/queue/pic.toml +10 -0
- codecin/lib/queue/src/queue.cin +112 -0
- codecin/lib/rand/pic.toml +10 -0
- codecin/lib/rand/src/rand.cin +46 -0
- codecin/lib/set/pic.toml +10 -0
- codecin/lib/set/src/set.cin +269 -0
- codecin/lib/sort/pic.toml +10 -0
- codecin/lib/sort/src/sort.cin +93 -0
- codecin/lib/stat/pic.toml +10 -0
- codecin/lib/stat/src/stat.cin +138 -0
- codecin/lib/str/pic.toml +10 -0
- codecin/lib/str/src/str.cin +54 -0
- codecin/lib/termux/pic.toml +10 -0
- codecin/lib/termux/src/termux.cin +118 -0
- codecin/lib/test/pic.toml +10 -0
- codecin/lib/test/src/test.cin +74 -0
- codecin/lib/text/pic.toml +10 -0
- codecin/lib/text/src/text.cin +323 -0
- codecin/lib/time/pic.toml +10 -0
- codecin/lib/time/src/time.cin +54 -0
- codecin/lib/token/pic.toml +10 -0
- codecin/lib/token/src/token.cin +183 -0
- codecin/lib/tree/pic.toml +10 -0
- codecin/lib/tree/src/tree.cin +256 -0
- codecin/lib/unionfind/pic.toml +10 -0
- codecin/lib/unionfind/src/unionfind.cin +115 -0
- codecin/lib/validate/pic.toml +10 -0
- codecin/lib/validate/src/validate.cin +148 -0
- codecin/lib/vec/pic.toml +10 -0
- codecin/lib/vec/src/vec.cin +88 -0
- codecin/logger.py +145 -0
- codecin/memory.py +306 -0
- codecin/mkn.py +916 -0
- codecin/native/aot/aot.go +114 -0
- codecin/native/aot/stub_main.go.txt +23 -0
- codecin/native/build.ps1 +33 -0
- codecin/native/build.sh +48 -0
- codecin/native/cmd/cincc/main.go +66 -0
- codecin/native/compiler/codegen.go +2238 -0
- codecin/native/compiler/compile_test.go +1069 -0
- codecin/native/compiler/parser.go +1331 -0
- codecin/native/compiler/syscalls.go +166 -0
- codecin/native/compiler/tokenizer.go +394 -0
- codecin/native/compiler/types.go +217 -0
- codecin/native/engine/args.go +37 -0
- codecin/native/engine/audio.go +402 -0
- codecin/native/engine/audio_other.go +105 -0
- codecin/native/engine/audio_test.go +279 -0
- codecin/native/engine/audio_windows.go +190 -0
- codecin/native/engine/canvas.go +271 -0
- codecin/native/engine/console_other.go +9 -0
- codecin/native/engine/console_windows.go +43 -0
- codecin/native/engine/crom.go +86 -0
- codecin/native/engine/encode.go +93 -0
- codecin/native/engine/engine_test.go +198 -0
- codecin/native/engine/ffi_nocgo.go +20 -0
- codecin/native/engine/ffi_registry.go +69 -0
- codecin/native/engine/ffi_unix.go +109 -0
- codecin/native/engine/ffi_windows.go +117 -0
- codecin/native/engine/gui.go +209 -0
- codecin/native/engine/gui_stub.go +13 -0
- codecin/native/engine/gui_test.go +148 -0
- codecin/native/engine/gui_windows.go +604 -0
- codecin/native/engine/gui_x11.go +723 -0
- codecin/native/engine/host_test.go +139 -0
- codecin/native/engine/hostcrypto.go +30 -0
- codecin/native/engine/hostdesktop.go +173 -0
- codecin/native/engine/hostnet.go +127 -0
- codecin/native/engine/isa_gen.go +689 -0
- codecin/native/engine/keyboard.go +432 -0
- codecin/native/engine/keyboard_other.go +94 -0
- codecin/native/engine/keyboard_stub.go +17 -0
- codecin/native/engine/keyboard_termios_darwin.go +9 -0
- codecin/native/engine/keyboard_termios_linux.go +9 -0
- codecin/native/engine/keyboard_test.go +246 -0
- codecin/native/engine/keyboard_windows.go +208 -0
- codecin/native/engine/keyboard_windows_test.go +123 -0
- codecin/native/engine/lineedit.go +262 -0
- codecin/native/engine/lineedit_test.go +105 -0
- codecin/native/engine/lineint_unix.go +17 -0
- codecin/native/engine/lineint_windows.go +19 -0
- codecin/native/engine/mem_other.go +37 -0
- codecin/native/engine/mem_windows.go +33 -0
- codecin/native/engine/native.go +640 -0
- codecin/native/engine/netsock.go +321 -0
- codecin/native/engine/ops_ext.go +515 -0
- codecin/native/engine/stdin.go +72 -0
- codecin/native/engine/stdin_other.go +9 -0
- codecin/native/engine/stdin_windows.go +60 -0
- codecin/native/engine/system.go +313 -0
- codecin/native/engine/termux.go +180 -0
- codecin/native/engine/version_gen.go +7 -0
- codecin/native/engine/vkb_darwin.go +62 -0
- codecin/native/engine/vkb_linux.go +95 -0
- codecin/native/engine/vkb_stub.go +11 -0
- codecin/native/engine/vm.go +1677 -0
- codecin/native/go.mod +3 -0
- codecin/native/ir/ir.go +48 -0
- codecin/native/main.go +448 -0
- codecin/native/mc/aarch64.go +165 -0
- codecin/native/mc/aarch64_test.go +30 -0
- codecin/native/mc/elf.go +88 -0
- codecin/native/mc/print_test.go +52 -0
- codecin/native/mc/x86_64.go +1262 -0
- codecin/native/mc/x86_64_test.go +102 -0
- codecin/native.py +432 -0
- codecin/native_codegen.py +987 -0
- codecin/nativegen.py +786 -0
- codecin/object.py +539 -0
- codecin/optimizer.py +236 -0
- codecin/packaging/__init__.py +46 -0
- codecin/packaging/archive.py +177 -0
- codecin/packaging/model.py +519 -0
- codecin/packaging/spec.py +193 -0
- codecin/packaging/store.py +372 -0
- codecin/packaging/toml.py +541 -0
- codecin/packaging/vcs.py +215 -0
- codecin/pic.py +1917 -0
- codecin/pic_api.py +374 -0
- codecin/pic_login.py +519 -0
- codecin/pic_registry.py +515 -0
- codecin/registers.py +130 -0
- codecin/sdgcc.py +493 -0
- codecin/stats.py +230 -0
- codecin/stdlib.py +138 -0
- codecin/toolchain.py +396 -0
- codecin/toolkit.py +26 -0
- codecin/version.py +260 -0
- codecin-7.22.10.dist-info/METADATA +1077 -0
- codecin-7.22.10.dist-info/RECORD +202 -0
- codecin-7.22.10.dist-info/WHEEL +5 -0
- codecin-7.22.10.dist-info/entry_points.txt +5 -0
- codecin-7.22.10.dist-info/licenses/LICENSE +7 -0
- codecin-7.22.10.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,987 @@
|
|
|
1
|
+
"""native AOT 后端: 把 CIN/ASM 编译后的指令流生成独立 Go 程序。
|
|
2
|
+
|
|
3
|
+
与旧的 AOT 路径 (嵌入 UCBC 字节码 + Go VM 解释执行) 不同, native 后端把
|
|
4
|
+
每条指令直接展开成 Go 语句:
|
|
5
|
+
|
|
6
|
+
* 整数/控制流/内存/SYS/ARM64/RISC-V 扩展/FP/Vector 指令直接生成
|
|
7
|
+
:class:`engine.NativeRuntime` 原语调用, 由 Go 编译器生成 x86-64/ARM64
|
|
8
|
+
机器码;
|
|
9
|
+
* 少数动态控制流/无法静态求值的内存操作数通过 ``rt.Exec`` 复用现有 VM
|
|
10
|
+
单指令语义, 作为受控回退;
|
|
11
|
+
* 生成代码不包含 UCBC 解码循环, 因此没有逐指令 opcode dispatch。
|
|
12
|
+
|
|
13
|
+
生成源码由 ``codecin.aot`` 写入临时模块并调用 ``go build`` (交叉编译由
|
|
14
|
+
GOOS/GOARCH 控制)。本模块只负责源码生成, 不执行构建。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import struct
|
|
18
|
+
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
|
|
19
|
+
|
|
20
|
+
from .isa import Cond
|
|
21
|
+
|
|
22
|
+
Instruction = Tuple[str, List[Tuple[Any, ...]]]
|
|
23
|
+
Segments = Sequence[Tuple[int, bytes]]
|
|
24
|
+
|
|
25
|
+
MASK64 = 0xFFFFFFFFFFFFFFFF
|
|
26
|
+
STACK_SLOT = 8
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class NativeCodegenError(Exception):
|
|
30
|
+
"""native 代码生成失败 (通常是无法解析的标签/操作数)。"""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _i64(v: int) -> int:
|
|
34
|
+
"""把无符号 64 位值转成 Go int64 字面量。"""
|
|
35
|
+
v &= MASK64
|
|
36
|
+
return v - (1 << 64) if v >= (1 << 63) else v
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _u64(v: int) -> int:
|
|
40
|
+
return int(v) & MASK64
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _float_bits(f: float) -> int:
|
|
44
|
+
return struct.unpack('<Q', struct.pack('<d', float(f)))[0]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _go_bytes(data: bytes, indent: str = '\t') -> str:
|
|
48
|
+
"""生成 Go []byte 字面量 (每行 16 字节)。"""
|
|
49
|
+
if not data:
|
|
50
|
+
return 'nil'
|
|
51
|
+
lines = ['[]byte{']
|
|
52
|
+
for i in range(0, len(data), 16):
|
|
53
|
+
chunk = data[i:i + 16]
|
|
54
|
+
lines.append(indent + '\t' + ', '.join(f'0x{b:02x}' for b in chunk) + ',')
|
|
55
|
+
lines.append(indent + '}')
|
|
56
|
+
return '\n'.join(lines)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class _Generator:
|
|
60
|
+
def __init__(self, instructions: Sequence[Instruction],
|
|
61
|
+
labels: Dict[str, int],
|
|
62
|
+
segments: Segments,
|
|
63
|
+
entry_pc: int,
|
|
64
|
+
mem_size: int,
|
|
65
|
+
sp: int,
|
|
66
|
+
heap_base: int,
|
|
67
|
+
max_steps: int,
|
|
68
|
+
program_name: str = 'program',
|
|
69
|
+
block_mode: bool = False):
|
|
70
|
+
self.instructions = list(instructions)
|
|
71
|
+
self.labels = dict(labels)
|
|
72
|
+
self.segments = list(segments)
|
|
73
|
+
self.entry_pc = int(entry_pc)
|
|
74
|
+
self.mem_size = int(mem_size)
|
|
75
|
+
self.sp = int(sp)
|
|
76
|
+
self.heap_base = int(heap_base)
|
|
77
|
+
self.max_steps = int(max_steps)
|
|
78
|
+
self.program_name = program_name
|
|
79
|
+
self.block_mode = block_mode
|
|
80
|
+
self.lines: List[str] = []
|
|
81
|
+
|
|
82
|
+
# ---------------- 基础设施 ----------------
|
|
83
|
+
|
|
84
|
+
def _emit(self, text: str = '') -> None:
|
|
85
|
+
self.lines.append(text)
|
|
86
|
+
|
|
87
|
+
def _code(self, text: str) -> None:
|
|
88
|
+
self.lines.append('\t' + text)
|
|
89
|
+
|
|
90
|
+
def _fail(self, call: str) -> None:
|
|
91
|
+
self._code(f'if e := {call}; e != "" {{')
|
|
92
|
+
if self.block_mode:
|
|
93
|
+
self._code('\trt.Abort(e)')
|
|
94
|
+
self._code('\treturn -2')
|
|
95
|
+
else:
|
|
96
|
+
self._code('\treturn rt.Abort(e)')
|
|
97
|
+
self._code('}')
|
|
98
|
+
|
|
99
|
+
def _target(self, arg: Tuple[Any, ...]) -> Optional[int]:
|
|
100
|
+
kind = arg[0]
|
|
101
|
+
if kind == 'label':
|
|
102
|
+
target = self.labels.get(arg[1])
|
|
103
|
+
elif kind == 'imm':
|
|
104
|
+
target = int(arg[1])
|
|
105
|
+
else:
|
|
106
|
+
return None
|
|
107
|
+
if target is None or target < 0 or target >= len(self.instructions):
|
|
108
|
+
return None
|
|
109
|
+
return int(target)
|
|
110
|
+
|
|
111
|
+
def _val(self, arg: Tuple[Any, ...]) -> Optional[str]:
|
|
112
|
+
"""把可静态求值的操作数转成 Go uint64 表达式。"""
|
|
113
|
+
kind = arg[0]
|
|
114
|
+
if kind == 'reg':
|
|
115
|
+
return f'rt.Reg({int(arg[1])})'
|
|
116
|
+
if kind == 'imm':
|
|
117
|
+
return f'uint64(0x{_u64(arg[1]):x})'
|
|
118
|
+
if kind == 'str':
|
|
119
|
+
return f'uint64(0x{_u64(arg[1]):x})'
|
|
120
|
+
if kind == 'float':
|
|
121
|
+
return f'uint64(0x{_float_bits(arg[1]):x})'
|
|
122
|
+
return None
|
|
123
|
+
|
|
124
|
+
def _addr(self, arg: Tuple[Any, ...]) -> Optional[str]:
|
|
125
|
+
kind = arg[0]
|
|
126
|
+
if kind == 'reg':
|
|
127
|
+
return f'rt.Reg({int(arg[1])})'
|
|
128
|
+
if kind == 'imm':
|
|
129
|
+
return f'uint64(0x{_u64(arg[1]):x})'
|
|
130
|
+
if kind == 'mem':
|
|
131
|
+
base = _i64(int(arg[1]))
|
|
132
|
+
off = _i64(int(arg[2]))
|
|
133
|
+
return f'rt.Addr({base}, {off})'
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
def _arg_lit(self, arg: Tuple[Any, ...]) -> str:
|
|
137
|
+
kind = arg[0]
|
|
138
|
+
if kind == 'label':
|
|
139
|
+
target = self.labels.get(arg[1])
|
|
140
|
+
if target is None:
|
|
141
|
+
raise NativeCodegenError(f'undefined label: {arg[1]}')
|
|
142
|
+
return f'{{Kind: engine.KindImm, Value: {target}}}'
|
|
143
|
+
if kind == 'reg':
|
|
144
|
+
return f'{{Kind: engine.KindReg, Value: {int(arg[1])}}}'
|
|
145
|
+
if kind == 'imm':
|
|
146
|
+
return f'{{Kind: engine.KindImm, Value: {_i64(int(arg[1]))}}}'
|
|
147
|
+
if kind == 'mem':
|
|
148
|
+
return (f'{{Kind: engine.KindMem, Value: {_i64(int(arg[1]))}, '
|
|
149
|
+
f'Extra: {_i64(int(arg[2]))}}}')
|
|
150
|
+
if kind == 'cond':
|
|
151
|
+
return f'{{Kind: engine.KindCond, Value: {self._cond_code(arg[1])}}}'
|
|
152
|
+
if kind == 'float':
|
|
153
|
+
return (f'{{Kind: engine.KindFloat, '
|
|
154
|
+
f'Value: {_i64(_float_bits(arg[1]))}}}')
|
|
155
|
+
if kind == 'str':
|
|
156
|
+
return f'{{Kind: engine.KindStr, Value: {_i64(int(arg[1]))}}}'
|
|
157
|
+
if kind == 'vec':
|
|
158
|
+
return f'{{Kind: engine.KindVec, Value: {int(arg[1])}}}'
|
|
159
|
+
if kind == 'veclane':
|
|
160
|
+
return (f'{{Kind: engine.KindVecLane, Value: {int(arg[1])}, '
|
|
161
|
+
f'Extra: {int(arg[2])}}}')
|
|
162
|
+
raise NativeCodegenError(f'unknown operand kind: {kind}')
|
|
163
|
+
|
|
164
|
+
def _out_lit(self, arg: Tuple[Any, ...]) -> str:
|
|
165
|
+
"""OUT 操作数 -> (kind, value, extra) 三个 Go 表达式。"""
|
|
166
|
+
kind = arg[0]
|
|
167
|
+
if kind == 'reg':
|
|
168
|
+
return 'engine.KindReg', str(int(arg[1])), '0'
|
|
169
|
+
if kind == 'imm':
|
|
170
|
+
return 'engine.KindImm', str(_i64(int(arg[1]))), '0'
|
|
171
|
+
if kind == 'str':
|
|
172
|
+
return 'engine.KindStr', str(_i64(int(arg[1]))), '0'
|
|
173
|
+
if kind == 'float':
|
|
174
|
+
return 'engine.KindFloat', str(_i64(_float_bits(arg[1]))), '0'
|
|
175
|
+
if kind == 'mem':
|
|
176
|
+
return ('engine.KindMem', str(_i64(int(arg[1]))),
|
|
177
|
+
str(_i64(int(arg[2]))))
|
|
178
|
+
if kind == 'vec':
|
|
179
|
+
return 'engine.KindVec', str(int(arg[1])), '0'
|
|
180
|
+
if kind == 'veclane':
|
|
181
|
+
return ('engine.KindVecLane', str(int(arg[1])),
|
|
182
|
+
str(int(arg[2])))
|
|
183
|
+
if kind == 'cond':
|
|
184
|
+
return 'engine.KindCond', str(self._cond_code(arg[1])), '0'
|
|
185
|
+
raise NativeCodegenError(f'unsupported OUT operand: {kind}')
|
|
186
|
+
|
|
187
|
+
@staticmethod
|
|
188
|
+
def _cond_code(name: str) -> int:
|
|
189
|
+
try:
|
|
190
|
+
return Cond.NAMES.index(str(name).upper())
|
|
191
|
+
except ValueError as e:
|
|
192
|
+
raise NativeCodegenError(f'unknown condition: {name}') from e
|
|
193
|
+
|
|
194
|
+
def _exec(self, op: str, args: Sequence[Tuple[Any, ...]], pc: int) -> None:
|
|
195
|
+
lits = ', '.join('engine.Arg' + self._arg_lit(a) for a in args)
|
|
196
|
+
self._fail(f'rt.Exec("{op}", []engine.Arg{{{lits}}}, {pc})')
|
|
197
|
+
|
|
198
|
+
# ---------------- 单条指令 ----------------
|
|
199
|
+
|
|
200
|
+
def _emit_ins(self, op: str, args: List[Tuple[Any, ...]],
|
|
201
|
+
idx: int) -> bool:
|
|
202
|
+
"""生成一条指令;返回 True 表示已经生成终止控制流。"""
|
|
203
|
+
|
|
204
|
+
# ---- 基本移动/算术 ----
|
|
205
|
+
if op == 'MOV':
|
|
206
|
+
v = self._val(args[1])
|
|
207
|
+
if v is None:
|
|
208
|
+
self._exec(op, args, idx)
|
|
209
|
+
else:
|
|
210
|
+
self._code(f'rt.Mov({int(args[0][1])}, {v})')
|
|
211
|
+
return False
|
|
212
|
+
if op in ('ADD', 'SUB', 'MUL', 'DIV', 'AND', 'OR', 'XOR',
|
|
213
|
+
'SHL', 'SHR'):
|
|
214
|
+
rd = int(args[0][1])
|
|
215
|
+
v = self._val(args[1])
|
|
216
|
+
if v is None:
|
|
217
|
+
self._exec(op, args, idx)
|
|
218
|
+
return False
|
|
219
|
+
method = {'ADD': 'Add', 'SUB': 'Sub', 'MUL': 'Mul', 'DIV': 'Div',
|
|
220
|
+
'AND': 'And', 'OR': 'Or', 'XOR': 'Xor',
|
|
221
|
+
'SHL': 'Shl', 'SHR': 'Shr'}[op]
|
|
222
|
+
if op == 'DIV':
|
|
223
|
+
self._fail(f'rt.Div({rd}, {v})')
|
|
224
|
+
else:
|
|
225
|
+
self._code(f'rt.{method}({rd}, {v})')
|
|
226
|
+
return False
|
|
227
|
+
if op == 'ASR':
|
|
228
|
+
# 两操作数形式是 Base ASR rd, rs; 三操作数形式是
|
|
229
|
+
# ARM64/RISC-V 扩展 ASR rd, rn, shift。
|
|
230
|
+
if len(args) >= 3:
|
|
231
|
+
rd, rs = int(args[0][1]), int(args[1][1])
|
|
232
|
+
v = self._val(args[2])
|
|
233
|
+
if v is None:
|
|
234
|
+
self._exec(op, args, idx)
|
|
235
|
+
else:
|
|
236
|
+
self._code(f'rt.AsrFrom({rd}, {rs}, {v})')
|
|
237
|
+
return False
|
|
238
|
+
rd = int(args[0][1])
|
|
239
|
+
v = self._val(args[1])
|
|
240
|
+
if v is None:
|
|
241
|
+
self._exec(op, args, idx)
|
|
242
|
+
else:
|
|
243
|
+
self._code(f'rt.Asr({rd}, {v})')
|
|
244
|
+
return False
|
|
245
|
+
if op in ('ADDI', 'LSL', 'LSR'):
|
|
246
|
+
rd, rs = int(args[0][1]), int(args[1][1])
|
|
247
|
+
v = self._val(args[2])
|
|
248
|
+
if v is None:
|
|
249
|
+
self._exec(op, args, idx)
|
|
250
|
+
return False
|
|
251
|
+
if op == 'ADDI':
|
|
252
|
+
self._code(f'rt.AddTo({rd}, {rs}, {v})')
|
|
253
|
+
else:
|
|
254
|
+
method = {'LSL': 'LslFrom', 'LSR': 'LsrFrom'}[op]
|
|
255
|
+
self._code(f'rt.{method}({rd}, {rs}, {v})')
|
|
256
|
+
return False
|
|
257
|
+
if op in ('XORI', 'ORI', 'ANDI'):
|
|
258
|
+
rd, rs = int(args[0][1]), int(args[1][1])
|
|
259
|
+
v = self._val(args[2])
|
|
260
|
+
if v is None:
|
|
261
|
+
self._exec(op, args, idx)
|
|
262
|
+
return False
|
|
263
|
+
go_op = {'XORI': '^', 'ORI': '|', 'ANDI': '&'}[op]
|
|
264
|
+
self._code(f'rt.SetReg({rd}, rt.Reg({rs}) {go_op} {v})')
|
|
265
|
+
return False
|
|
266
|
+
if op in ('INC', 'DEC'):
|
|
267
|
+
rd = int(args[0][1])
|
|
268
|
+
self._code(f'rt.{"Inc" if op == "INC" else "Dec"}({rd})')
|
|
269
|
+
return False
|
|
270
|
+
if op == 'MVN':
|
|
271
|
+
rd = int(args[0][1])
|
|
272
|
+
v = self._val(args[1])
|
|
273
|
+
if v is None:
|
|
274
|
+
self._exec(op, args, idx)
|
|
275
|
+
else:
|
|
276
|
+
self._code(f'rt.Mvn({rd}, {v})')
|
|
277
|
+
return False
|
|
278
|
+
if op == 'CMP':
|
|
279
|
+
a = self._val(args[0])
|
|
280
|
+
b = self._val(args[1])
|
|
281
|
+
if a is None or b is None:
|
|
282
|
+
self._exec(op, args, idx)
|
|
283
|
+
else:
|
|
284
|
+
self._code(f'rt.Cmp({a}, {b})')
|
|
285
|
+
return False
|
|
286
|
+
|
|
287
|
+
# ---- 栈 ----
|
|
288
|
+
if op == 'PUSH':
|
|
289
|
+
v = self._val(args[0])
|
|
290
|
+
if v is None:
|
|
291
|
+
self._exec(op, args, idx)
|
|
292
|
+
else:
|
|
293
|
+
self._fail(f'rt.Push({v})')
|
|
294
|
+
return False
|
|
295
|
+
if op == 'POP':
|
|
296
|
+
self._code('{')
|
|
297
|
+
self._code('\tv, e := rt.Pop()')
|
|
298
|
+
if self.block_mode:
|
|
299
|
+
self._code('\tif e != "" { rt.Abort(e); return -2 }')
|
|
300
|
+
else:
|
|
301
|
+
self._code('\tif e != "" { return rt.Abort(e) }')
|
|
302
|
+
self._code(f'\trt.SetReg({int(args[0][1])}, v)')
|
|
303
|
+
self._code('}')
|
|
304
|
+
return False
|
|
305
|
+
|
|
306
|
+
# ---- I/O / 系统调用 ----
|
|
307
|
+
if op == 'IN':
|
|
308
|
+
self._code(f'rt.In({int(args[0][1])})')
|
|
309
|
+
return False
|
|
310
|
+
if op == 'OUT':
|
|
311
|
+
kind, value, extra = self._out_lit(args[0])
|
|
312
|
+
self._fail(f'rt.Out({kind}, {value}, {extra})')
|
|
313
|
+
return False
|
|
314
|
+
if op == 'SYS':
|
|
315
|
+
if args[0][0] != 'imm':
|
|
316
|
+
self._exec(op, args, idx)
|
|
317
|
+
else:
|
|
318
|
+
self._fail(f'rt.Sys(uint64({_u64(args[0][1])}))')
|
|
319
|
+
return False
|
|
320
|
+
if op == 'HALT':
|
|
321
|
+
self._code('return -1' if self.block_mode else 'return true')
|
|
322
|
+
return True
|
|
323
|
+
|
|
324
|
+
# ---- 内存 ----
|
|
325
|
+
load_width = {'LOAD': (4, False), 'LW': (4, True), 'LD': (8, True),
|
|
326
|
+
'LB': (1, True), 'LH': (2, True), 'LDR': (4, False)}
|
|
327
|
+
if op in load_width:
|
|
328
|
+
width, signed = load_width[op]
|
|
329
|
+
addr = self._addr(args[1])
|
|
330
|
+
if addr is None:
|
|
331
|
+
self._exec(op, args, idx)
|
|
332
|
+
else:
|
|
333
|
+
self._fail(f'rt.Load({int(args[0][1])}, {addr}, {width}, '
|
|
334
|
+
f'{"true" if signed else "false"})')
|
|
335
|
+
return False
|
|
336
|
+
store_width = {'STORE': 4, 'SW': 4, 'STR': 4, 'SD': 8,
|
|
337
|
+
'SB': 1, 'SH': 2}
|
|
338
|
+
if op in store_width:
|
|
339
|
+
addr = self._addr(args[1])
|
|
340
|
+
if addr is None:
|
|
341
|
+
self._exec(op, args, idx)
|
|
342
|
+
else:
|
|
343
|
+
self._fail(f'rt.Store({int(args[0][1])}, {addr}, '
|
|
344
|
+
f'{store_width[op]})')
|
|
345
|
+
return False
|
|
346
|
+
|
|
347
|
+
# ---- 无条件跳转 ----
|
|
348
|
+
if op == 'JMP':
|
|
349
|
+
target = self._target(args[0])
|
|
350
|
+
if target is not None:
|
|
351
|
+
self._code(f'return {target}' if self.block_mode
|
|
352
|
+
else f'goto L{target}')
|
|
353
|
+
return True
|
|
354
|
+
v = self._val(args[0])
|
|
355
|
+
if v is not None:
|
|
356
|
+
if self.block_mode:
|
|
357
|
+
self._code(f'return int({v})')
|
|
358
|
+
else:
|
|
359
|
+
self._code(f'target = int({v})')
|
|
360
|
+
self._code('goto Ldispatch')
|
|
361
|
+
return True
|
|
362
|
+
self._exec(op, args, idx)
|
|
363
|
+
if self.block_mode:
|
|
364
|
+
self._code('return rt.PC()')
|
|
365
|
+
else:
|
|
366
|
+
self._code('target = rt.PC()')
|
|
367
|
+
self._code('goto Ldispatch')
|
|
368
|
+
return True
|
|
369
|
+
|
|
370
|
+
# ---- 条件跳转 (标志位) ----
|
|
371
|
+
if op in ('JZ', 'JE', 'JNZ', 'JL', 'JG'):
|
|
372
|
+
target = self._target(args[0])
|
|
373
|
+
if target is None:
|
|
374
|
+
self._exec(op, args, idx)
|
|
375
|
+
if self.block_mode:
|
|
376
|
+
self._code('return rt.PC()')
|
|
377
|
+
else:
|
|
378
|
+
self._code('target = rt.PC()')
|
|
379
|
+
self._code('goto Ldispatch')
|
|
380
|
+
return True
|
|
381
|
+
cond = {'JZ': 'rt.Z()', 'JE': 'rt.Z()', 'JNZ': '!rt.Z()',
|
|
382
|
+
'JL': 'rt.N() != rt.V()',
|
|
383
|
+
'JG': '!rt.Z() && rt.N() == rt.V()'}[op]
|
|
384
|
+
if self.block_mode:
|
|
385
|
+
self._code(f'if {cond} {{ return {target} }}')
|
|
386
|
+
else:
|
|
387
|
+
self._code(f'if {cond} {{ goto L{target} }}')
|
|
388
|
+
return False
|
|
389
|
+
|
|
390
|
+
# ---- ARM64 条件分支 ----
|
|
391
|
+
if op == 'B':
|
|
392
|
+
cond_arg = next((a for a in args if a[0] == 'cond'), None)
|
|
393
|
+
target_arg = next((a for a in args if a[0] != 'cond'), None)
|
|
394
|
+
target = self._target(target_arg) if target_arg else None
|
|
395
|
+
if cond_arg is None or target is None:
|
|
396
|
+
self._exec(op, args, idx)
|
|
397
|
+
if self.block_mode:
|
|
398
|
+
self._code('return rt.PC()')
|
|
399
|
+
else:
|
|
400
|
+
self._code('target = rt.PC()')
|
|
401
|
+
self._code('goto Ldispatch')
|
|
402
|
+
return True
|
|
403
|
+
code = self._cond_code(cond_arg[1])
|
|
404
|
+
if self.block_mode:
|
|
405
|
+
self._code(f'if rt.Cond({code}) {{ return {target} }}')
|
|
406
|
+
else:
|
|
407
|
+
self._code(f'if rt.Cond({code}) {{ goto L{target} }}')
|
|
408
|
+
return False
|
|
409
|
+
if op in ('CBZ', 'CBNZ'):
|
|
410
|
+
target = self._target(args[1])
|
|
411
|
+
if target is None:
|
|
412
|
+
self._exec(op, args, idx)
|
|
413
|
+
if self.block_mode:
|
|
414
|
+
self._code('return rt.PC()')
|
|
415
|
+
else:
|
|
416
|
+
self._code('target = rt.PC()')
|
|
417
|
+
self._code('goto Ldispatch')
|
|
418
|
+
return True
|
|
419
|
+
cmp = '==' if op == 'CBZ' else '!='
|
|
420
|
+
if self.block_mode:
|
|
421
|
+
self._code(f'if rt.Reg({int(args[0][1])}) {cmp} 0 '
|
|
422
|
+
f'{{ return {target} }}')
|
|
423
|
+
else:
|
|
424
|
+
self._code(f'if rt.Reg({int(args[0][1])}) {cmp} 0 '
|
|
425
|
+
f'{{ goto L{target} }}')
|
|
426
|
+
return False
|
|
427
|
+
if op in ('TBZ', 'TBNZ'):
|
|
428
|
+
target = self._target(args[2])
|
|
429
|
+
bit = self._val(args[1])
|
|
430
|
+
if target is None or bit is None:
|
|
431
|
+
self._exec(op, args, idx)
|
|
432
|
+
if self.block_mode:
|
|
433
|
+
self._code('return rt.PC()')
|
|
434
|
+
else:
|
|
435
|
+
self._code('target = rt.PC()')
|
|
436
|
+
self._code('goto Ldispatch')
|
|
437
|
+
return True
|
|
438
|
+
cmp = '==' if op == 'TBZ' else '!='
|
|
439
|
+
if self.block_mode:
|
|
440
|
+
self._code(
|
|
441
|
+
f'if rt.Reg({int(args[0][1])}) & (1 << ({bit} & 63)) '
|
|
442
|
+
f'{cmp} 0 {{ return {target} }}')
|
|
443
|
+
else:
|
|
444
|
+
self._code(
|
|
445
|
+
f'if rt.Reg({int(args[0][1])}) & (1 << ({bit} & 63)) '
|
|
446
|
+
f'{cmp} 0 {{ goto L{target} }}')
|
|
447
|
+
return False
|
|
448
|
+
|
|
449
|
+
# ---- RISC-V 条件分支 ----
|
|
450
|
+
if op in ('BEQ', 'BNE', 'BLT', 'BGE', 'BLTU', 'BGEU'):
|
|
451
|
+
target = self._target(args[2])
|
|
452
|
+
if target is None:
|
|
453
|
+
self._exec(op, args, idx)
|
|
454
|
+
if self.block_mode:
|
|
455
|
+
self._code('return rt.PC()')
|
|
456
|
+
else:
|
|
457
|
+
self._code('target = rt.PC()')
|
|
458
|
+
self._code('goto Ldispatch')
|
|
459
|
+
return True
|
|
460
|
+
rs1, rs2 = int(args[0][1]), int(args[1][1])
|
|
461
|
+
if op == 'BEQ':
|
|
462
|
+
cond = f'rt.Reg({rs1}) == rt.Reg({rs2})'
|
|
463
|
+
elif op == 'BNE':
|
|
464
|
+
cond = f'rt.Reg({rs1}) != rt.Reg({rs2})'
|
|
465
|
+
elif op == 'BLT':
|
|
466
|
+
cond = f'int64(rt.Reg({rs1})) < int64(rt.Reg({rs2}))'
|
|
467
|
+
elif op == 'BGE':
|
|
468
|
+
cond = f'int64(rt.Reg({rs1})) >= int64(rt.Reg({rs2}))'
|
|
469
|
+
elif op == 'BLTU':
|
|
470
|
+
cond = f'rt.Reg({rs1}) < rt.Reg({rs2})'
|
|
471
|
+
else:
|
|
472
|
+
cond = f'rt.Reg({rs1}) >= rt.Reg({rs2})'
|
|
473
|
+
if self.block_mode:
|
|
474
|
+
self._code(f'if {cond} {{ return {target} }}')
|
|
475
|
+
else:
|
|
476
|
+
self._code(f'if {cond} {{ goto L{target} }}')
|
|
477
|
+
return False
|
|
478
|
+
|
|
479
|
+
# ---- 调用/返回 ----
|
|
480
|
+
if op in ('CALL', 'BL'):
|
|
481
|
+
target = self._target(args[0])
|
|
482
|
+
if target is None:
|
|
483
|
+
self._exec(op, args, idx)
|
|
484
|
+
if self.block_mode:
|
|
485
|
+
self._code('return rt.PC()')
|
|
486
|
+
else:
|
|
487
|
+
self._code('target = rt.PC()')
|
|
488
|
+
self._code('goto Ldispatch')
|
|
489
|
+
return True
|
|
490
|
+
self._fail(f'rt.Push(uint64({idx + 1}))')
|
|
491
|
+
self._code(f'return {target}' if self.block_mode
|
|
492
|
+
else f'goto L{target}')
|
|
493
|
+
return True
|
|
494
|
+
if op == 'RET':
|
|
495
|
+
self._code('{')
|
|
496
|
+
self._code('\tv, e := rt.PopRet()')
|
|
497
|
+
if self.block_mode:
|
|
498
|
+
self._code('\tif e != "" { rt.Abort(e); return -2 }')
|
|
499
|
+
self._code('\treturn v')
|
|
500
|
+
else:
|
|
501
|
+
self._code('\tif e != "" { return rt.Abort(e) }')
|
|
502
|
+
self._code('\ttarget = v')
|
|
503
|
+
self._code('}')
|
|
504
|
+
if not self.block_mode:
|
|
505
|
+
self._code('goto Ldispatch')
|
|
506
|
+
return True
|
|
507
|
+
if op == 'JAL':
|
|
508
|
+
if args[0][0] == 'reg':
|
|
509
|
+
rd = int(args[0][1])
|
|
510
|
+
target_arg = args[1]
|
|
511
|
+
else:
|
|
512
|
+
rd = 31
|
|
513
|
+
target_arg = args[0]
|
|
514
|
+
target = self._target(target_arg)
|
|
515
|
+
if target is None:
|
|
516
|
+
self._exec(op, args, idx)
|
|
517
|
+
if self.block_mode:
|
|
518
|
+
self._code('return rt.PC()')
|
|
519
|
+
else:
|
|
520
|
+
self._code('target = rt.PC()')
|
|
521
|
+
self._code('goto Ldispatch')
|
|
522
|
+
return True
|
|
523
|
+
if rd != 31:
|
|
524
|
+
self._code(f'rt.SetReg({rd}, uint64({idx + 1}))')
|
|
525
|
+
self._code(f'return {target}' if self.block_mode
|
|
526
|
+
else f'goto L{target}')
|
|
527
|
+
return True
|
|
528
|
+
if op == 'JALR':
|
|
529
|
+
self._exec(op, args, idx)
|
|
530
|
+
if self.block_mode:
|
|
531
|
+
self._code('return rt.PC()')
|
|
532
|
+
else:
|
|
533
|
+
self._code('target = rt.PC()')
|
|
534
|
+
self._code('goto Ldispatch')
|
|
535
|
+
return True
|
|
536
|
+
if op == 'BR':
|
|
537
|
+
if self.block_mode:
|
|
538
|
+
self._code(f'return int(rt.Reg({int(args[0][1])}))')
|
|
539
|
+
else:
|
|
540
|
+
self._code(f'target = int(rt.Reg({int(args[0][1])}))')
|
|
541
|
+
self._code('goto Ldispatch')
|
|
542
|
+
return True
|
|
543
|
+
|
|
544
|
+
# ---- ARM64/RISC-V 扩展整数 ----
|
|
545
|
+
if op in ('ADDS', 'SUBS', 'ADDC', 'SUBC'):
|
|
546
|
+
rd, rn = int(args[0][1]), int(args[1][1])
|
|
547
|
+
v = self._val(args[2])
|
|
548
|
+
if v is None:
|
|
549
|
+
self._exec(op, args, idx)
|
|
550
|
+
else:
|
|
551
|
+
method = {'ADDS': 'AddS', 'SUBS': 'SubS',
|
|
552
|
+
'ADDC': 'AddC', 'SUBC': 'SubC'}[op]
|
|
553
|
+
self._code(f'rt.{method}({rd}, {rn}, {v})')
|
|
554
|
+
return False
|
|
555
|
+
if op in ('ROR', 'EOR', 'BIC', 'ORN'):
|
|
556
|
+
rd, rn = int(args[0][1]), int(args[1][1])
|
|
557
|
+
v = self._val(args[2])
|
|
558
|
+
if v is None:
|
|
559
|
+
self._exec(op, args, idx)
|
|
560
|
+
else:
|
|
561
|
+
method = {'ROR': 'Ror', 'EOR': 'Eor',
|
|
562
|
+
'BIC': 'Bic', 'ORN': 'Orn'}[op]
|
|
563
|
+
self._code(f'rt.{method}({rd}, {rn}, {v})')
|
|
564
|
+
return False
|
|
565
|
+
if op in ('LDP', 'STP'):
|
|
566
|
+
addr = self._addr(args[2])
|
|
567
|
+
if addr is None:
|
|
568
|
+
self._exec(op, args, idx)
|
|
569
|
+
else:
|
|
570
|
+
if op == 'LDP':
|
|
571
|
+
self._fail(f'rt.Ldp({int(args[0][1])}, '
|
|
572
|
+
f'{int(args[1][1])}, {addr})')
|
|
573
|
+
else:
|
|
574
|
+
self._fail(f'rt.Stp({int(args[0][1])}, '
|
|
575
|
+
f'{int(args[1][1])}, {addr})')
|
|
576
|
+
return False
|
|
577
|
+
if op in ('CSEL', 'CSINC', 'CSINV', 'CSNEG'):
|
|
578
|
+
rd, rn = int(args[0][1]), int(args[1][1])
|
|
579
|
+
v = self._val(args[2])
|
|
580
|
+
cond_arg = args[3] if len(args) > 3 else None
|
|
581
|
+
if v is None or cond_arg is None or cond_arg[0] != 'cond':
|
|
582
|
+
self._exec(op, args, idx)
|
|
583
|
+
else:
|
|
584
|
+
cond = self._cond_code(cond_arg[1])
|
|
585
|
+
self._code(f'rt.CondSelect("{op}", {rd}, {rn}, {v}, {cond})')
|
|
586
|
+
return False
|
|
587
|
+
if op in ('SXTB', 'SXTH', 'SXTW', 'UXTB', 'UXTH'):
|
|
588
|
+
rd = int(args[0][1])
|
|
589
|
+
v = self._val(args[1])
|
|
590
|
+
if v is None:
|
|
591
|
+
self._exec(op, args, idx)
|
|
592
|
+
else:
|
|
593
|
+
width = {'SXTB': 8, 'SXTH': 16, 'SXTW': 32,
|
|
594
|
+
'UXTB': 8, 'UXTH': 16}[op]
|
|
595
|
+
method = 'SignExtend' if op.startswith('SX') else 'ZeroExtend'
|
|
596
|
+
self._code(f'rt.{method}({rd}, {v}, {width})')
|
|
597
|
+
return False
|
|
598
|
+
if op in ('CLZ', 'CLS', 'RBIT', 'REV'):
|
|
599
|
+
rd = int(args[0][1])
|
|
600
|
+
v = self._val(args[1])
|
|
601
|
+
if v is None:
|
|
602
|
+
self._exec(op, args, idx)
|
|
603
|
+
else:
|
|
604
|
+
method = {'CLZ': 'Clz', 'CLS': 'Cls',
|
|
605
|
+
'RBIT': 'Rbit', 'REV': 'Rev'}[op]
|
|
606
|
+
self._code(f'rt.{method}({rd}, {v})')
|
|
607
|
+
return False
|
|
608
|
+
if op in ('SLTI', 'SLTIU'):
|
|
609
|
+
rd, rs = int(args[0][1]), int(args[1][1])
|
|
610
|
+
v = self._val(args[2])
|
|
611
|
+
if v is None:
|
|
612
|
+
self._exec(op, args, idx)
|
|
613
|
+
else:
|
|
614
|
+
self._code(f'rt.SetLessImm({rd}, {rs}, {v}, '
|
|
615
|
+
f'{"true" if op == "SLTI" else "false"})')
|
|
616
|
+
return False
|
|
617
|
+
if op in ('SLLI', 'SRLI', 'SRAI'):
|
|
618
|
+
rd, rs = int(args[0][1]), int(args[1][1])
|
|
619
|
+
v = self._val(args[2])
|
|
620
|
+
if v is None:
|
|
621
|
+
self._exec(op, args, idx)
|
|
622
|
+
else:
|
|
623
|
+
method = {'SLLI': 'LslFrom', 'SRLI': 'LsrFrom',
|
|
624
|
+
'SRAI': 'AsrFrom'}[op]
|
|
625
|
+
self._code(f'rt.{method}({rd}, {rs}, {v})')
|
|
626
|
+
return False
|
|
627
|
+
if op == 'LUI':
|
|
628
|
+
rd = int(args[0][1])
|
|
629
|
+
v = self._val(args[1])
|
|
630
|
+
if v is None:
|
|
631
|
+
self._exec(op, args, idx)
|
|
632
|
+
else:
|
|
633
|
+
self._code(f'rt.Lui({rd}, {v})')
|
|
634
|
+
return False
|
|
635
|
+
if op == 'AUIPC':
|
|
636
|
+
rd = int(args[0][1])
|
|
637
|
+
v = self._val(args[1])
|
|
638
|
+
if v is None:
|
|
639
|
+
self._exec(op, args, idx)
|
|
640
|
+
else:
|
|
641
|
+
self._code(f'rt.Auipc({rd}, {v}, {idx})')
|
|
642
|
+
return False
|
|
643
|
+
|
|
644
|
+
# ---- 浮点/向量 ----
|
|
645
|
+
if op in ('FADD', 'FSUB', 'FMUL', 'FDIV'):
|
|
646
|
+
rd, rn, rm = int(args[0][1]), int(args[1][1]), int(args[2][1])
|
|
647
|
+
method = {'FADD': 'FAdd', 'FSUB': 'FSub',
|
|
648
|
+
'FMUL': 'FMul', 'FDIV': 'FDiv'}[op]
|
|
649
|
+
if op == 'FDIV':
|
|
650
|
+
self._fail(f'rt.FDiv({rd}, {rn}, {rm})')
|
|
651
|
+
else:
|
|
652
|
+
self._code(f'rt.{method}({rd}, {rn}, {rm})')
|
|
653
|
+
return False
|
|
654
|
+
if op == 'FCMP':
|
|
655
|
+
self._code(f'rt.FCmp({int(args[0][1])}, {int(args[1][1])})')
|
|
656
|
+
return False
|
|
657
|
+
if op == 'FCVT':
|
|
658
|
+
rd, rs = int(args[0][1]), int(args[1][1])
|
|
659
|
+
if args[1][0] in ('vec', 'veclane'):
|
|
660
|
+
lane = int(args[1][2]) if args[1][0] == 'veclane' else 0
|
|
661
|
+
self._code(f'rt.FCvtToInt({rd}, {rs}, {lane})')
|
|
662
|
+
elif args[1][0] == 'reg':
|
|
663
|
+
self._code(f'rt.FCvtToFloat({rd}, {rs})')
|
|
664
|
+
else:
|
|
665
|
+
self._exec(op, args, idx)
|
|
666
|
+
return False
|
|
667
|
+
if op in ('FABS', 'FNEG'):
|
|
668
|
+
rd, rs = int(args[0][1]), int(args[1][1])
|
|
669
|
+
method = 'FAbs' if op == 'FABS' else 'FNeg'
|
|
670
|
+
self._code(f'rt.{method}({rd}, {rs})')
|
|
671
|
+
return False
|
|
672
|
+
if op in ('LDRS', 'STRS'):
|
|
673
|
+
addr = self._addr(args[1])
|
|
674
|
+
if addr is None:
|
|
675
|
+
self._exec(op, args, idx)
|
|
676
|
+
elif op == 'LDRS':
|
|
677
|
+
self._fail(f'rt.LoadF32({int(args[0][1])}, {addr})')
|
|
678
|
+
else:
|
|
679
|
+
self._fail(f'rt.StoreF32({int(args[0][1])}, {addr})')
|
|
680
|
+
return False
|
|
681
|
+
if op in ('VADD', 'VSUB', 'VMUL', 'VDIV'):
|
|
682
|
+
self._fail(f'rt.VOp("{op}", {int(args[0][1])}, '
|
|
683
|
+
f'{int(args[1][1])}, {int(args[2][1])})')
|
|
684
|
+
return False
|
|
685
|
+
if op in ('VLD1', 'VST1'):
|
|
686
|
+
addr = self._addr(args[1])
|
|
687
|
+
if addr is None:
|
|
688
|
+
self._exec(op, args, idx)
|
|
689
|
+
elif op == 'VLD1':
|
|
690
|
+
self._fail(f'rt.VLoad1({int(args[0][1])}, {addr})')
|
|
691
|
+
else:
|
|
692
|
+
self._fail(f'rt.VStore1({int(args[0][1])}, {addr})')
|
|
693
|
+
return False
|
|
694
|
+
|
|
695
|
+
# ---- 无操作 ----
|
|
696
|
+
if op in ('NOP', 'WFE', 'WFI', 'SEV'):
|
|
697
|
+
# 每条指令前面的 Tick() 已经是一条语句; 无需额外 goto。
|
|
698
|
+
return False
|
|
699
|
+
|
|
700
|
+
# ---- 其余: 受控回退到 VM 单指令语义 ----
|
|
701
|
+
self._exec(op, args, idx)
|
|
702
|
+
return False
|
|
703
|
+
|
|
704
|
+
# ---------------- 控制流目标分析 ----------------
|
|
705
|
+
|
|
706
|
+
def _analyze_targets(self) -> Tuple[Set[int], bool]:
|
|
707
|
+
"""返回 (需要生成标签的下标集合, 是否需要 Ldispatch)。
|
|
708
|
+
|
|
709
|
+
只为真正的跳转目标/返回地址生成标签, 顺序执行不再逐条 ``goto``。
|
|
710
|
+
这样大程序 (例如 basic.cin 的数万条指令) 不会生成数万个标签和
|
|
711
|
+
goto, Go 编译时间和源码体积都会显著下降。
|
|
712
|
+
"""
|
|
713
|
+
n = len(self.instructions)
|
|
714
|
+
needed: Set[int] = set()
|
|
715
|
+
dynamic = False
|
|
716
|
+
has_ret = any(op == 'RET' for op, _ in self.instructions)
|
|
717
|
+
|
|
718
|
+
def add(target: Optional[int]) -> None:
|
|
719
|
+
if target is not None and 0 <= target < n:
|
|
720
|
+
needed.add(target)
|
|
721
|
+
|
|
722
|
+
if self.entry_pc != 0:
|
|
723
|
+
add(self.entry_pc)
|
|
724
|
+
|
|
725
|
+
for idx, (op, args) in enumerate(self.instructions):
|
|
726
|
+
if op in ('CALL', 'BL', 'JAL'):
|
|
727
|
+
# 返回地址只在存在 RET 时才有意义; 否则标签会变成未使用。
|
|
728
|
+
if has_ret and idx + 1 < n:
|
|
729
|
+
needed.add(idx + 1)
|
|
730
|
+
if op == 'JAL':
|
|
731
|
+
if args and args[0][0] == 'reg':
|
|
732
|
+
targ = args[1] if len(args) > 1 else None
|
|
733
|
+
else:
|
|
734
|
+
targ = args[0] if args else None
|
|
735
|
+
else:
|
|
736
|
+
targ = args[0] if args else None
|
|
737
|
+
target = self._target(targ) if targ else None
|
|
738
|
+
if target is None:
|
|
739
|
+
dynamic = True
|
|
740
|
+
else:
|
|
741
|
+
add(target)
|
|
742
|
+
continue
|
|
743
|
+
if op in ('JMP', 'JZ', 'JE', 'JNZ', 'JL', 'JG'):
|
|
744
|
+
targ = args[0] if args else None
|
|
745
|
+
target = self._target(targ) if targ else None
|
|
746
|
+
if target is None:
|
|
747
|
+
dynamic = True
|
|
748
|
+
else:
|
|
749
|
+
add(target)
|
|
750
|
+
continue
|
|
751
|
+
if op == 'B':
|
|
752
|
+
target_arg = next((a for a in args if a[0] != 'cond'), None)
|
|
753
|
+
target = self._target(target_arg) if target_arg else None
|
|
754
|
+
if target is None:
|
|
755
|
+
dynamic = True
|
|
756
|
+
else:
|
|
757
|
+
add(target)
|
|
758
|
+
continue
|
|
759
|
+
if op in ('CBZ', 'CBNZ'):
|
|
760
|
+
targ = args[1] if len(args) > 1 else None
|
|
761
|
+
target = self._target(targ) if targ else None
|
|
762
|
+
if target is None:
|
|
763
|
+
dynamic = True
|
|
764
|
+
else:
|
|
765
|
+
add(target)
|
|
766
|
+
continue
|
|
767
|
+
if op in ('TBZ', 'TBNZ'):
|
|
768
|
+
targ = args[2] if len(args) > 2 else None
|
|
769
|
+
target = self._target(targ) if targ else None
|
|
770
|
+
if target is None:
|
|
771
|
+
dynamic = True
|
|
772
|
+
else:
|
|
773
|
+
add(target)
|
|
774
|
+
continue
|
|
775
|
+
if op in ('BEQ', 'BNE', 'BLT', 'BGE', 'BLTU', 'BGEU'):
|
|
776
|
+
targ = args[2] if len(args) > 2 else None
|
|
777
|
+
target = self._target(targ) if targ else None
|
|
778
|
+
if target is None:
|
|
779
|
+
dynamic = True
|
|
780
|
+
else:
|
|
781
|
+
add(target)
|
|
782
|
+
continue
|
|
783
|
+
if op in ('JALR', 'BR'):
|
|
784
|
+
dynamic = True
|
|
785
|
+
|
|
786
|
+
if dynamic:
|
|
787
|
+
needed.update(range(n))
|
|
788
|
+
return needed, (has_ret or dynamic)
|
|
789
|
+
|
|
790
|
+
# ---------------- 函数/程序 ----------------
|
|
791
|
+
|
|
792
|
+
def _emit_program_header(self) -> None:
|
|
793
|
+
self._emit(f'// Code generated by codecin native backend for '
|
|
794
|
+
f'{self.program_name}; DO NOT EDIT.')
|
|
795
|
+
self._emit('package main')
|
|
796
|
+
self._emit()
|
|
797
|
+
self._emit('import (')
|
|
798
|
+
self._emit('\t"io"')
|
|
799
|
+
self._emit('\t"os"')
|
|
800
|
+
self._emit()
|
|
801
|
+
self._emit('\t"codecin-native/engine"')
|
|
802
|
+
self._emit(')')
|
|
803
|
+
self._emit()
|
|
804
|
+
self._emit('var nativeSegments = []engine.MemSeg{')
|
|
805
|
+
for addr, data in self.segments:
|
|
806
|
+
self._emit(f'\t{{Addr: {int(addr)}, Data: {_go_bytes(data, chr(9))}}},')
|
|
807
|
+
self._emit('}')
|
|
808
|
+
self._emit()
|
|
809
|
+
self._emit('func main() {')
|
|
810
|
+
self._emit('\tengine.ConsoleInit()')
|
|
811
|
+
self._emit('\tengine.SetProgramArgs(os.Args[1:])')
|
|
812
|
+
self._emit('\tvar in []byte')
|
|
813
|
+
self._emit('\tif fi, err := os.Stdin.Stat(); err == nil && '
|
|
814
|
+
'fi.Mode()&os.ModeCharDevice == 0 {')
|
|
815
|
+
self._emit('\t\tif data, err := io.ReadAll(os.Stdin); err == nil {')
|
|
816
|
+
self._emit('\t\t\tin = data')
|
|
817
|
+
self._emit('\t\t}')
|
|
818
|
+
self._emit('\t}')
|
|
819
|
+
self._emit(f'\trt := engine.NewNativeRuntime({self.mem_size}, '
|
|
820
|
+
f'{self.sp}, {self.heap_base}, nativeSegments, '
|
|
821
|
+
f'{self.max_steps})')
|
|
822
|
+
self._emit('\trt.SetInput(in)')
|
|
823
|
+
self._emit('\trt.SetStreamOutput(true) // 真实终端: 边执行边输出')
|
|
824
|
+
self._emit('\tok := run(rt)')
|
|
825
|
+
self._emit('\tos.Exit(rt.Finish(ok))')
|
|
826
|
+
self._emit('}')
|
|
827
|
+
self._emit()
|
|
828
|
+
|
|
829
|
+
def _block_starts(self) -> List[int]:
|
|
830
|
+
"""基本块入口: 跳转目标、CALL/JAL 返回点、控制指令的下一条。"""
|
|
831
|
+
n = len(self.instructions)
|
|
832
|
+
starts: Set[int] = set()
|
|
833
|
+
if 0 <= self.entry_pc < n:
|
|
834
|
+
starts.add(self.entry_pc)
|
|
835
|
+
dynamic = False
|
|
836
|
+
|
|
837
|
+
def add(target: Optional[int]) -> None:
|
|
838
|
+
if target is not None and 0 <= target < n:
|
|
839
|
+
starts.add(target)
|
|
840
|
+
|
|
841
|
+
for idx, (op, args) in enumerate(self.instructions):
|
|
842
|
+
target: Optional[int] = None
|
|
843
|
+
is_control = True
|
|
844
|
+
if op in ('JMP', 'JZ', 'JE', 'JNZ', 'JL', 'JG'):
|
|
845
|
+
target = self._target(args[0]) if args else None
|
|
846
|
+
elif op == 'B':
|
|
847
|
+
target_arg = next((a for a in args if a[0] != 'cond'), None)
|
|
848
|
+
target = self._target(target_arg) if target_arg else None
|
|
849
|
+
elif op in ('CBZ', 'CBNZ'):
|
|
850
|
+
target = self._target(args[1]) if len(args) > 1 else None
|
|
851
|
+
elif op in ('TBZ', 'TBNZ', 'BEQ', 'BNE', 'BLT', 'BGE',
|
|
852
|
+
'BLTU', 'BGEU'):
|
|
853
|
+
target = self._target(args[2]) if len(args) > 2 else None
|
|
854
|
+
elif op in ('CALL', 'BL'):
|
|
855
|
+
target = self._target(args[0]) if args else None
|
|
856
|
+
elif op == 'JAL':
|
|
857
|
+
if args and args[0][0] == 'reg':
|
|
858
|
+
targ = args[1] if len(args) > 1 else None
|
|
859
|
+
else:
|
|
860
|
+
targ = args[0] if args else None
|
|
861
|
+
target = self._target(targ) if targ else None
|
|
862
|
+
elif op in ('RET', 'HALT'):
|
|
863
|
+
target = None
|
|
864
|
+
elif op in ('JALR', 'BR'):
|
|
865
|
+
target = None
|
|
866
|
+
dynamic = True
|
|
867
|
+
else:
|
|
868
|
+
is_control = False
|
|
869
|
+
if not is_control:
|
|
870
|
+
continue
|
|
871
|
+
if idx + 1 < n:
|
|
872
|
+
starts.add(idx + 1)
|
|
873
|
+
if target is None:
|
|
874
|
+
dynamic = True
|
|
875
|
+
else:
|
|
876
|
+
add(target)
|
|
877
|
+
|
|
878
|
+
if dynamic:
|
|
879
|
+
starts.update(v for v in self.labels.values() if 0 <= v < n)
|
|
880
|
+
if not starts:
|
|
881
|
+
starts.add(0)
|
|
882
|
+
return sorted(starts)
|
|
883
|
+
|
|
884
|
+
def _generate_blocks(self) -> str:
|
|
885
|
+
self._emit_program_header()
|
|
886
|
+
n = len(self.instructions)
|
|
887
|
+
starts = self._block_starts()
|
|
888
|
+
blocks = [(s, starts[i + 1] if i + 1 < len(starts) else n)
|
|
889
|
+
for i, s in enumerate(starts)]
|
|
890
|
+
|
|
891
|
+
self._emit('func run(rt *engine.NativeRuntime) bool {')
|
|
892
|
+
self._emit(f'\tpc := {self.entry_pc}')
|
|
893
|
+
self._emit('\tfor {')
|
|
894
|
+
self._emit('\t\tswitch pc {')
|
|
895
|
+
for i, (start, _end) in enumerate(blocks):
|
|
896
|
+
self._emit(f'\t\tcase {start}:')
|
|
897
|
+
self._emit(f'\t\t\tpc = block{i}(rt)')
|
|
898
|
+
self._emit(f'\t\tcase {n}:')
|
|
899
|
+
self._emit('\t\t\treturn true')
|
|
900
|
+
self._emit('\t\tdefault:')
|
|
901
|
+
self._emit('\t\t\treturn rt.Abort("invalid control-flow target")')
|
|
902
|
+
self._emit('\t\t}')
|
|
903
|
+
self._emit('\t\tif pc == -1 { return true }')
|
|
904
|
+
self._emit('\t\tif pc == -2 { return false }')
|
|
905
|
+
self._emit('\t}')
|
|
906
|
+
self._emit('}')
|
|
907
|
+
self._emit()
|
|
908
|
+
|
|
909
|
+
for i, (start, end) in enumerate(blocks):
|
|
910
|
+
self._emit(f'func block{i}(rt *engine.NativeRuntime) int {{')
|
|
911
|
+
for idx in range(start, end):
|
|
912
|
+
op, args = self.instructions[idx]
|
|
913
|
+
self._emit('\tif e := rt.Tick(); e != "" {')
|
|
914
|
+
self._emit('\t\trt.Abort(e)')
|
|
915
|
+
self._emit('\t\treturn -2')
|
|
916
|
+
self._emit('\t}')
|
|
917
|
+
self._emit_ins(op, args, idx)
|
|
918
|
+
self._emit()
|
|
919
|
+
self._emit(f'\treturn {end}')
|
|
920
|
+
self._emit('}')
|
|
921
|
+
self._emit()
|
|
922
|
+
return '\n'.join(self.lines) + '\n'
|
|
923
|
+
|
|
924
|
+
def generate(self) -> str:
|
|
925
|
+
if not self.instructions:
|
|
926
|
+
self.instructions = [('HALT', [])]
|
|
927
|
+
self.entry_pc = max(0, min(self.entry_pc, len(self.instructions) - 1))
|
|
928
|
+
if self.block_mode:
|
|
929
|
+
return self._generate_blocks()
|
|
930
|
+
self._emit_program_header()
|
|
931
|
+
self._emit('func run(rt *engine.NativeRuntime) bool {')
|
|
932
|
+
self._emit('\tvar target int')
|
|
933
|
+
self._emit('\t_ = target')
|
|
934
|
+
needed, dispatch = self._analyze_targets()
|
|
935
|
+
if self.entry_pc != 0:
|
|
936
|
+
self._emit(f'\tgoto L{self.entry_pc}')
|
|
937
|
+
self._emit()
|
|
938
|
+
for idx, (op, args) in enumerate(self.instructions):
|
|
939
|
+
if idx in needed:
|
|
940
|
+
self._emit(f'L{idx}:')
|
|
941
|
+
self._emit('\tif e := rt.Tick(); e != "" {')
|
|
942
|
+
self._emit('\t\treturn rt.Abort(e)')
|
|
943
|
+
self._emit('\t}')
|
|
944
|
+
self._emit_ins(op, args, idx)
|
|
945
|
+
self._emit()
|
|
946
|
+
if dispatch:
|
|
947
|
+
self._emit('Ldispatch:')
|
|
948
|
+
self._emit('\tswitch target {')
|
|
949
|
+
for idx in sorted(needed):
|
|
950
|
+
if idx >= len(self.instructions):
|
|
951
|
+
continue
|
|
952
|
+
self._emit(f'\tcase {idx}:')
|
|
953
|
+
self._emit(f'\t\tgoto L{idx}')
|
|
954
|
+
self._emit(f'\tcase {len(self.instructions)}:')
|
|
955
|
+
self._emit('\t\treturn true')
|
|
956
|
+
self._emit('\tdefault:')
|
|
957
|
+
self._emit('\t\treturn rt.Abort("invalid control-flow target")')
|
|
958
|
+
self._emit('\t}')
|
|
959
|
+
self._emit('\treturn true')
|
|
960
|
+
self._emit('}')
|
|
961
|
+
return '\n'.join(self.lines) + '\n'
|
|
962
|
+
|
|
963
|
+
|
|
964
|
+
def generate_go_source(instructions: Sequence[Instruction],
|
|
965
|
+
labels: Dict[str, int],
|
|
966
|
+
segments: Segments,
|
|
967
|
+
entry_pc: int = 0,
|
|
968
|
+
mem_size: int = 1 << 30,
|
|
969
|
+
sp: Optional[int] = None,
|
|
970
|
+
heap_base: Optional[int] = None,
|
|
971
|
+
max_steps: int = 0,
|
|
972
|
+
program_name: str = 'program',
|
|
973
|
+
block_mode: Optional[bool] = None) -> str:
|
|
974
|
+
"""生成 native AOT 的 Go 源码。
|
|
975
|
+
|
|
976
|
+
``block_mode=None`` 时按指令数自动选择: 超过 800 条使用基本块拆分,
|
|
977
|
+
避免单个 Go 函数过大导致 `go build` 极慢。
|
|
978
|
+
"""
|
|
979
|
+
if sp is None:
|
|
980
|
+
sp = int(mem_size) - STACK_SLOT
|
|
981
|
+
if heap_base is None:
|
|
982
|
+
heap_base = int(mem_size) // 2
|
|
983
|
+
if block_mode is None:
|
|
984
|
+
block_mode = len(instructions) > 800
|
|
985
|
+
return _Generator(instructions, labels, segments, entry_pc, mem_size,
|
|
986
|
+
sp, heap_base, max_steps, program_name,
|
|
987
|
+
block_mode=block_mode).generate()
|