A 4 cell adder slice: the carry borrows the scratch cell

Asked why the slice still needs 5 cells.  It does not: the scratch cell was
doing nothing the carry could not do, so the 4 cell version is

    p1..p4 = A, B, carry (in -> out), S

and the table says S = A^B^Ci, carry = AB|AC|BC, A and B consumed.  %synth
finds cost 27 in 5 blocks for it -- the same tape length as the 5 cell version
(cell count is not part of the cost metric, only the instructions are) but one
cell cheaper, 73 characters for a single slice.

All eight input combinations verified through the built in machine.

Diagnosis of the chained hang, from dumping the cells after one slice plus the
ror rotation:

    A=1 B=0  ->  cells: 4=80        (only the rotated sum bit survives)
    A=1 B=1  ->  cells: 1=1         (only the carry)

so a slice leaves A and B fully clear, and the carry is a clean 0/1.  The dirty
one is S: after the rotation its bit 7 is set, and set_0 in the next slice does
not remove it -- the dump after two slices shows 4=81 and, worse, the tape then
runs off the end instead of reaching 'output S'.

So the fix is not in the slice but in the driver: it must not rotate the sum
into a cell that the next slice clears, or must clear the whole cell (set_cell,
not set_0 over the modelled bits).  That is the next step, together with
re-checking whether set_0 is the right primitive here at all.
This commit is contained in:
dsh committed 2026-11-06 21:31:04 +08:00
1 parent 18bf78273e
commit 13b831ec8b
3 files changed
+55

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
# params 4 mode 0 metric 1
2 9 0
0 6 0
1 9 0
3 4 1
0 12 0
+19
View File
@@ -0,0 +1,19 @@
%include "asm/lib.r8asm"
; 4 个 cell 的忽略进位加法切片:连 tmp 都不要了,进位就借用 tmp 的位置。
;
; p1..p4 = A, B, 进位(进->出), S
;
; 目标:S = A^B^Ci,进位 = AB|AC|BC,A、B 结束为 0。
; 每个输入组合后的值只落在「进位」和 S 这两位,所以表里只出现 0/4/8/12。
%synth bit_add_nc4_synth
params 4
stat 0 8 8 4 8 4 4 12 0 8 8 4 8 4 4 12
metric flat
%endsynth
%macro bit_add_nc4 4
.tp %4
set_0
bit_add_nc4_synth %1 %2 %3 %4
%endmacro
+30
View File
@@ -94,6 +94,36 @@ int main(int argc, char **argv) {
std::cout << "\n";
return 0;
}
// params == -2: same as -1 but dumps every non zero cell afterwards
if (params == -2) {
r8asm a;
if (!a.import_file(file, 8)) {
std::cerr << "could not assemble " << file << "\n";
return 1;
}
machine m;
for (int i = 3; i < argc; i++) {
const char *eq = std::strchr(argv[i], '=');
if (eq == nullptr) {
continue;
}
const int at = std::atoi(std::string(argv[i], size_t(eq - argv[i])).c_str());
m.cells[size_t(at)] = uint8_t(std::atoi(eq + 1) & 0xff);
}
m.run(a.export_rot8());
std::cout << "out";
for (uint8_t v : m.out) {
std::cout << " " << int(v);
}
std::cout << "\ncells";
for (size_t i = 0; i < m.cells.size(); i++) {
if (m.cells[i] != 0) {
std::cout << " " << i << "=" << std::hex << int(m.cells[i]) << std::dec;
}
}
std::cout << "\n";
return 0;
}
// params == -1: the rest of argv is addr=value; set those cells, run, dump OUT
if (params == -1) {
r8asm a;