wuica-cli 0.1.9 → 0.1.10
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 +96 -30
- package/dist/data/uarch.json.br +0 -0
- package/dist/manifest.json +6 -6
- package/dist/wuica_wasm.wasm.br +0 -0
- package/index.d.ts +164 -10
- package/lib/cli.js +194 -39
- 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 +100 -17
- package/lib/mcp.js +107 -84
- package/lib/objfile.js +4 -2
- 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 +24 -17
- 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 +139 -16
- package/lib/web/markdown.js +437 -0
- package/lib/web/whatif-core.js +339 -0
- package/package.json +3 -1
- package/lib/insights.js +0 -100
- package/lib/whatif.js +0 -136
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
// What-if experiments without the DOM: the whole block re-analyzed with one change each: unrolled ×2/×4/×8 (n copies of
|
|
2
|
+
// the body and the loop's branch once, per original iteration), N accumulators (unrolled ×N with the chain's register
|
|
3
|
+
// renamed in each copy: accum.js, assembled), the front end limited only by the issue width, macro- or micro-fusion
|
|
4
|
+
// switched; and the estimate without the loop-carried chain (the largest other limit, no analysis). One module for the
|
|
5
|
+
// page (whatif.js runs the experiments on its engines and renders them) and the npm package (whatIf(), the MCP tool
|
|
6
|
+
// what_if; its copy in packages/wuica/lib/web, web-modules.json).
|
|
7
|
+
|
|
8
|
+
import { ACCUMULATORS, accumulatorText, bestAccumulators } from './accum.js';
|
|
9
|
+
|
|
10
|
+
export const VARIANTS = Object.freeze(['unroll2', 'unroll4', 'unroll8', 'acc2', 'acc3', 'acc4', 'acc8', 'simpleFrontEnd', 'noMacroFusion', 'noMicroFusion', 'nochain']);
|
|
11
|
+
// Variants that run only when asked for (not in the default set): align, the block at each of the 64 alignment offsets
|
|
12
|
+
// (64 analyses: min, median, max, the best and the worst offset, the spread).
|
|
13
|
+
export const OPT_IN_VARIANTS = Object.freeze(['align']);
|
|
14
|
+
const ALL_VARIANTS = [...VARIANTS, ...OPT_IN_VARIANTS];
|
|
15
|
+
|
|
16
|
+
const UNROLL = [2, 4, 8];
|
|
17
|
+
|
|
18
|
+
// The instructions of a response as byte ranges of the code: [{row, start, end, fused}], or null if the rows do not
|
|
19
|
+
// make up the code (undecodable bytes).
|
|
20
|
+
export function instrRanges(response, hex) {
|
|
21
|
+
const rows = response?.rows;
|
|
22
|
+
if (!Array.isArray(rows)) return null;
|
|
23
|
+
const out = [];
|
|
24
|
+
let at = 0;
|
|
25
|
+
rows.forEach((x, row) => {
|
|
26
|
+
if (x.kind !== 'instr') return;
|
|
27
|
+
const op = String(x.opcode ?? '').toLowerCase();
|
|
28
|
+
out.push({ row, start: at, end: at + op.length / 2, op, fused: x.notes === 'M' });
|
|
29
|
+
at += op.length / 2;
|
|
30
|
+
});
|
|
31
|
+
if (!out.length || out.map((i) => i.op).join('') !== String(hex ?? '').toLowerCase()) return null;
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// The loop unrolled n times: n copies of the body, then the loop's branch once (with the instruction it is macro-fused
|
|
36
|
+
// with). Registers are not renamed: the dependencies stay; what goes is the loop overhead (n − 1 branches and their
|
|
37
|
+
// compares) and the front end sees a longer body. {ok, hex, tail} or {ok: false, reason}.
|
|
38
|
+
export function unrollHex(response, hex, n) {
|
|
39
|
+
if (response?.mode !== 'loop') return { ok: false, reason: 'not a loop' };
|
|
40
|
+
const ins = instrRanges(response, hex);
|
|
41
|
+
if (!ins) return { ok: false, reason: 'the code has bytes that are not instructions' };
|
|
42
|
+
const last = ins.length - 1;
|
|
43
|
+
const tailFrom = ins[last].fused && last > 0 ? ins[last - 1].start : ins[last].start;
|
|
44
|
+
if (tailFrom === 0) return { ok: false, reason: 'nothing but the branch' };
|
|
45
|
+
const code = String(hex).toLowerCase();
|
|
46
|
+
return { ok: true, hex: code.slice(0, 2 * tailFrom).repeat(n) + code.slice(2 * tailFrom), tail: tailFrom === ins[last].start ? 1 : 2 };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const FLAGS = [
|
|
50
|
+
['simpleFrontEnd', 'simple front end', 'detailed front end', 'a front end limited only by the issue width (uiCA -simpleFrontEnd); not always faster'],
|
|
51
|
+
['noMacroFusion', 'no macro-fusion', 'macro-fusion', 'compare and branch not fused (uiCA -noMacroFusion)'],
|
|
52
|
+
['noMicroFusion', 'no micro-fusion', 'micro-fusion', 'load and operation not fused (uiCA -noMicroFusion)'],
|
|
53
|
+
];
|
|
54
|
+
|
|
55
|
+
// The experiments for a response: [{id, label, title, hex, options, per}] (analyses) and, if the chain is a limit,
|
|
56
|
+
// {id: 'nochain', label, estimate, title} (no analysis: the largest other limit, as uiCA computes them).
|
|
57
|
+
// The accumulator variants have `text` (assembly, accum.js) instead of hex until it is assembled, and `renamed` (the
|
|
58
|
+
// chain's registers and those of the copies); one that cannot be made has `error` (one row, 'acc').
|
|
59
|
+
// options: the request's options (alignmentOffset, ..., without hex, arch, includeTrace)
|
|
60
|
+
export function experiments(response, hex, options) {
|
|
61
|
+
const out = [];
|
|
62
|
+
for (const n of UNROLL) {
|
|
63
|
+
const u = unrollHex(response, hex, n);
|
|
64
|
+
if (u.ok) out.push({ id: `unroll${n}`, label: `unroll ×${n}`, per: n, hex: u.hex, options,
|
|
65
|
+
title: `${n} copies of the loop body and one branch${u.tail === 2 ? ' (with its macro-fused compare)' : ''}; registers not renamed, so the dependencies stay; per original iteration` });
|
|
66
|
+
}
|
|
67
|
+
if (response?.mode === 'loop' && response.criticalPath?.edges?.length) {
|
|
68
|
+
for (const n of ACCUMULATORS) {
|
|
69
|
+
const a = accumulatorText(response, hex, n);
|
|
70
|
+
// none possible: one row with the reason; a larger N alone (no free registers left): its row with the reason
|
|
71
|
+
if (!a.ok && n === ACCUMULATORS[0]) { out.push({ id: 'acc', label: 'accumulators', per: 1, error: a.reason, options, title: `N accumulators: ${a.reason}` }); break; }
|
|
72
|
+
if (!a.ok) { out.push({ id: `acc${n}`, label: `${n} accumulators`, per: n, error: a.reason, options, title: `${n} accumulators: ${a.reason}` }); continue; }
|
|
73
|
+
const names = a.renamed.map((x) => `${x.from} → ${x.to.join(', ')}`).join('; ');
|
|
74
|
+
out.push({ id: `acc${n}`, label: `${n} accumulators`, per: n, text: a.text, options, renamed: a.renamed,
|
|
75
|
+
title: `unrolled ×${n} with the chain's register renamed in each copy (${names}): ${n} independent chains; per original iteration` });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
for (const [k, on, off, what] of FLAGS) {
|
|
79
|
+
const v = !options?.[k];
|
|
80
|
+
out.push({ id: k, label: v ? on : off, per: 1, hex: String(hex).toLowerCase(), options: { ...options, [k]: v }, title: v ? what : `${off} (as without uiCA -${k})` });
|
|
81
|
+
}
|
|
82
|
+
const lims = Array.isArray(response?.limits) ? response.limits : [];
|
|
83
|
+
const dep = lims.find((l) => l.name === 'Dependencies');
|
|
84
|
+
const others = lims.filter((l) => l.name !== 'Dependencies').map((l) => Number(l.tp));
|
|
85
|
+
if (dep && others.length) {
|
|
86
|
+
const est = Math.max(...others);
|
|
87
|
+
out.push({ id: 'nochain', label: 'no chain', estimate: est, per: 1,
|
|
88
|
+
title: `at best the largest other limit (${lims.filter((l) => l.name !== 'Dependencies' && Number(l.tp) === est).map((l) => l.name).join(', ')}): an estimate without the loop-carried dependencies, not a simulation` });
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// The limits a simulation cannot beat in its steady state: port pressure and the issue width (uiCA's Ports and Issue
|
|
94
|
+
// limits). A variant's analysis measures its steady state over the iterations the simulation runs (fewer for an unrolled
|
|
95
|
+
// copy), and can come out a little under them: 8 accumulators on a dot product on SKL gave 63.75 cycles per 8 original
|
|
96
|
+
// iterations under its Ports limit of 64 (64.00 with minCycles 20000). The data keeps the simulated number (tp) and says
|
|
97
|
+
// so (approx: {limit, shown}: the limit per original iteration); the text, the Markdown and the page show such a variant
|
|
98
|
+
// at the limit, marked as approximate (≈; ~ in plain text): shownOutcome. Only within SAMPLING of the limit: uiCA's own results
|
|
99
|
+
// are under these limits too, by more (of 21,184 fixture responses, 278 under Ports, by up to 10%, and 68 under Issue,
|
|
100
|
+
// by up to 1.7%: its model, not sampling), and the loop-carried chain's limit is no floor at all (156, up to 86%).
|
|
101
|
+
const HARD_LIMITS = ['Ports', 'Issue'];
|
|
102
|
+
export const SAMPLING = 0.01; // relative
|
|
103
|
+
/** @param {any} limits @returns {{name: string, tp: number} | null} the largest of them */
|
|
104
|
+
export function hardLimit(limits) {
|
|
105
|
+
/** @type {{name: string, tp: number} | null} */
|
|
106
|
+
let best = null;
|
|
107
|
+
for (const l of Array.isArray(limits) ? limits : []) {
|
|
108
|
+
const tp = Number(l?.tp);
|
|
109
|
+
if (HARD_LIMITS.includes(l?.name) && Number.isFinite(tp) && (!best || tp > best.tp)) best = { name: l.name, tp };
|
|
110
|
+
}
|
|
111
|
+
return best;
|
|
112
|
+
}
|
|
113
|
+
// a variant's cycles per original iteration (r: its analysis, with limits): {tp (simulated), approx?: {limit, shown}}
|
|
114
|
+
function perOriginal(r, per) {
|
|
115
|
+
const tp = Number(r.tp) / per, hard = hardLimit(r.limits);
|
|
116
|
+
if (!hard) return { tp };
|
|
117
|
+
const floor = hard.tp / per;
|
|
118
|
+
if (!(tp < floor - 0.005) || floor - tp > SAMPLING * floor) return { tp };
|
|
119
|
+
return { tp, approx: { limit: hard.name, shown: floor } };
|
|
120
|
+
}
|
|
121
|
+
// What a display shows for a variant ({tp, delta, speedup, approx?}) against the base's cycles: at its limit when approx.
|
|
122
|
+
/** @param {any} v @param {number} baseTp @returns {{tp: number, delta: number, speedup: number | null}} */
|
|
123
|
+
export function shownOutcome(v, baseTp) {
|
|
124
|
+
if (!v.approx) return { tp: v.tp, delta: v.delta, speedup: v.speedup };
|
|
125
|
+
const tp = v.approx.shown;
|
|
126
|
+
return { tp, delta: tp - baseTp, speedup: tp > 0 ? baseTp / tp : null };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// One result line of the page: {tp (per original iteration, simulated), delta, speedup, comparable, approx?} from a
|
|
130
|
+
// summary ({tp, mode, limits} or {error}).
|
|
131
|
+
/** @returns {any} */
|
|
132
|
+
export function outcome(base, exp, r) {
|
|
133
|
+
if (exp.error) return { error: exp.error };
|
|
134
|
+
if (exp.estimate !== undefined) {
|
|
135
|
+
const tp = exp.estimate;
|
|
136
|
+
return { tp, delta: tp - base.tp, speedup: tp > 0 ? base.tp / tp : Infinity, estimate: true };
|
|
137
|
+
}
|
|
138
|
+
if (!r) return null;
|
|
139
|
+
if (r.error) return { error: r.error };
|
|
140
|
+
if (r.mode && base.mode && r.mode !== base.mode) return { error: `analyzed ${r.mode === 'loop' ? 'as a loop' : 'unrolled'}: not comparable` };
|
|
141
|
+
const { tp, approx } = perOriginal(r, exp.per);
|
|
142
|
+
return { tp, delta: tp - base.tp, speedup: tp > 0 ? base.tp / tp : Infinity, ...(approx ? { approx } : {}) };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// The size of an experiment relative to the block (the time of its analysis grows about linearly).
|
|
146
|
+
export const weight = (exp, baseBytes) => (exp.estimate !== undefined || exp.error ? 0 : exp.hex ? (exp.hex.length / 2) / Math.max(1, baseBytes) : exp.per);
|
|
147
|
+
|
|
148
|
+
// The best number of accumulators from the base throughput and the results of the accumulator variants ({n, tp} or
|
|
149
|
+
// null if none has a result).
|
|
150
|
+
export function bestOf(baseTp, exps, results) {
|
|
151
|
+
const tps = new Map([[1, Number(baseTp)]]);
|
|
152
|
+
for (const x of exps) {
|
|
153
|
+
if (!/^acc\d+$/.test(x.id)) continue;
|
|
154
|
+
const r = results.get(x.id);
|
|
155
|
+
if (r && !r.error && Number.isFinite(r.tp)) { const p = perOriginal(r, x.per); tps.set(x.per, p.approx?.shown ?? p.tp); } // (as shown)
|
|
156
|
+
}
|
|
157
|
+
return tps.size > 1 ? bestAccumulators(tps) : null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ---- the package's whatIf (the MCP tool what_if, the CLI's -whatif) -------------------------------------------------
|
|
161
|
+
|
|
162
|
+
// The label of a variant as experiments() gives it (for the variants it does not make).
|
|
163
|
+
function labelOf(id, options) {
|
|
164
|
+
if (id.startsWith('unroll')) return `unroll ×${id.slice(6)}`;
|
|
165
|
+
if (id.startsWith('acc')) return `${id.slice(3)} accumulators`;
|
|
166
|
+
if (id === 'align') return 'alignment 0-63';
|
|
167
|
+
const f = FLAGS.find(([k]) => k === id);
|
|
168
|
+
return f ? (options?.[id] ? f[2] : f[1]) : 'no chain';
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const round = (x) => Math.round(x * 100) / 100;
|
|
172
|
+
|
|
173
|
+
// What the package returns for one experiment, from the base result and the variant's (or its estimate).
|
|
174
|
+
export function toolOutcome(base, exp, r) {
|
|
175
|
+
const row = { id: exp.id, label: exp.label };
|
|
176
|
+
if (exp.renamed) row.renamed = exp.renamed;
|
|
177
|
+
let tp;
|
|
178
|
+
if (exp.error) return { ...row, error: exp.error };
|
|
179
|
+
if (exp.estimate !== undefined) { tp = exp.estimate; row.estimate = true; }
|
|
180
|
+
else if (!r || r.code !== 0) {
|
|
181
|
+
const error = r?.error ?? 'not analyzed';
|
|
182
|
+
// a limit or failure of the unrolled code, not of the caller's block: say so
|
|
183
|
+
return { ...row, error: exp.per > 1 && exp.hex ? `the block unrolled ×${exp.per} (${exp.hex.length} hex characters) could not be analyzed: ${error}` : error };
|
|
184
|
+
}
|
|
185
|
+
else if (r.mode !== base.mode) return { ...row, error: `analyzed ${r.mode === 'loop' ? 'as a loop' : 'unrolled'}: not comparable` };
|
|
186
|
+
else {
|
|
187
|
+
const p = perOriginal(r, exp.per);
|
|
188
|
+
tp = p.tp; row.bottlenecks = r.bottlenecks;
|
|
189
|
+
if (p.approx) row.approx = { limit: p.approx.limit, shown: round(p.approx.shown) };
|
|
190
|
+
}
|
|
191
|
+
return { ...row, tp: round(tp), delta: round(tp - base.tp), speedup: tp > 0 ? round(base.tp / tp) : null };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Runs the experiments with analyze(arch, {hex, options}) (one after another). request: as analyze's ({source | hex,
|
|
195
|
+
// syntax, loop, options}); variants: ids of VARIANTS (default: all); assemble(text) -> {code, hex} (the accumulator
|
|
196
|
+
// variants; Intel syntax). Resolves to {code: 0, arch, tp, mode, bottlenecks, loop?, variants: [{id, label, tp, delta,
|
|
197
|
+
// speedup, estimate?, bottlenecks?, renamed?, error?}], accumulators?: {best, tp}} or the base's failure.
|
|
198
|
+
// accumulators: the best number of accumulators (the smallest within 1% of the fastest, 1 = as it is) among those run.
|
|
199
|
+
/**
|
|
200
|
+
* @param {(arch: string, request: any) => Promise<any>} analyze
|
|
201
|
+
* @param {string} arch
|
|
202
|
+
* @param {any} request
|
|
203
|
+
* @param {readonly string[] | null} [variants]
|
|
204
|
+
* @param {{assemble?: ((text: string) => Promise<any>) | null}} [tools]
|
|
205
|
+
*/
|
|
206
|
+
export async function whatIf(analyze, arch, request, variants = VARIANTS, { assemble = null } = {}) {
|
|
207
|
+
const unknown = (variants ?? []).filter((v) => !ALL_VARIANTS.includes(v));
|
|
208
|
+
if (unknown.length) return { code: 1, error: `unknown variant(s): ${unknown.join(', ')} (known: ${ALL_VARIANTS.join(', ')})`, stderr: [] };
|
|
209
|
+
const base = await analyze(arch, request);
|
|
210
|
+
if (base.code !== 0) return base;
|
|
211
|
+
// a base its CPU cannot run (unsupported: caveats.js cannotRun, the library's analyze): its number is no result, so no
|
|
212
|
+
// variant compares with it: said once, no variants
|
|
213
|
+
if (base.unsupported) {
|
|
214
|
+
return { code: 0, arch: base.arch, tp: base.tp, mode: base.mode, bottlenecks: base.bottlenecks, ...(base.loop ? { loop: base.loop } : {}),
|
|
215
|
+
...(base.decodeErrors ? { decodeErrors: base.decodeErrors } : {}), ...(base.stderr?.length ? { stderr: base.stderr } : {}),
|
|
216
|
+
unit: 'cycles per original iteration', unsupported: base.unsupported, variants: [] };
|
|
217
|
+
}
|
|
218
|
+
// the code as the rows have it (the analyzed bytes, if every byte was decoded), for the unrolled copies; the other
|
|
219
|
+
// variants analyze the caller's code as given (hex in any form the library accepts, or the assembled bytes)
|
|
220
|
+
const rowsHex = base.decodeErrors ? '' : base.rows.filter((x) => x.kind === 'instr').map((x) => String(x.opcode ?? '').toLowerCase()).join('');
|
|
221
|
+
const code = base.hex !== undefined ? { hex: base.hex } : { hex: request.hex };
|
|
222
|
+
const options = { ...(request.options ?? {}) };
|
|
223
|
+
const want = new Set(variants ?? VARIANTS);
|
|
224
|
+
const out = [];
|
|
225
|
+
// the alignment offset the base got from the code's addresses (objdump input) holds for the variants too
|
|
226
|
+
if (options.alignmentOffset === undefined && request.alignmentOffset === undefined && base.loop?.alignmentOffset !== undefined) options.alignmentOffset = base.loop.alignmentOffset;
|
|
227
|
+
const exps = experiments(base, rowsHex, options);
|
|
228
|
+
const accError = exps.find((x) => x.id === 'acc')?.error;
|
|
229
|
+
// an analysis that says the request stops (notRun: a server's deadline for the whole request, a busy server): the
|
|
230
|
+
// variants without a result are "not run: <why>"; what finished stays
|
|
231
|
+
let halt = null;
|
|
232
|
+
const notRun = (exp) => ({ id: exp.id, label: labelOf(exp.id, options), error: `not run: ${halt}` });
|
|
233
|
+
for (const exp of exps) {
|
|
234
|
+
if (!want.has(exp.id)) continue;
|
|
235
|
+
if (exp.estimate !== undefined) { out.push(toolOutcome(base, exp, null)); continue; } // (no analysis: nochain)
|
|
236
|
+
if (halt) { out.push(notRun(exp)); continue; }
|
|
237
|
+
if (exp.text && !exp.hex) {
|
|
238
|
+
const a = assemble ? await assemble(exp.text) : null;
|
|
239
|
+
if (a?.notRun) { halt = a.notRun; out.push(notRun(exp)); continue; }
|
|
240
|
+
if (a?.code === 0 && a.hex) exp.hex = a.hex;
|
|
241
|
+
else { out.push(toolOutcome(base, { ...exp, error: a ? `the variant does not assemble: ${a.error}` : 'no assembler' }, null)); continue; }
|
|
242
|
+
}
|
|
243
|
+
const r = await analyze(base.arch, exp.per > 1 ? { hex: exp.hex, options: exp.options } : { ...code, options: exp.options });
|
|
244
|
+
if (r?.notRun) { halt = r.notRun; out.push(notRun(exp)); continue; }
|
|
245
|
+
out.push(toolOutcome(base, exp, r));
|
|
246
|
+
}
|
|
247
|
+
if (want.has('align')) {
|
|
248
|
+
if (halt) out.push(notRun({ id: 'align' }));
|
|
249
|
+
else {
|
|
250
|
+
const { notRun: why, ...a } = await alignment(analyze, base, code, options);
|
|
251
|
+
if (why) halt = why;
|
|
252
|
+
out.push(a);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
for (const id of want) {
|
|
256
|
+
if (!out.some((x) => x.id === id)) {
|
|
257
|
+
out.push({ id, label: labelOf(id, options), error: base.mode !== 'loop' && (id.startsWith('unroll') || id.startsWith('acc')) ? 'not a loop' : id === 'nochain' || id.startsWith('acc') ? (id.startsWith('acc') && accError) || 'no loop-carried chain' : 'not applicable' });
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
out.sort((a, b) => ALL_VARIANTS.indexOf(a.id) - ALL_VARIANTS.indexOf(b.id));
|
|
261
|
+
// (the best number of accumulators only when every accumulator variant asked for has run)
|
|
262
|
+
const accs = out.filter((x) => x.id.startsWith('acc') && x.tp !== undefined);
|
|
263
|
+
const accsCut = out.some((x) => x.id.startsWith('acc') && /^not run: /.test(x.error ?? ''));
|
|
264
|
+
const best = accs.length && !accsCut ? bestAccumulators(new Map([[1, base.tp], ...accs.map((x) => /** @type {[number, number]} */ ([Number(x.id.slice(3)), x.tp]))])) : null;
|
|
265
|
+
// (the base's decode errors and warnings: they hold for the variants too; and how many variants were not run)
|
|
266
|
+
const skipped = halt ? out.filter((x) => /^not run: /.test(x.error ?? '')).length : 0;
|
|
267
|
+
const stderr = [...(base.stderr ?? []), ...(halt ? [{ text: `Warning: ${skipped} of ${out.length} variant(s) not run: ${halt}` }] : [])];
|
|
268
|
+
return { code: 0, arch: base.arch, tp: base.tp, mode: base.mode, bottlenecks: base.bottlenecks, ...(base.loop ? { loop: base.loop } : {}),
|
|
269
|
+
...(base.decodeErrors ? { decodeErrors: base.decodeErrors } : {}), ...(stderr.length ? { stderr } : {}), ...(halt ? { notRun: halt } : {}),
|
|
270
|
+
unit: 'cycles per original iteration', variants: out, ...(best ? { accumulators: { best: best.n, tp: round(best.tp) } } : {}) };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// The variant align: the code at each alignment offset 0-63 (64 analyses with the other options as given). tp is the
|
|
274
|
+
// median; alignment: {min, median, max, best, worst (the first offset with the minimum, the maximum), spread (max - min),
|
|
275
|
+
// offset (the base's, 0-63: the analyzer reads an offset modulo 64)}. A failed analysis at any offset: the variant's error.
|
|
276
|
+
/** @returns {Promise<any>} */
|
|
277
|
+
async function alignment(analyze, base, code, options) {
|
|
278
|
+
const row = { id: 'align', label: labelOf('align') };
|
|
279
|
+
const tps = [];
|
|
280
|
+
for (let k = 0; k < 64; k++) {
|
|
281
|
+
const r = await analyze(base.arch, { ...code, options: { ...options, alignmentOffset: k } });
|
|
282
|
+
if (r.notRun) return { ...row, notRun: r.notRun, error: `not run: ${r.notRun} (${k} of the 64 offsets analyzed)` };
|
|
283
|
+
if (r.code !== 0) return { ...row, error: `alignment offset ${k}: ${r.error}` };
|
|
284
|
+
if (r.mode !== base.mode) return { ...row, error: `alignment offset ${k}: analyzed ${r.mode === 'loop' ? 'as a loop' : 'unrolled'}` };
|
|
285
|
+
tps.push(r.tp);
|
|
286
|
+
}
|
|
287
|
+
const sorted = [...tps].sort((a, b) => a - b);
|
|
288
|
+
const min = sorted[0], max = sorted[63], median = round((sorted[31] + sorted[32]) / 2);
|
|
289
|
+
return { ...row, tp: median, delta: round(median - base.tp), speedup: median > 0 ? round(base.tp / median) : null,
|
|
290
|
+
alignment: { min, median, max, best: tps.indexOf(min), worst: tps.indexOf(max), spread: round(max - min), offset: ((Number(options.alignmentOffset ?? 0) % 64) + 64) % 64 } };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// ---- per element and as text (the CLI's -whatif, the REST API's text/plain) ------------------------------------------------
|
|
294
|
+
|
|
295
|
+
// A what-if result with cycles per element (`per` elements per original iteration): elementsPerIteration and perElement on
|
|
296
|
+
// it, perElement on each variant with a tp. Unchanged without `per` or for a failure.
|
|
297
|
+
export function whatIfPerElement(x, per) {
|
|
298
|
+
if (!per || x.code) return x;
|
|
299
|
+
return { ...x, elementsPerIteration: per, perElement: x.tp / per, variants: x.variants.map((v) => (v.tp !== undefined ? { ...v, perElement: v.tp / per } : v)) };
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const fmt2 = (x) => Number(x).toFixed(2);
|
|
303
|
+
// cycles per element: 3 significant digits under 0.1 (0.0625, 0.0313), else two decimals
|
|
304
|
+
const fmtEl = (x) => (x !== 0 && Math.abs(x) < 0.1 ? Number(x).toPrecision(3) : fmt2(x));
|
|
305
|
+
const VARIANT_W = 18;
|
|
306
|
+
|
|
307
|
+
// The what-if table as text (per element with elementsPerIteration); a failure as one line.
|
|
308
|
+
export function whatIfText(x) {
|
|
309
|
+
if (x.code) return `What if (${x.arch ?? ''}): ${x.error}\n`;
|
|
310
|
+
if (x.unsupported) {
|
|
311
|
+
return [`What if (${x.arch}): not a result: ${x.unsupported} (the base ${fmt2(x.tp)} leaves out what ${x.arch} cannot run): no variants`,
|
|
312
|
+
...(x.stderr ?? []).map((l) => ` warning: ${String(l.text).replace(/^Warning: /, '')}`)].join('\n') + '\n';
|
|
313
|
+
}
|
|
314
|
+
const per = x.elementsPerIteration;
|
|
315
|
+
const f = per ? (v) => fmtEl(v / per) : fmt2;
|
|
316
|
+
const rows = x.variants.map((v) => { if (v.error) return ` ${v.label.padEnd(VARIANT_W)} ${'-'.padStart(8)} ${v.error}`;
|
|
317
|
+
const s = shownOutcome(v, x.tp);
|
|
318
|
+
return ` ${v.label.padEnd(VARIANT_W)} ${`${v.estimate ? '>=' : v.approx ? '~' : ''}${f(s.tp)}`.padStart(8)} ${`${s.delta > 0 ? '+' : ''}${f(s.delta)}`.padStart(8)} ${`${fmt2(s.speedup ?? 0)}x`.padStart(7)}${v.approx ? ` at its ${v.approx.limit} limit (simulated ${per ? Number(v.tp / per).toPrecision(3) : fmt2(v.tp)})` : ''}`; });
|
|
319
|
+
return [per ? `What if (${x.arch}), cycles per element (${per} per original iteration; base ${fmtEl(x.tp / per)}):` : `What if (${x.arch}), cycles per original iteration (base ${fmt2(x.tp)}):`,
|
|
320
|
+
` ${'variant'.padEnd(VARIANT_W)} ${'cycles'.padStart(8)} ${'delta'.padStart(8)} ${'speedup'.padStart(7)}`, ...rows,
|
|
321
|
+
...(x.accumulators ? [` best number of accumulators: ${x.accumulators.best}${x.accumulators.best === 1 ? ' (as it is)' : ''}`] : []),
|
|
322
|
+
...x.variants.filter((v) => v.alignment).map((v) => { const a = v.alignment; return ` alignment over 64 offsets: min ${f(a.min)} (offset ${a.best}), median ${f(a.median)}, max ${f(a.max)} (offset ${a.worst}), spread ${f(a.spread)}; this block at offset ${a.offset}`; }),
|
|
323
|
+
...(x.stderr ?? []).map((l) => ` warning: ${String(l.text).replace(/^Warning: /, '')}`)].join('\n') + '\n';
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// The what-if of a request as the interfaces take it (the library's whatIf method, the MCP tool what_if, the REST API's
|
|
327
|
+
// POST /api/what-if/<arch>): w has analyze(arch, request) and assemble(text, syntax); request is analyze's ({source | hex,
|
|
328
|
+
// syntax, loop, func, options}) with `variants` (ids of VARIANTS, default all) and `per` (elements per original
|
|
329
|
+
// iteration: also cycles per element). Resolves to whatIf's result (whatIfPerElement with `per`) or a failure.
|
|
330
|
+
/** @param {any} w @param {string} arch @param {any} [request] @returns {Promise<any>} */
|
|
331
|
+
export async function whatIfRequest(w, arch, request = {}) {
|
|
332
|
+
const bad = (error) => ({ code: 1, error, stderr: [{ text: error }] });
|
|
333
|
+
if (request === null || typeof request !== 'object' || Array.isArray(request)) return bad('the request must be an object');
|
|
334
|
+
const { variants, per, ...rest } = request;
|
|
335
|
+
if (variants !== undefined && !Array.isArray(variants)) return bad('`variants` must be an array of variant ids');
|
|
336
|
+
if (per !== undefined && !(typeof per === 'number' && Number.isFinite(per) && per > 0)) return bad('`per` must be a positive number (elements per iteration)');
|
|
337
|
+
const x = await whatIf((a, r) => w.analyze(a, r), arch, rest, variants ?? VARIANTS, { assemble: (text) => w.assemble(text, 'intel') });
|
|
338
|
+
return whatIfPerElement(x, per);
|
|
339
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wuica-cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.10",
|
|
4
4
|
"description": "x86-64 basic-block throughput prediction in WebAssembly: a bit-exact Rust/WebAssembly port of uiCA, as a library, a CLI and an MCP server",
|
|
5
5
|
"license": "AGPL-3.0-only",
|
|
6
6
|
"type": "module",
|
|
@@ -49,6 +49,8 @@
|
|
|
49
49
|
],
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"@modelcontextprotocol/sdk": "1.32.2",
|
|
52
|
+
"@types/node": "20.19.43",
|
|
53
|
+
"typescript": "7.0.2",
|
|
52
54
|
"zod": "4.6.7"
|
|
53
55
|
},
|
|
54
56
|
"repository": {
|
package/lib/insights.js
DELETED
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
// What the web page's bound view shows (web/js/bound.js), for the compact form (summarize(), the MCP `analyze` JSON):
|
|
2
|
-
// how busy each resource is as a share of the predicted cycles, the next limit after the bottleneck, the critical chain,
|
|
3
|
-
// and the instructions with the largest share of the binding resource. Derived from the response only (no analysis).
|
|
4
|
-
// tests-js/web_bound.mjs checks that it agrees with the page on the built-in examples.
|
|
5
|
-
|
|
6
|
-
import { caveats } from './web/caveats.js';
|
|
7
|
-
|
|
8
|
-
const FRONT = new Set(['MITE', 'MS', 'DSB', 'LSD']);
|
|
9
|
-
const COUNTS = new Set(['Issued', 'Exec.']);
|
|
10
|
-
const isPort = (c) => !FRONT.has(c) && !COUNTS.has(c);
|
|
11
|
-
const EPS = 0.005;
|
|
12
|
-
const SATURATED = 0.95;
|
|
13
|
-
const round = (x) => Math.round(x * 100) / 100;
|
|
14
|
-
|
|
15
|
-
const total = (r, i) => r.rows.reduce((s, x) => s + (Number(x.values?.[i]) || 0), 0);
|
|
16
|
-
|
|
17
|
-
// The weight of each row in a resource (as the page's blame()), or null.
|
|
18
|
-
function weights(r, id) {
|
|
19
|
-
const col = (name) => r.columns.indexOf(name);
|
|
20
|
-
const fromColumn = (i) => (i < 0 ? null : r.rows.map((x) => Number(x.values?.[i]) || 0));
|
|
21
|
-
if (id === 'Ports') {
|
|
22
|
-
const ports = r.columns.map((c, i) => ({ i, t: isPort(c) && c !== 'Div' ? total(r, i) : 0 })).filter((p) => p.t > 0);
|
|
23
|
-
if (!ports.length) return null;
|
|
24
|
-
const top = Math.max(...ports.map((p) => p.t));
|
|
25
|
-
const hot = ports.filter((p) => p.t >= SATURATED * top);
|
|
26
|
-
return { w: r.rows.map((x) => hot.reduce((s, p) => s + (Number(x.values?.[p.i]) || 0), 0)), ports: hot.map((p) => r.columns[p.i]) };
|
|
27
|
-
}
|
|
28
|
-
if (id === 'Issue') return { w: fromColumn(col('Issued')) };
|
|
29
|
-
if (FRONT.has(id)) return { w: fromColumn(col(id)) };
|
|
30
|
-
if (id === 'Decoder') {
|
|
31
|
-
const i = col('MITE');
|
|
32
|
-
if (i >= 0 && total(r, i) > 0) return { w: fromColumn(i) };
|
|
33
|
-
return { w: r.rows.map((x) => (x.kind === 'instr' && x.notes !== 'M' ? 1 : 0)) };
|
|
34
|
-
}
|
|
35
|
-
if (id === 'Predecoder') return { w: r.rows.map((x) => (x.kind === 'instr' ? String(x.opcode ?? '').length / 2 : 0)) };
|
|
36
|
-
if (id === 'Divider') return { w: fromColumn(col('Div')) };
|
|
37
|
-
if (id === 'Dependencies') {
|
|
38
|
-
const edges = r.criticalPath?.edges;
|
|
39
|
-
if (!Array.isArray(edges) || !edges.length) return null;
|
|
40
|
-
const w = r.rows.map(() => 0);
|
|
41
|
-
for (const e of edges) if (e.from >= 0 && e.from < w.length) w[e.from] += Number(e.latency) || 0;
|
|
42
|
-
return { w };
|
|
43
|
-
}
|
|
44
|
-
return null;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
// {utilization, binding, largest?, next?, unexplained?, chain?, hot?} or null.
|
|
48
|
-
// utilization: {limit or port column: cycles / tp} (1 = busy every cycle; above 1: uiCA's bound is above the simulation)
|
|
49
|
-
// binding: the bottleneck(s) uiCA names (the response's `bottlenecks`; [] when it names none: no single limit explains
|
|
50
|
-
// tp, the page says "unknown")
|
|
51
|
-
// largest: when uiCA names none, the largest limit(s): the nearest bound, which alone does not reach tp
|
|
52
|
-
// next: {limit, tp, maxSpeedup}: the largest limit below the binding one; tp / next.tp is an upper bound of the speedup
|
|
53
|
-
// unexplained: cycles per iteration that no single limit explains
|
|
54
|
-
// chain: the critical loop-carried chain: [{index, instr, operand, latency, carried}] (index into `instructions`)
|
|
55
|
-
// hot: {resource, ports?, instructions: [{index, instr, share}]}: the largest shares of the binding resource (top 5)
|
|
56
|
-
// caveats: [{id, text, title, instructions: [index]}]: known blind spots the block meets (web/js/caveats.js):
|
|
57
|
-
// rmw-index (store forwarding between iterations through an indexed address), exit (an exit's mispredict),
|
|
58
|
-
// split (loads that may cross a cache line; on a CPU whose model charges crossings, only the loads it cannot
|
|
59
|
-
// follow); absent if none
|
|
60
|
-
// config: the CPU's configuration in uarch.json (configs[r.arch]), for the caveats; without it, split warns as on a CPU
|
|
61
|
-
// without a split-load cost (the instance's insights() and summarize() pass it).
|
|
62
|
-
export function insights(r, config = null) {
|
|
63
|
-
const tp = Number(r?.tp);
|
|
64
|
-
if (!(tp > 0) || !Array.isArray(r.limits) || !Array.isArray(r.rows) || !Array.isArray(r.columns)) return null;
|
|
65
|
-
const utilization = {};
|
|
66
|
-
for (const l of r.limits) utilization[l.name] = round(l.tp / tp);
|
|
67
|
-
r.columns.forEach((c, i) => { if (isPort(c)) { const t = total(r, i); if (t > 0) utilization[c] = round(t / tp); } });
|
|
68
|
-
const limits = r.limits.map((l) => ({ name: l.name, tp: Number(l.tp) }));
|
|
69
|
-
const max = limits.length ? Math.max(...limits.map((l) => l.tp)) : 0;
|
|
70
|
-
// the cycles of a bottleneck: its limit; the divider (no limit of its own): the Div column
|
|
71
|
-
const divCol = r.columns.indexOf('Div');
|
|
72
|
-
const valueOf = (name) => limits.find((l) => l.name === name)?.tp ?? (name === 'Divider' && divCol >= 0 ? total(r, divCol) : 0);
|
|
73
|
-
const binding = [...(r.bottlenecks ?? [])];
|
|
74
|
-
const largest = binding.length ? [] : limits.filter((l) => l.tp >= max - EPS).map((l) => l.name);
|
|
75
|
-
const top = binding.length ? binding : largest;
|
|
76
|
-
const bindValue = Math.max(0, ...top.map(valueOf));
|
|
77
|
-
let next = null;
|
|
78
|
-
for (const l of limits) if (!top.includes(l.name) && l.tp < bindValue - EPS && (!next || l.tp > next.tp)) next = { limit: l.name, tp: l.tp };
|
|
79
|
-
const out = { utilization, binding };
|
|
80
|
-
if (largest.length) out.largest = largest;
|
|
81
|
-
if (next) out.next = { ...next, maxSpeedup: next.tp > 0 ? round(tp / next.tp) : null };
|
|
82
|
-
if (limits.length && tp - max > EPS) out.unexplained = round(tp - max);
|
|
83
|
-
const edges = r.criticalPath?.edges;
|
|
84
|
-
if (Array.isArray(edges) && edges.length) {
|
|
85
|
-
out.chain = edges.map((e) => ({ index: e.from, instr: r.rows[e.from]?.label, operand: String(e.operand).toLowerCase(), latency: e.latency, carried: !!e.carried }));
|
|
86
|
-
}
|
|
87
|
-
if (top[0]) {
|
|
88
|
-
const b = weights(r, top[0]);
|
|
89
|
-
const sum = b?.w?.reduce((s, x) => s + x, 0) ?? 0;
|
|
90
|
-
if (b?.w && sum > 0) {
|
|
91
|
-
const shares = b.w.map((x, index) => ({ index, share: x / sum })).filter((x) => x.share > 0)
|
|
92
|
-
.sort((a, c) => c.share - a.share || a.index - c.index).slice(0, 5)
|
|
93
|
-
.map((x) => ({ index: x.index, instr: r.rows[x.index].label, share: round(x.share) }));
|
|
94
|
-
out.hot = { resource: top[0], ...(b.ports ? { ports: b.ports } : {}), instructions: shares };
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
const cv = caveats(r, config);
|
|
98
|
-
if (cv.length) out.caveats = cv.map((c) => ({ id: c.id, text: c.text, title: c.title, instructions: c.rows }));
|
|
99
|
-
return out;
|
|
100
|
-
}
|
package/lib/whatif.js
DELETED
|
@@ -1,136 +0,0 @@
|
|
|
1
|
-
// The what-if experiments of the web page (web/js/whatif.js), for the MCP tool `what_if`: the block re-analyzed with one
|
|
2
|
-
// change each: unrolled ×2/×4/×8 (n copies of the body and the loop's branch once, per original iteration), N
|
|
3
|
-
// accumulators (unrolled ×N with the chain's register renamed in each copy: the page's accum.js, assembled), the front
|
|
4
|
-
// end limited only by the issue width, macro- or micro-fusion switched; and the estimate without the loop-carried chain
|
|
5
|
-
// (the largest other limit, no analysis). tests-js/web_whatif.mjs checks that the variants agree with the page's.
|
|
6
|
-
|
|
7
|
-
import { ACCUMULATORS, accumulatorText, bestAccumulators } from './web/accum.js';
|
|
8
|
-
|
|
9
|
-
export const VARIANTS = Object.freeze(['unroll2', 'unroll4', 'unroll8', 'acc2', 'acc3', 'acc4', 'acc8', 'simpleFrontEnd', 'noMacroFusion', 'noMicroFusion', 'nochain']);
|
|
10
|
-
const UNROLL = [2, 4, 8];
|
|
11
|
-
const FLAGS = [
|
|
12
|
-
['simpleFrontEnd', 'simple front end', 'detailed front end'],
|
|
13
|
-
['noMacroFusion', 'no macro-fusion', 'macro-fusion'],
|
|
14
|
-
['noMicroFusion', 'no micro-fusion', 'micro-fusion'],
|
|
15
|
-
];
|
|
16
|
-
|
|
17
|
-
// The instructions as byte ranges of the code, or null if the rows do not make up the code (undecodable bytes).
|
|
18
|
-
function instrRanges(response, hex) {
|
|
19
|
-
const out = [];
|
|
20
|
-
let at = 0;
|
|
21
|
-
for (const x of response?.rows ?? []) {
|
|
22
|
-
if (x.kind !== 'instr') continue;
|
|
23
|
-
const op = String(x.opcode ?? '').toLowerCase();
|
|
24
|
-
out.push({ start: at, op, fused: x.notes === 'M' });
|
|
25
|
-
at += op.length / 2;
|
|
26
|
-
}
|
|
27
|
-
return out.length && out.map((i) => i.op).join('') === String(hex ?? '').toLowerCase() ? out : null;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
// The loop unrolled n times (as the page): {ok, hex, tail} or {ok: false, reason}
|
|
31
|
-
export function unrollHex(response, hex, n) {
|
|
32
|
-
if (response?.mode !== 'loop') return { ok: false, reason: 'not a loop' };
|
|
33
|
-
const ins = instrRanges(response, hex);
|
|
34
|
-
if (!ins) return { ok: false, reason: 'the code has bytes that are not instructions' };
|
|
35
|
-
const last = ins.length - 1;
|
|
36
|
-
const tailFrom = ins[last].fused && last > 0 ? ins[last - 1].start : ins[last].start;
|
|
37
|
-
if (tailFrom === 0) return { ok: false, reason: 'nothing but the branch' };
|
|
38
|
-
const code = String(hex).toLowerCase();
|
|
39
|
-
return { ok: true, hex: code.slice(0, 2 * tailFrom).repeat(n) + code.slice(2 * tailFrom), tail: tailFrom === ins[last].start ? 1 : 2 };
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// The experiments for a response: [{id, label, per, hex, options} | {id: 'nochain', label, estimate, per}] (as the page's
|
|
43
|
-
// experiments()); options: the simulation options of the base analysis.
|
|
44
|
-
export function experiments(response, hex, options = {}) {
|
|
45
|
-
const out = [];
|
|
46
|
-
for (const n of UNROLL) {
|
|
47
|
-
const u = unrollHex(response, hex, n);
|
|
48
|
-
if (u.ok) out.push({ id: `unroll${n}`, label: `unroll ×${n}`, per: n, hex: u.hex, options });
|
|
49
|
-
}
|
|
50
|
-
if (response?.mode === 'loop' && response.criticalPath?.edges?.length) {
|
|
51
|
-
for (const n of ACCUMULATORS) {
|
|
52
|
-
const a = accumulatorText(response, hex, n);
|
|
53
|
-
if (!a.ok && n === ACCUMULATORS[0]) { out.push({ id: 'acc', label: 'accumulators', per: 1, error: a.reason, options }); break; }
|
|
54
|
-
if (!a.ok) { out.push({ id: `acc${n}`, label: `${n} accumulators`, per: n, error: a.reason, options }); continue; }
|
|
55
|
-
out.push({ id: `acc${n}`, label: `${n} accumulators`, per: n, text: a.text, options, renamed: a.renamed });
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
for (const [k, on, off] of FLAGS) {
|
|
59
|
-
const v = !options?.[k];
|
|
60
|
-
out.push({ id: k, label: v ? on : off, per: 1, hex: String(hex).toLowerCase(), options: { ...options, [k]: v } });
|
|
61
|
-
}
|
|
62
|
-
const lims = Array.isArray(response?.limits) ? response.limits : [];
|
|
63
|
-
const others = lims.filter((l) => l.name !== 'Dependencies').map((l) => Number(l.tp));
|
|
64
|
-
if (lims.some((l) => l.name === 'Dependencies') && others.length) out.push({ id: 'nochain', label: 'no chain', estimate: Math.max(...others), per: 1 });
|
|
65
|
-
return out;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
// The label of a variant as experiments() gives it (for the variants it does not make).
|
|
69
|
-
function labelOf(id, options) {
|
|
70
|
-
if (id.startsWith('unroll')) return `unroll ×${id.slice(6)}`;
|
|
71
|
-
if (id.startsWith('acc')) return `${id.slice(3)} accumulators`;
|
|
72
|
-
const f = FLAGS.find(([k]) => k === id);
|
|
73
|
-
return f ? (options?.[id] ? f[2] : f[1]) : 'no chain';
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
const round = (x) => Math.round(x * 100) / 100;
|
|
77
|
-
|
|
78
|
-
// What the tool returns for one experiment, from the base result and the variant's (or its estimate).
|
|
79
|
-
export function outcome(base, exp, r) {
|
|
80
|
-
const row = { id: exp.id, label: exp.label };
|
|
81
|
-
if (exp.renamed) row.renamed = exp.renamed;
|
|
82
|
-
let tp;
|
|
83
|
-
if (exp.error) return { ...row, error: exp.error };
|
|
84
|
-
if (exp.estimate !== undefined) { tp = exp.estimate; row.estimate = true; }
|
|
85
|
-
else if (!r || r.code !== 0) {
|
|
86
|
-
const error = r?.error ?? 'not analyzed';
|
|
87
|
-
// a limit or failure of the unrolled code, not of the caller's block: say so
|
|
88
|
-
return { ...row, error: exp.per > 1 && exp.hex ? `the block unrolled ×${exp.per} (${exp.hex.length} hex characters) could not be analyzed: ${error}` : error };
|
|
89
|
-
}
|
|
90
|
-
else if (r.mode !== base.mode) return { ...row, error: `analyzed ${r.mode === 'loop' ? 'as a loop' : 'unrolled'}: not comparable` };
|
|
91
|
-
else { tp = r.tp / exp.per; row.bottlenecks = r.bottlenecks; }
|
|
92
|
-
return { ...row, tp: round(tp), delta: round(tp - base.tp), speedup: tp > 0 ? round(base.tp / tp) : null };
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
// Runs the experiments with analyze(arch, {hex, options}) (one after another). request: as analyze's ({source | hex,
|
|
96
|
-
// syntax, loop, options}); variants: ids of VARIANTS (default: all); assemble(text) -> {code, hex} (the accumulator
|
|
97
|
-
// variants; Intel syntax). Resolves to {code: 0, arch, tp, mode, bottlenecks, loop?, variants: [{id, label, tp, delta,
|
|
98
|
-
// speedup, estimate?, bottlenecks?, renamed?, error?}], accumulators?: {best, tp}} or the base's failure.
|
|
99
|
-
// accumulators: the best number of accumulators (the smallest within 1% of the fastest, 1 = as it is) among those run.
|
|
100
|
-
export async function whatIf(analyze, arch, request, variants = VARIANTS, { assemble = null } = {}) {
|
|
101
|
-
const unknown = (variants ?? []).filter((v) => !VARIANTS.includes(v));
|
|
102
|
-
if (unknown.length) return { code: 1, error: `unknown variant(s): ${unknown.join(', ')} (known: ${VARIANTS.join(', ')})`, stderr: [] };
|
|
103
|
-
const base = await analyze(arch, request);
|
|
104
|
-
if (base.code !== 0) return base;
|
|
105
|
-
// the code as the rows have it (the analyzed bytes, if every byte was decoded), for the unrolled copies; the other
|
|
106
|
-
// variants analyze the caller's code as given (hex in any form the library accepts, or the assembled bytes)
|
|
107
|
-
const rowsHex = base.decodeErrors ? '' : base.rows.filter((x) => x.kind === 'instr').map((x) => String(x.opcode ?? '').toLowerCase()).join('');
|
|
108
|
-
const code = base.hex !== undefined ? { hex: base.hex } : { hex: request.hex };
|
|
109
|
-
const options = { ...(request.options ?? {}) };
|
|
110
|
-
const want = new Set(variants ?? VARIANTS);
|
|
111
|
-
const out = [];
|
|
112
|
-
// the alignment offset the base got from the code's addresses (objdump input) holds for the variants too
|
|
113
|
-
if (options.alignmentOffset === undefined && request.alignmentOffset === undefined && base.loop?.alignmentOffset !== undefined) options.alignmentOffset = base.loop.alignmentOffset;
|
|
114
|
-
const exps = experiments(base, rowsHex, options);
|
|
115
|
-
const accError = exps.find((x) => x.id === 'acc')?.error;
|
|
116
|
-
for (const exp of exps) {
|
|
117
|
-
if (!want.has(exp.id)) continue;
|
|
118
|
-
if (exp.text && !exp.hex) {
|
|
119
|
-
const a = assemble ? await assemble(exp.text) : null;
|
|
120
|
-
if (a?.code === 0 && a.hex) exp.hex = a.hex;
|
|
121
|
-
else { out.push(outcome(base, { ...exp, error: a ? `the variant does not assemble: ${a.error}` : 'no assembler' }, null)); continue; }
|
|
122
|
-
}
|
|
123
|
-
const r = exp.estimate !== undefined ? null : await analyze(base.arch, exp.per > 1 ? { hex: exp.hex, options: exp.options } : { ...code, options: exp.options });
|
|
124
|
-
out.push(outcome(base, exp, r));
|
|
125
|
-
}
|
|
126
|
-
for (const id of want) {
|
|
127
|
-
if (!out.some((x) => x.id === id)) {
|
|
128
|
-
out.push({ id, label: labelOf(id, options), error: base.mode !== 'loop' && (id.startsWith('unroll') || id.startsWith('acc')) ? 'not a loop' : id === 'nochain' || id.startsWith('acc') ? (id.startsWith('acc') && accError) || 'no loop-carried chain' : 'not applicable' });
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
out.sort((a, b) => VARIANTS.indexOf(a.id) - VARIANTS.indexOf(b.id));
|
|
132
|
-
const accs = out.filter((x) => x.id.startsWith('acc') && x.tp !== undefined);
|
|
133
|
-
const best = accs.length ? bestAccumulators(new Map([[1, base.tp], ...accs.map((x) => [Number(x.id.slice(3)), x.tp])])) : null;
|
|
134
|
-
return { code: 0, arch: base.arch, tp: base.tp, mode: base.mode, bottlenecks: base.bottlenecks, ...(base.loop ? { loop: base.loop } : {}), unit: 'cycles per original iteration', variants: out,
|
|
135
|
-
...(best ? { accumulators: { best: best.n, tp: round(best.tp) } } : {}) };
|
|
136
|
-
}
|