wuica-cli 0.1.9 → 0.1.12
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.
- package/README.md +140 -40
- package/dist/data/arch/ADL-P.bin.br +0 -0
- package/dist/data/arch/ICX.bin.br +0 -0
- package/dist/data/arch/ZEN3.bin.br +0 -0
- package/dist/data/uarch.json.br +0 -0
- package/dist/manifest.json +19 -19
- package/dist/wuica_wasm.wasm.br +0 -0
- package/index.d.ts +175 -15
- package/lib/cli.js +205 -44
- package/lib/core.js +9 -1
- package/lib/details.js +4 -23
- package/lib/examples.js +1 -0
- package/lib/files.js +2 -1
- package/lib/index.js +120 -21
- package/lib/mcp.js +108 -85
- package/lib/objfile.js +51 -11
- package/lib/thread-worker.js +9 -6
- package/lib/threads.js +8 -2
- package/lib/wasm.js +12 -6
- package/lib/web/ab-diff.js +217 -0
- package/lib/web/accum.js +10 -2
- package/lib/web/asm-regions.js +27 -20
- package/lib/web/asm-tokens.js +357 -0
- package/lib/web/assembler.js +36 -6
- package/lib/web/block-diff.js +165 -0
- package/lib/web/bound-core.js +211 -0
- package/lib/web/branch-label.js +155 -0
- package/lib/web/caveats.js +107 -3
- package/lib/web/details.js +91 -0
- package/lib/web/examples.js +5 -1
- package/lib/web/loop-find.js +398 -35
- package/lib/web/markdown.js +437 -0
- package/lib/web/whatif-core.js +339 -0
- package/package.json +7 -2
- package/lib/insights.js +0 -100
- package/lib/whatif.js +0 -136
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
// A–B comparison: compares two analysis responses (docs/WASM-API.md): throughput, bottlenecks, limits, and an
|
|
2
|
+
// instruction-by-instruction alignment of the two uop tables with the change of every shared column.
|
|
3
|
+
// Pure: no DOM, runs under Node (tests-js/web_ab_diff.mjs).
|
|
4
|
+
|
|
5
|
+
import { columnKind } from './bound-core.js';
|
|
6
|
+
|
|
7
|
+
export const EPS = 0.005; // values are shown with two decimals: smaller differences are "the same"
|
|
8
|
+
// A change of one instruction's uops that is under this in every column (uops per iteration), with the same notes, is
|
|
9
|
+
// "minor": uiCA's port assignment moves a few hundredths of a uop between ports when the code around an instruction
|
|
10
|
+
// changes (±0.03 seen). The Markdown and text forms of A–B leave minor changes out; the page's Δ table (which frames
|
|
11
|
+
// every cell that differs at its two decimals) and the JSON keep them.
|
|
12
|
+
export const MINOR = 0.05;
|
|
13
|
+
|
|
14
|
+
// Prefixes that come before the mnemonic in a disassembly ("lock add", "rep movsb", "notrack jmp").
|
|
15
|
+
const PREFIXES = new Set(['lock', 'rep', 'repe', 'repz', 'repne', 'repnz', 'bnd', 'notrack', 'xacquire', 'xrelease',
|
|
16
|
+
'data16', 'data32', 'addr32', 'cs', 'ds', 'es', 'ss', 'fs', 'gs', 'rex', 'rex.w', '{vex}', '{vex3}', '{evex}']);
|
|
17
|
+
// Direct branches: their operand is an address that changes whenever the code before the target changes size.
|
|
18
|
+
const BRANCH = /^(?:j[a-z]{1,4}|loop[a-z]{0,2}|jrcxz|jecxz|call|xbegin)$/;
|
|
19
|
+
const TARGET = /^(?:0x[0-9a-f]+|[0-9a-f]+|[0-9]+|0x[0-9a-f]+ <.*>|[0-9a-f]+ <.*>)$/;
|
|
20
|
+
|
|
21
|
+
// The text of an instruction for matching, and its mnemonic. Direct branch targets are replaced by "→" so that
|
|
22
|
+
// "jnz 0xfffffffffffffff5" and "jnz 0xfffffffffffffff2" match.
|
|
23
|
+
export function normalizeInstr(label) {
|
|
24
|
+
const t = String(label ?? '').trim().toLowerCase().replace(/\s+/g, ' ').replace(/ ?, ?/g, ', ');
|
|
25
|
+
const words = t.split(' ');
|
|
26
|
+
let i = 0;
|
|
27
|
+
while (i < words.length - 1 && PREFIXES.has(words[i])) i++;
|
|
28
|
+
const mnemonic = words[i] ?? '';
|
|
29
|
+
const operands = words.slice(i + 1).join(' ');
|
|
30
|
+
let key = t;
|
|
31
|
+
if (BRANCH.test(mnemonic) && TARGET.test(operands)) key = [...words.slice(0, i + 1), '→'].join(' ');
|
|
32
|
+
return { key, mnemonic };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// The instructions of a response, each with the extra uops the renamer inserts before it (regMerge, stackSync)
|
|
36
|
+
// added to its values: they are caused by it.
|
|
37
|
+
export function instructionUnits(response) {
|
|
38
|
+
const rows = Array.isArray(response?.rows) ? response.rows : [];
|
|
39
|
+
const n = Array.isArray(response?.columns) ? response.columns.length : 0;
|
|
40
|
+
const units = [];
|
|
41
|
+
let pending = [];
|
|
42
|
+
const unit = (row, extras) => {
|
|
43
|
+
const values = new Array(n).fill(0);
|
|
44
|
+
for (const r of [...extras, row]) for (let i = 0; i < n; i++) values[i] += Number(r.values?.[i]) || 0;
|
|
45
|
+
const { key, mnemonic } = row.kind === 'instr' ? normalizeInstr(row.label) : { key: `<${row.kind}>`, mnemonic: `<${row.kind}>` };
|
|
46
|
+
return { label: String(row.label ?? ''), key, mnemonic, notes: row.notes ?? '', values, extras: extras.map((x) => x.kind), row };
|
|
47
|
+
};
|
|
48
|
+
for (const row of rows) {
|
|
49
|
+
if (row.kind !== 'instr') { pending.push(row); continue; }
|
|
50
|
+
units.push(unit(row, pending));
|
|
51
|
+
pending = [];
|
|
52
|
+
}
|
|
53
|
+
for (const row of pending) units.push(unit(row, [])); // extra uops after the last instruction (not expected)
|
|
54
|
+
return units;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Longest common subsequence of two arrays of keys: [[i, j], ...] of the matched pairs, in order. The common
|
|
58
|
+
// prefix and suffix are matched first; the rest uses the quadratic table (up to `limit` cells), beyond that
|
|
59
|
+
// nothing more is matched.
|
|
60
|
+
export function lcsPairs(a, b, limit = 4e6) {
|
|
61
|
+
const pairs = [];
|
|
62
|
+
let lo = 0;
|
|
63
|
+
while (lo < a.length && lo < b.length && a[lo] === b[lo]) { pairs.push([lo, lo]); lo++; }
|
|
64
|
+
let ha = a.length, hb = b.length;
|
|
65
|
+
const tail = [];
|
|
66
|
+
while (ha > lo && hb > lo && a[ha - 1] === b[hb - 1]) { ha--; hb--; tail.push([ha, hb]); }
|
|
67
|
+
const n = ha - lo, m = hb - lo;
|
|
68
|
+
if (n > 0 && m > 0 && n * m <= limit) {
|
|
69
|
+
const w = m + 1;
|
|
70
|
+
const t = new Uint32Array((n + 1) * w); // t[i][j]: LCS length of a[lo+i..ha) and b[lo+j..hb)
|
|
71
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
72
|
+
for (let j = m - 1; j >= 0; j--) {
|
|
73
|
+
t[i * w + j] = a[lo + i] === b[lo + j] ? t[(i + 1) * w + j + 1] + 1 : Math.max(t[(i + 1) * w + j], t[i * w + j + 1]);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
let i = 0, j = 0;
|
|
77
|
+
while (i < n && j < m) {
|
|
78
|
+
if (a[lo + i] === b[lo + j]) { pairs.push([lo + i, lo + j]); i++; j++; }
|
|
79
|
+
else if (t[(i + 1) * w + j] >= t[i * w + j + 1]) i++;
|
|
80
|
+
else j++;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
for (let k = tail.length - 1; k >= 0; k--) pairs.push(tail[k]);
|
|
84
|
+
return pairs;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Aligns two lists of instruction units: [{op, a, b}] with op
|
|
88
|
+
// 'same' the same instruction text (a and b are indices)
|
|
89
|
+
// 'modified' in a stretch between matches, the same mnemonic with other operands
|
|
90
|
+
// 'removed' only in A (b is null), 'added' only in B (a is null)
|
|
91
|
+
export function alignUnits(ua, ub) {
|
|
92
|
+
const out = [];
|
|
93
|
+
const gap = (a0, a1, b0, b1) => { // the unmatched stretches a0..a1 and b0..b1: pair them by mnemonic
|
|
94
|
+
const pa = lcsPairs(ua.slice(a0, a1).map((u) => u.mnemonic), ub.slice(b0, b1).map((u) => u.mnemonic));
|
|
95
|
+
let i = a0, j = b0;
|
|
96
|
+
for (const [x, y] of pa) {
|
|
97
|
+
while (i < a0 + x) out.push({ op: 'removed', a: i++, b: null });
|
|
98
|
+
while (j < b0 + y) out.push({ op: 'added', a: null, b: j++ });
|
|
99
|
+
out.push({ op: 'modified', a: i++, b: j++ });
|
|
100
|
+
}
|
|
101
|
+
while (i < a1) out.push({ op: 'removed', a: i++, b: null });
|
|
102
|
+
while (j < b1) out.push({ op: 'added', a: null, b: j++ });
|
|
103
|
+
};
|
|
104
|
+
let i = 0, j = 0;
|
|
105
|
+
for (const [x, y] of lcsPairs(ua.map((u) => u.key), ub.map((u) => u.key))) {
|
|
106
|
+
gap(i, x, j, y);
|
|
107
|
+
out.push({ op: 'same', a: x, b: y });
|
|
108
|
+
i = x + 1; j = y + 1;
|
|
109
|
+
}
|
|
110
|
+
gap(i, ua.length, j, ub.length);
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const okResponse = (r) => !!r && typeof r === 'object' && !('error' in r) && Array.isArray(r.rows) && Array.isArray(r.columns);
|
|
115
|
+
const round = (v) => (Math.abs(v) < EPS ? 0 : v);
|
|
116
|
+
|
|
117
|
+
// The columns both responses have (by name), in A's order: [{name, kind, ia, ib}].
|
|
118
|
+
export function sharedColumns(ra, rb) {
|
|
119
|
+
return ra.columns.map((name, ia) => ({ name, kind: columnKind(name), ia, ib: rb.columns.indexOf(name) })).filter((c) => c.ib >= 0);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Two cycle counts (per iteration or per element) are the same when they differ by less than REL of the larger one:
|
|
123
|
+
// uiCA's throughputs are exact to its two decimals at about 2 cycles, and per element they can be 100× smaller, so the
|
|
124
|
+
// test is relative, on the unrounded values.
|
|
125
|
+
export const REL = 0.0025;
|
|
126
|
+
export const sameValue = (a, b) => Math.abs(b - a) <= REL * Math.max(Math.abs(a), Math.abs(b));
|
|
127
|
+
// verdict for a change of a cycle count from a to b (lower is better); verdict(delta) alone: against EPS (older form)
|
|
128
|
+
export function verdict(a, b) {
|
|
129
|
+
if (b === undefined) return Math.abs(a) < EPS ? 'same' : a < 0 ? 'better' : 'worse';
|
|
130
|
+
return sameValue(a, b) ? 'same' : b < a ? 'better' : 'worse';
|
|
131
|
+
}
|
|
132
|
+
// A cycle count as shown: two decimals, or three significant digits below 0.1 (per element: 0.0156)
|
|
133
|
+
export function cycles(v) {
|
|
134
|
+
if (typeof v !== 'number' || !Number.isFinite(v)) return '–';
|
|
135
|
+
const a = Math.abs(v);
|
|
136
|
+
return a !== 0 && a < 0.1 ? v.toPrecision(3) : v.toFixed(2);
|
|
137
|
+
}
|
|
138
|
+
// a change of a cycle count, with its sign (a real minus sign): "+1.50", "−0.00313"
|
|
139
|
+
export const signedCycles = (v) => `${v < 0 ? '−' : '+'}${cycles(Math.abs(v))}`;
|
|
140
|
+
|
|
141
|
+
// The comparison of two responses. workA, workB: the elements (or bytes) one iteration of A and of B processes; the
|
|
142
|
+
// cycle counts are divided by them before they are compared (cycles per element). scale (older form): B does the work
|
|
143
|
+
// of `scale` iterations of A, i.e. workA = 1, workB = scale.
|
|
144
|
+
// Either response may be an error ({error}) or missing: then only what can be compared is filled in.
|
|
145
|
+
/**
|
|
146
|
+
* @param {any} ra
|
|
147
|
+
* @param {any} rb
|
|
148
|
+
* @param {{workA?: number, workB?: number | null, scale?: number}} [opts]
|
|
149
|
+
*/
|
|
150
|
+
export function compareResponses(ra, rb, { workA = 1, workB = null, scale = 1 } = {}) {
|
|
151
|
+
const wa = workA > 0 ? workA : 1, wb = workB !== null && workB > 0 ? workB : scale > 0 ? scale : 1;
|
|
152
|
+
const okA = okResponse(ra), okB = okResponse(rb);
|
|
153
|
+
/** @type {any} */
|
|
154
|
+
const out = { okA, okB, workA: wa, workB: wb, scale: wb / wa, perElement: wa !== 1 || wb !== 1, tp: null, bottlenecks: null, limits: [], diff: null };
|
|
155
|
+
if (!okA || !okB) return out;
|
|
156
|
+
const a = Number(ra.tp) / wa, b = Number(rb.tp) / wb;
|
|
157
|
+
const v = verdict(a, b);
|
|
158
|
+
const delta = v === 'same' ? 0 : b - a; // (unrounded; 0 when the same)
|
|
159
|
+
out.tp = { a, b, aRaw: Number(ra.tp), bRaw: Number(rb.tp), delta, pct: a > 0 ? (100 * delta) / a : null, speedup: b > 0 ? a / b : null, verdict: v };
|
|
160
|
+
|
|
161
|
+
const ba = ra.bottlenecks ?? [], bb = rb.bottlenecks ?? [];
|
|
162
|
+
out.bottlenecks = { a: ba, b: bb, same: ba.length === bb.length && ba.every((x) => bb.includes(x)),
|
|
163
|
+
gone: ba.filter((x) => !bb.includes(x)), new: bb.filter((x) => !ba.includes(x)), kept: ba.filter((x) => bb.includes(x)) };
|
|
164
|
+
|
|
165
|
+
const names = [...new Set([...(ra.limits ?? []).map((l) => l.name), ...(rb.limits ?? []).map((l) => l.name)])];
|
|
166
|
+
out.limits = names.map((name) => {
|
|
167
|
+
const la = ra.limits.find((l) => l.name === name), lb = rb.limits.find((l) => l.name === name);
|
|
168
|
+
const va = la ? Number(la.tp) / wa : null, vb = lb ? Number(lb.tp) / wb : null;
|
|
169
|
+
return { name, a: va, b: vb, delta: va !== null && vb !== null ? (sameValue(va, vb) ? 0 : vb - va) : null,
|
|
170
|
+
bottleneckA: ba.includes(name), bottleneckB: bb.includes(name) };
|
|
171
|
+
});
|
|
172
|
+
out.diff = diffTables(ra, rb);
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// The instruction-by-instruction difference of two uop tables.
|
|
177
|
+
// rows: [{status, a: unit|null, b: unit|null, deltas: [per shown column, B − A]}]
|
|
178
|
+
// status: 'same' | 'changed' (same instruction, other uops) | 'modified' | 'added' | 'removed'
|
|
179
|
+
// minor: a 'changed' row whose every shared column differs by less than MINOR (and the notes are the same)
|
|
180
|
+
// columns: the shared columns that are shown: the issued uops and every execution port either side uses
|
|
181
|
+
// totals: the sum of the deltas per shown column
|
|
182
|
+
// portsComparable: false if the two sides have different execution ports (e.g. Skylake and Zen 3)
|
|
183
|
+
// counts: rows per status
|
|
184
|
+
export function diffTables(ra, rb) {
|
|
185
|
+
const ua = instructionUnits(ra), ub = instructionUnits(rb);
|
|
186
|
+
const shared = sharedColumns(ra, rb);
|
|
187
|
+
const portsA = ra.columns.filter((c) => columnKind(c) === 'port'), portsB = rb.columns.filter((c) => columnKind(c) === 'port');
|
|
188
|
+
const portsComparable = portsA.length === portsB.length && portsA.every((c) => portsB.includes(c));
|
|
189
|
+
const used = (c) => [ra, rb].some((r, k) => r.rows.some((x) => Number(x.values?.[k ? c.ib : c.ia]) > 0));
|
|
190
|
+
const columns = shared.filter((c) => (c.name === 'Issued' || (c.kind === 'port' && portsComparable)) && used(c));
|
|
191
|
+
const counts = { same: 0, changed: 0, modified: 0, added: 0, removed: 0 };
|
|
192
|
+
const totals = new Array(columns.length).fill(0);
|
|
193
|
+
const rows = alignUnits(ua, ub).map(({ op, a, b }) => {
|
|
194
|
+
const x = a === null ? null : ua[a], y = b === null ? null : ub[b];
|
|
195
|
+
const deltas = columns.map((c, k) => {
|
|
196
|
+
const d = (y ? y.values[c.ib] : 0) - (x ? x.values[c.ia] : 0);
|
|
197
|
+
totals[k] += d;
|
|
198
|
+
return round(d);
|
|
199
|
+
});
|
|
200
|
+
let status = op, minor = false;
|
|
201
|
+
if (op === 'same') {
|
|
202
|
+
const allShared = shared.every((c) => Math.abs(y.values[c.ib] - x.values[c.ia]) < EPS);
|
|
203
|
+
status = allShared && x.notes === y.notes && (portsComparable || deltas.every((d) => d === 0)) ? 'same' : 'changed';
|
|
204
|
+
minor = status === 'changed' && x.notes === y.notes && shared.every((c) => Math.abs(y.values[c.ib] - x.values[c.ia]) < MINOR);
|
|
205
|
+
}
|
|
206
|
+
counts[status]++;
|
|
207
|
+
return { status, a: x, b: y, deltas, ...(minor ? { minor } : {}) };
|
|
208
|
+
});
|
|
209
|
+
return { rows, columns, totals: totals.map(round), portsComparable, counts };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// "+0.25", "−0.5" (a real minus sign), "" for zero
|
|
213
|
+
export function signed(v, digits = 2) {
|
|
214
|
+
if (typeof v !== 'number' || !Number.isFinite(v) || Math.abs(v) < EPS) return '';
|
|
215
|
+
const s = String(Math.round(Math.abs(v) * 10 ** digits) / 10 ** digits);
|
|
216
|
+
return (v < 0 ? '−' : '+') + s;
|
|
217
|
+
}
|
package/lib/web/accum.js
CHANGED
|
@@ -12,12 +12,14 @@ const GPR = [
|
|
|
12
12
|
['rsi', 'esi', 'si', 'sil'], ['rdi', 'edi', 'di', 'dil'], ['rbp', 'ebp', 'bp', 'bpl'], ['rsp', 'esp', 'sp', 'spl'],
|
|
13
13
|
...Array.from({ length: 8 }, (_, k) => [`r${k + 8}`, `r${k + 8}d`, `r${k + 8}w`, `r${k + 8}b`]),
|
|
14
14
|
];
|
|
15
|
+
/** @type {Map<string, Family>} */
|
|
15
16
|
const FAMILY = new Map(GPR.flatMap((names) => names.map((n, size) => [n, { kind: 'gpr', base: names[0], size }])));
|
|
16
17
|
// the registers a copy can get, in this order (not rsp; the ones with implicit uses last)
|
|
17
18
|
const GPR_FREE = ['r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15', 'rbx', 'rbp', 'rsi', 'rdi', 'rcx', 'rdx', 'rax'];
|
|
18
19
|
// Instructions with implicit register operands (the response has no operand sets without the details: this list is
|
|
19
20
|
// the x86-64 instructions that read or write a register they do not name): [test, registers]. 'vall': every vector
|
|
20
21
|
// register. Renaming such a register would change what they do, and none of them may get a copy's register.
|
|
22
|
+
/** @type {[RegExp, string[]][]} */
|
|
21
23
|
const IMPLICIT = [
|
|
22
24
|
[/^(?:i?div|mul|cdq|cqo|cwd|rdtsc|xsave\w*|xrstor\w*|in|out)$/, ['rax', 'rdx']],
|
|
23
25
|
[/^(?:cbw|cwde|cdqe|lahf|sahf|cmpxchg|stos\w*|lods\w*|scas\w*)$/, ['rax']],
|
|
@@ -51,17 +53,21 @@ export const implicitUse = (mnemonic, operands) => {
|
|
|
51
53
|
const VEC = /^([xyz]mm)(\d+)$/;
|
|
52
54
|
|
|
53
55
|
// The family of a register name: {kind: 'gpr', base: 'rax', size} or {kind: 'vec', index}; null if not renamable.
|
|
56
|
+
/** @typedef {{kind: 'gpr', base: string, size: number} | {kind: 'vec', base: string, index: number}} Family */
|
|
57
|
+
/** @returns {Family | null} */
|
|
54
58
|
export function family(name) {
|
|
55
59
|
const n = String(name).toLowerCase();
|
|
56
60
|
const v = VEC.exec(n);
|
|
57
|
-
if (v) return { kind: 'vec', index: Number(v[2]), base: `v${v[2]}` };
|
|
61
|
+
if (v) return { kind: /** @type {const} */ ('vec'), index: Number(v[2]), base: `v${v[2]}` };
|
|
58
62
|
return FAMILY.get(n) ?? null;
|
|
59
63
|
}
|
|
60
64
|
|
|
61
65
|
// The registers on the critical loop-carried chain: {ok, bases: ['rax' | 'v0', ...], names} or {ok: false, reason}.
|
|
66
|
+
/** @returns {{ok: true, bases: string[], names: string[]} | {ok: false, reason: string}} */
|
|
62
67
|
export function chainRegisters(response) {
|
|
63
68
|
const edges = response?.criticalPath?.edges;
|
|
64
69
|
if (!Array.isArray(edges) || !edges.length) return { ok: false, reason: 'no loop-carried chain' };
|
|
70
|
+
/** @type {string[]} */
|
|
65
71
|
const bases = [], names = [];
|
|
66
72
|
for (const e of edges) {
|
|
67
73
|
const op = String(e.operand ?? '');
|
|
@@ -87,7 +93,7 @@ function renameText(text, map) {
|
|
|
87
93
|
if (!f || !map.has(f.base)) return tok;
|
|
88
94
|
const to = map.get(f.base);
|
|
89
95
|
if (f.kind === 'vec') return tok.slice(0, 3) + to.slice(1);
|
|
90
|
-
const names = GPR.find((g) => g[0] === to);
|
|
96
|
+
const names = GPR.find((g) => g[0] === to) ?? [];
|
|
91
97
|
const n = names[f.size];
|
|
92
98
|
if (!n) { bad = true; return tok; }
|
|
93
99
|
return tok === tok.toUpperCase() ? n.toUpperCase() : n;
|
|
@@ -125,6 +131,7 @@ const splitInstr = (label) => { const t = String(label).trim().replace(/\s+/g, '
|
|
|
125
131
|
|
|
126
132
|
// The variant with n accumulators: {ok: true, text, per: n, renamed: [{from, to: [names]}]} or {ok: false, reason}.
|
|
127
133
|
// response: the analysis of hex (a loop); the rows must make up the code (as for the unrolled variants).
|
|
134
|
+
/** @returns {{ok: true, text: string, per: number, renamed: {from: string, to: string[]}[]} | {ok: false, reason: string}} */
|
|
128
135
|
export function accumulatorText(response, hex, n) {
|
|
129
136
|
if (response?.mode !== 'loop') return { ok: false, reason: 'not a loop' };
|
|
130
137
|
const rows = Array.isArray(response.rows) ? response.rows : [];
|
|
@@ -145,6 +152,7 @@ export function accumulatorText(response, hex, n) {
|
|
|
145
152
|
const body = ins.slice(0, tailFrom), tail = ins.slice(tailFrom);
|
|
146
153
|
// registers in use (any form: al/ax/eax/rax, xmm/ymm/zmm are one register), and the implicit ones
|
|
147
154
|
const uses = (i) => { const s = splitInstr(i.label); return new Set([...regsIn(i.label).map((r) => family(r)?.base).filter(Boolean), ...implicitUse(s.mnemonic, s.operands)]); };
|
|
155
|
+
/** @type {Map<any, any>} */
|
|
148
156
|
const usesOf = new Map(ins.map((i) => [i, uses(i)]));
|
|
149
157
|
const used = new Set(ins.flatMap((i) => [...usesOf.get(i)]));
|
|
150
158
|
const implicit = new Set(ins.flatMap((i) => { const s = splitInstr(i.label); return implicitUse(s.mnemonic, s.operands); }));
|
package/lib/web/asm-regions.js
CHANGED
|
@@ -42,6 +42,11 @@ const sectionName = (args) => (/^\s*("?)([^",\s]+)\1/.exec(args)?.[2] ?? '');
|
|
|
42
42
|
// opts (loop-find.js, preparePaste): pick {begin, end}: lines (1-based) of the code to analyze when nothing is marked (the
|
|
43
43
|
// loop: its first instruction at or after `begin` to the end of line `end`); stubs: symbols to define right after the
|
|
44
44
|
// analyzed code (the loop's exits: its conditional branches out of it are then short and not taken).
|
|
45
|
+
/**
|
|
46
|
+
* @param {string} text
|
|
47
|
+
* @param {{pick?: {begin: number, end: number} | null, stubs?: string[]}} [opts]
|
|
48
|
+
* @returns {any}
|
|
49
|
+
*/
|
|
45
50
|
export function planMarked(text, { pick = null, stubs = [] } = {}) {
|
|
46
51
|
text = String(text ?? '');
|
|
47
52
|
if (!QUICK.test(text) && !pick && !stubs.length) return null;
|
|
@@ -49,10 +54,15 @@ export function planMarked(text, { pick = null, stubs = [] } = {}) {
|
|
|
49
54
|
const labels = [];
|
|
50
55
|
const inserts = []; // {line, col, label}
|
|
51
56
|
const regions = [];
|
|
52
|
-
|
|
53
|
-
|
|
57
|
+
/** @type {any} */
|
|
58
|
+
let region = null;
|
|
59
|
+
let pendingBegin = false;
|
|
60
|
+
/** @type {{line: number, message: string} | null} */
|
|
61
|
+
let error = null;
|
|
62
|
+
const locs = [], files = new Map();
|
|
54
63
|
let inText = true, prev = false;
|
|
55
64
|
const stack = [];
|
|
65
|
+
/** @type {any} */
|
|
56
66
|
let iaca = null; // {kind: '111' | '222', line, col} of a mov that can be an IACA marker
|
|
57
67
|
let block = false;
|
|
58
68
|
const label = (line, col) => { const name = `.Lwuica_${labels.length}`; labels.push(name); inserts.push({ line, col, label: name }); return labels.length - 1; };
|
|
@@ -98,7 +108,7 @@ export function planMarked(text, { pick = null, stubs = [] } = {}) {
|
|
|
98
108
|
}
|
|
99
109
|
const sts = statements(line);
|
|
100
110
|
for (const st of sts) {
|
|
101
|
-
const lead = LABELS.exec(st.text)[0].length;
|
|
111
|
+
const lead = /** @type {RegExpExecArray} */ (LABELS.exec(st.text))[0].length;
|
|
102
112
|
const body = st.text.slice(lead);
|
|
103
113
|
if (!body) continue;
|
|
104
114
|
const col = st.at + lead;
|
|
@@ -122,18 +132,11 @@ export function planMarked(text, { pick = null, stubs = [] } = {}) {
|
|
|
122
132
|
const name = d?.[1].toLowerCase() ?? '';
|
|
123
133
|
const args = d?.[2] ?? '';
|
|
124
134
|
// an objdump line with its bytes (loop-find.js) starts the picked code like an instruction
|
|
125
|
-
if (name === 'byte' && pickPending && inText && i + 1 >= pick
|
|
135
|
+
if (name === 'byte' && pickPending && inText && i + 1 >= Number(pick?.begin)) { region.begin = label(i, col); pickPending = false; }
|
|
126
136
|
if (name === 'loc') {
|
|
127
137
|
const m = /^(\d+)\s+(\d+)/.exec(args);
|
|
128
138
|
if (m && inText) locs.push({ label: label(i, col), file: Number(m[1]), line: Number(m[2]) });
|
|
129
|
-
//
|
|
130
|
-
// (a symbol of it, which the debug sections can use, is defined as 0 in the trailer)
|
|
131
|
-
const v = /\bview\s+(\S+)/.exec(body);
|
|
132
|
-
if (v) {
|
|
133
|
-
const at = col + v.index;
|
|
134
|
-
lines[i] = lines[i].slice(0, at) + ' '.repeat(v[0].length) + lines[i].slice(at + v[0].length);
|
|
135
|
-
if (/^[A-Za-z_.$][\w.$]*$/.test(v[1])) views.add(v[1]);
|
|
136
|
-
}
|
|
139
|
+
// (the directive itself is not assembled: assembler.js withoutLineTable)
|
|
137
140
|
} else if (name === 'file') {
|
|
138
141
|
const m = /^(\d+)\s/.exec(args);
|
|
139
142
|
const q = quoted(args);
|
|
@@ -148,7 +151,7 @@ export function planMarked(text, { pick = null, stubs = [] } = {}) {
|
|
|
148
151
|
}
|
|
149
152
|
if (/^[\w.$@]+\s*=/.test(body)) continue; // a symbol assignment
|
|
150
153
|
// an instruction
|
|
151
|
-
if (pickPending && inText && i + 1 >= pick
|
|
154
|
+
if (pickPending && inText && i + 1 >= Number(pick?.begin)) { region.begin = label(i, col); pickPending = false; }
|
|
152
155
|
// (a mov that can be an IACA marker is decided by the next statement)
|
|
153
156
|
const im = IACA_MOV.exec(body);
|
|
154
157
|
if (im) iaca = { kind: im[1] ?? im[2], line: i, col, inText };
|
|
@@ -183,9 +186,8 @@ export function planMarked(text, { pick = null, stubs = [] } = {}) {
|
|
|
183
186
|
const lineCount = lines.length;
|
|
184
187
|
const parts = [];
|
|
185
188
|
for (let k = 0; k < labels.length; k += 32) parts.push(`.long ${labels.slice(k, k + 32).map((n) => `.Lwuica_z-${n}`).join(', ')}`);
|
|
186
|
-
const sets = [...views].map((n) => `.set ${n}, 0\n`).join('');
|
|
187
189
|
const tail = stubsPlaced ? '' : `${stubs.map((n) => `${n}:`).join('\n')}\n`; // the exits at the end of the code
|
|
188
|
-
const out = `${lines.join('\n')}\n
|
|
190
|
+
const out = `${lines.join('\n')}\n.text\n${tail}.Lwuica_z:\n.long ${MAGIC}\n${parts.join('\n')}\n`;
|
|
189
191
|
if (region) delete region.closed;
|
|
190
192
|
return { text: out, labels, regions, region, locs, files, shifts, lineCount, error };
|
|
191
193
|
}
|
|
@@ -232,7 +234,9 @@ const base = (p) => String(p).split(/[\\/]/).pop();
|
|
|
232
234
|
|
|
233
235
|
// The analyzed bytes and the source lines of a plan: {bytes, region, source} or {error}.
|
|
234
236
|
export function cutPlan(plan, code, offsets) {
|
|
235
|
-
let start = 0, end = code.length
|
|
237
|
+
let start = 0, end = code.length;
|
|
238
|
+
/** @type {any} */
|
|
239
|
+
let region = null;
|
|
236
240
|
if (plan.region) {
|
|
237
241
|
const r = plan.region;
|
|
238
242
|
if (plan.error) return { error: plan.error };
|
|
@@ -241,6 +245,7 @@ export function cutPlan(plan, code, offsets) {
|
|
|
241
245
|
if (!(end > start)) return { error: { line: r.line, message: 'the marked region has no machine code in .text' } };
|
|
242
246
|
region = r.auto ? { auto: true } : { name: r.name, line: r.line, index: 0, count: plan.regions.length };
|
|
243
247
|
}
|
|
248
|
+
/** @type {any} */
|
|
244
249
|
let source = null;
|
|
245
250
|
if (plan.locs.length) {
|
|
246
251
|
const at = plan.locs.map((l) => ({ off: offsets[l.label], file: l.file, line: l.line }))
|
|
@@ -343,8 +348,8 @@ export function separatorNotes(text) {
|
|
|
343
348
|
// count} | null) and source ({text: null, file, spans: [{off, line}]} | null). assemble(text) -> promise of that result.
|
|
344
349
|
// A ';' comment after a statement is retried as '#' (above).
|
|
345
350
|
// opts.loop ('auto', 'whole' or a loop's index): the text is assembled for an analysis (loop-find.js): objdump lines,
|
|
346
|
-
// the loop or the body of a function, the exits as not taken. The result then also has loop ({index, count, name,
|
|
347
|
-
// endLine, address, alignment} | null: what was picked), loops ([{begin, end, label}]: the choices), body ({begin, end}
|
|
351
|
+
// the loop or the body of a function, the exits as not taken. The result then also has loop ({index, count, name, auto,
|
|
352
|
+
// line, endLine, address, alignment} | null: what was picked; auto: the default picked it), loops ([{begin, end, label}]: the choices), body ({begin, end}
|
|
348
353
|
// | null), choosable (a choice matters: code around the loop or the body) and alignment (from
|
|
349
354
|
// the text's addresses, or null), and the notes (exits, undefined jump targets) among its diagnostics.
|
|
350
355
|
export async function assembleMarked(assemble, text, opts = {}) {
|
|
@@ -375,10 +380,12 @@ export async function assembleMarked(assemble, text, opts = {}) {
|
|
|
375
380
|
}
|
|
376
381
|
if (!prep) return r;
|
|
377
382
|
const loop = prep.choice === null ? null : {
|
|
378
|
-
index: prep.choice === 'body' ? null : prep.choice, count: prep.loops.length, name: loopName(prep),
|
|
383
|
+
index: prep.choice === 'body' ? null : prep.choice, count: prep.loops.length, name: loopName(prep), auto: !!prep.auto,
|
|
379
384
|
line: prep.pick.begin, endLine: prep.pick.end, lines: prep.pick.lines, address: prep.address, alignment: prep.alignment,
|
|
380
385
|
};
|
|
381
|
-
|
|
386
|
+
// the source line of each analyzed instruction: of the pick, or of the whole text (not with a marked region)
|
|
387
|
+
const lines = prep.exactLines === false ? null : prep.pick ? prep.pick.lines : r.region ? null : prep.lines ?? null;
|
|
388
|
+
const out = { ...r, loop, loops: prep.loops, body: prep.body, choosable: prep.choosable, alignment: prep.alignment, lines, lineInfo: prep.lineInfo ?? null, profile: prep.profile ?? null };
|
|
382
389
|
if (r.ok && prep.notes.length) out.diagnostics = [...r.diagnostics, ...prep.notes];
|
|
383
390
|
return out;
|
|
384
391
|
}
|