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.
@@ -0,0 +1,437 @@
1
+ // Results as text, without the DOM: Markdown (GitHub-flavoured) for an issue, a review or a chat; the uop table as CSV;
2
+ // the response as JSON. From the response and the shared models (bound-core.js, ab-diff.js), never from the page. One
3
+ // module for the page (its copy controls) and the npm package (`wuica -md`, the library's `markdown`): its copy in
4
+ // packages/wuica/lib/web (web-modules.json).
5
+ //
6
+ // The text: valid GFM; pipes and backticks in instruction text escaped; numbers as the page and the CLI print them
7
+ // (cycles with two decimals, three significant digits below 0.1 per element; the uop table's values as uiCA prints them,
8
+ // zeros blank); table columns padded so that the source reads in a monospace font; no trailing whitespace; the same
9
+ // input gives the same text.
10
+ //
11
+ // Generators: report (the whole result), uopTable, cpuTable (several CPUs, or files x CPUs), whatIf, loops, compare (A-B);
12
+ // the page's other views, each from that view's model: bound, bytes, deps, sweep, traceRange, mcaText. A new view: a
13
+ // generator here that takes its model and builds its text with the exported building blocks: table(head, rows, align),
14
+ // code(text), text(s), fence(text, lang), cycles(v), signedCycles(v), uopValue(v).
15
+
16
+ import { insights, boundModel, blame, topRows } from './bound-core.js';
17
+ import { compareResponses, cycles, signed, signedCycles, MINOR } from './ab-diff.js';
18
+ import { branchLabels, analyzedLines } from './branch-label.js';
19
+ import { shownOutcome } from './whatif-core.js';
20
+ import { cannotRun, noData, noDataText } from './caveats.js';
21
+
22
+ export { cycles, signedCycles };
23
+
24
+ // ---- building blocks ------------------------------------------------------------------------------------------------
25
+
26
+ // a value of the uop table as uiCA prints it: up to two decimals, zeros blank
27
+ export const uopValue = (v) => (typeof v === 'number' && Number.isFinite(v) && v !== 0 ? String(Math.round(v * 100) / 100) : '');
28
+ const f2 = (v) => Number(v).toFixed(2);
29
+
30
+ // text in a table cell or a line: pipes and backticks escaped
31
+ export const text = (s) => String(s ?? '').replace(/\\/g, '\\\\').replace(/\|/g, '\\|').replace(/`/g, '\\`').replace(/\s+/g, ' ').trim();
32
+
33
+ // a code span (instruction text): a pipe escaped (GFM tables split cells at an unescaped pipe, also in code spans); a
34
+ // backtick inside: the span is fenced with more backticks than any run in the text
35
+ export function code(s) {
36
+ const t = String(s ?? '').replace(/\s+/g, ' ').trim().replace(/\|/g, '\\|');
37
+ if (!t.includes('`')) return `\`${t}\``;
38
+ const run = Math.max(...(t.match(/`+/g) ?? ['']).map((x) => x.length));
39
+ const f = '`'.repeat(run + 1);
40
+ return `${f} ${t} ${f}`;
41
+ }
42
+
43
+ // a fenced code block: the fence longer than any run of backticks in the text
44
+ export function fence(body, lang = '') {
45
+ const run = Math.max(2, ...(String(body).match(/`+/g) ?? ['']).map((x) => x.length));
46
+ const f = '`'.repeat(run + 1);
47
+ return `${f}${lang}\n${String(body).replace(/\s+$/, '')}\n${f}`;
48
+ }
49
+
50
+ // A GFM table, its columns padded to their widest cell. head: [names]; rows: [[cells]] (strings); align: per column
51
+ // 'l' (default), 'r', 'c'.
52
+ export function table(head, rows, align = []) {
53
+ const n = head.length;
54
+ const width = head.map((h, i) => Math.max(3, [...String(h)].length, ...rows.map((r) => [...String(r[i] ?? '')].length)));
55
+ const pad = (s, i) => {
56
+ const t = String(s ?? ''), w = width[i] - [...t].length;
57
+ if (align[i] === 'r') return ' '.repeat(w) + t;
58
+ if (align[i] === 'c') return ' '.repeat(Math.floor(w / 2)) + t + ' '.repeat(Math.ceil(w / 2));
59
+ return t + ' '.repeat(w);
60
+ };
61
+ const line = (cells) => `| ${cells.map(pad).join(' | ')} |`.replace(/\s+$/, '');
62
+ const rule = `|${width.map((w, i) => (align[i] === 'r' ? `${'-'.repeat(w + 1)}:` : align[i] === 'c' ? `:${'-'.repeat(w)}:` : '-'.repeat(w + 2))).join('|')}|`;
63
+ return [line(head), rule, ...rows.map((r) => line(Array.from({ length: n }, (_, i) => r[i] ?? '')))].join('\n');
64
+ }
65
+
66
+ // a hard line break without trailing spaces (GFM: a backslash at the end of the line)
67
+ const BR = '\\\n';
68
+ const join = (blocks) => blocks.filter((b) => b !== null && b !== undefined && b !== '').join('\n\n') + '\n';
69
+
70
+ // Branch targets as the page shows them (branch-label.js): the label written in the text, a numeric label as written,
71
+ // the nearest label plus an offset, else the offset in the block ("jnz 0x0"), never the analyzer's 64-bit relative
72
+ // value. meta.shown: the labels per row (the page's view.shown); else meta.src ({text, from, to}: the analyzed lines of
73
+ // the assembly, branch-label.js analyzedLines); else meta.source (the assembly text of the request: its analyzed lines
74
+ // from the result's loop); else the block's offsets.
75
+ export function shownLabels(r, meta = {}) {
76
+ const rows = Array.isArray(r?.rows) ? r.rows : [];
77
+ const shown = Array.isArray(meta.shown) && meta.shown.length === rows.length ? meta.shown : branchLabels(rows, meta.src ?? (typeof meta.source === 'string' ? analyzedLines(meta.source, r) : null));
78
+ return rows.map((x, i) => String(shown[i] ?? x.label ?? ''));
79
+ }
80
+ const cell = (row, label) => (row.kind === 'instr' ? code(label) : text(label));
81
+
82
+ // ---- one result -----------------------------------------------------------------------------------------------------
83
+
84
+ // "Issue 3.50" (per element with `per`): the largest limit(s), the nearest bound when uiCA names no bottleneck
85
+ function nearest(r, per = 1) {
86
+ const lims = (r?.limits ?? []).map((l) => ({ name: l.name, tp: Number(l.tp) })).filter((l) => Number.isFinite(l.tp));
87
+ if (!lims.length) return '';
88
+ const max = Math.max(...lims.map((l) => l.tp));
89
+ return `${lims.filter((l) => l.tp >= max - 0.005).map((l) => l.name).join(', ')} ${per > 1 ? cycles(max / per) : f2(max)}`;
90
+ }
91
+
92
+ // Code the CPU cannot run (caveats.js cannotRun): the page's own (meta.invalid), the library's `unsupported` (its
93
+ // reason), or from the response; null if it can.
94
+ // meta: {invalid, arch, analyzed (the analyzed assembly text: names the extension)}
95
+ export function cannotRunOf(r, meta = {}) {
96
+ if (meta.invalid !== undefined) return meta.invalid;
97
+ if (typeof r?.unsupported === 'string') return { reason: r.unsupported };
98
+ return cannotRun(r, { arch: meta.arch ?? r?.arch ?? null, code: meta.analyzed ?? null });
99
+ }
100
+
101
+ // The headline: cycles per iteration (or per element), the CPU, loop or unrolled, the bottleneck. A CPU that cannot run
102
+ // the code: its number struck through (not a result), and why.
103
+ // meta: {arch, archTitle (the CPU's title: "SKL · Skylake (2015)"), per (elements per iteration), invalid}
104
+ export function headline(r, meta = {}) {
105
+ const per = meta.per > 1 ? meta.per : 1;
106
+ const tp = Number(r.tp);
107
+ const bad = cannotRunOf(r, meta);
108
+ const strike = (t) => (bad ? `~~${t}~~` : t);
109
+ const head = (per > 1 ? `**${strike(cycles(tp / per))} cycles/element** (${f2(tp)} cycles/iteration, ${per} elements per iteration)` : `**${strike(f2(tp))} cycles/iteration**`)
110
+ + (bad ? ` (not a result: ${text(bad.reason)})` : '');
111
+ const bn = r.bottlenecks?.length ? r.bottlenecks.join(', ') : `unknown${nearest(r, per) ? ` · nearest ${nearest(r, per)}` : ''}`;
112
+ return `${head} · ${text(meta.archTitle ?? meta.arch ?? r.arch)} · ${r.mode === 'loop' ? 'loop' : 'unrolled'}${bad ? '' : ` · bottleneck: ${bn}`}`;
113
+ }
114
+
115
+ // The uop table: every row (branch targets as shownLabels), the columns that are used, the totals.
116
+ // meta: {shown | src | source} (shownLabels)
117
+ export function uopTable(r, meta = {}) {
118
+ const labels = shownLabels(r, meta);
119
+ const cols = r.columns.map((_, i) => i).filter((i) => r.rows.some((x) => Number(x.values?.[i]) || 0));
120
+ const tot = cols.map((i) => r.rows.reduce((s, x) => s + (Number(x.values?.[i]) || 0), 0));
121
+ const rows = r.rows.map((x, k) => [cell(x, labels[k]), text(x.notes ?? ''), ...cols.map((i) => uopValue(Number(x.values?.[i])))]);
122
+ rows.push(['**Total**', '', ...tot.map(uopValue)]);
123
+ return table(['Instruction', 'Notes', ...cols.map((i) => text(r.columns[i]))], rows, ['l', 'c', ...cols.map(() => 'r')]);
124
+ }
125
+
126
+ // The whole result: the headline, the limits, the next limit, what the model does not simulate (caveats), the
127
+ // critical chain, the uop table, the code (if given), a link (if given). A failure: its error and stderr lines.
128
+ // meta: {arch, archTitle, per, insights (bound-core.js insights(r, config), e.g. the library's w.insights(r)) or config
129
+ // (the CPU's configuration in uarch.json, for the caveats), shown | src | source (shownLabels), code, lang, link,
130
+ // title (a heading)}
131
+ export function report(r, meta = {}) {
132
+ const blocks = [];
133
+ if (meta.title) blocks.push(`## ${text(meta.title)}`);
134
+ if (!r || r.error || r.code || !Array.isArray(r.rows)) {
135
+ blocks.push(`**analysis failed:** ${text(r?.error ?? 'no result')}`);
136
+ const lines = (r?.stderr ?? []).map((l) => String(l.text ?? l)).filter((l) => l !== String(r?.error));
137
+ if (lines.length) blocks.push(fence(lines.join('\n')));
138
+ if (meta.code) blocks.push(fence(meta.code, meta.lang ?? 'asm'));
139
+ if (meta.link) blocks.push(`[open in wuica](${meta.link})`);
140
+ return join(blocks);
141
+ }
142
+ const per = meta.per > 1 ? meta.per : 1;
143
+ // a result its CPU cannot run: the headline with the reason, none of the diagnosis (limits, next limit, caveats,
144
+ // chain) of rows that are not that code
145
+ const bad = cannotRunOf(r, meta);
146
+ const ins = bad ? null : meta.insights ?? insights(r, meta.config ?? null);
147
+ const labels = shownLabels(r, meta);
148
+ const lines = [headline(r, meta)];
149
+ if (r.limits?.length && !bad) lines.push(`limits: ${r.limits.map((l) => `${l.name} ${per > 1 ? cycles(Number(l.tp) / per) : f2(l.tp)}`).join(' · ')}`);
150
+ if (ins?.next && ins.binding.length) lines.push(`next limit: ${ins.next.limit} ${per > 1 ? cycles(ins.next.tp / per) : f2(ins.next.tp)} (at most ${f2(ins.next.maxSpeedup)}x faster without ${ins.binding.join(', ')})`);
151
+ if (r.decodeErrors > 0) lines.push(`${r.decodeErrors} position(s) could not be decoded: the throughput leaves them out`);
152
+ { const n = meta.noData ?? r.noData ?? noData(r, { arch: meta.arch ?? r.arch ?? null }); if (n > 0) lines.push(`${noDataText(n)}: not in the instruction tables, their cost is left out`); }
153
+ blocks.push(lines.join(BR));
154
+ if (ins?.caveats?.length) blocks.push(ins.caveats.map((c) => `- **not modelled:** ${text(c.text)}: ${text(c.title)}`).join('\n'));
155
+ if (ins?.chain?.length) {
156
+ const lat = ins.chain.reduce((s, e) => s + (Number(e.latency) || 0), 0);
157
+ blocks.push(`critical chain (${lat} cycle${lat === 1 ? '' : 's'} of latency): ${ins.chain.map((e) => `${code(labels[e.index] ?? e.instr)} (${text(e.operand)}, ${e.latency})`).join(' → ')}`);
158
+ }
159
+ blocks.push(uopTable(r, { shown: labels }));
160
+ if (meta.code) blocks.push(fence(meta.code, meta.lang ?? 'asm'));
161
+ if (meta.link) blocks.push(`[open in wuica](${meta.link})`);
162
+ return join(blocks);
163
+ }
164
+
165
+ // ---- several CPUs, several files ----------------------------------------------------------------------------------
166
+
167
+ // The rows of a CPU table: from a compare() result ({results}), an analyze result (one CPU), or a failure.
168
+ function cpuRows(x) {
169
+ if (Array.isArray(x?.results)) return x.results;
170
+ if (x && !x.code && x.tp !== undefined) return [x];
171
+ return [{ arch: '', name: '', code: x?.code ?? 1, error: x?.error ?? 'no result' }];
172
+ }
173
+
174
+ // Several CPUs, one row each: CPU, model, TP (and per element), bottlenecks (or "- (nearest X)"), notes (undecodable
175
+ // instructions, caveats, prototype). The batch form: files x CPUs (items {file, loop?, result}).
176
+ // input: a compare() result, an array of its rows, or [{file, result}] (each result a compare() or analyze result)
177
+ // opts: {per (elements per iteration)}
178
+ // A row's caveats: its `caveats` ([{text}] or ids) as the CLI's -json gives them.
179
+ export function cpuTable(input, opts = {}) {
180
+ const per = opts.per > 1 ? opts.per : null;
181
+ const batch = Array.isArray(input) && input.some((x) => x && 'file' in x);
182
+ const items = batch ? input : [{ result: Array.isArray(input) ? { results: input } : input }];
183
+ const loopOf = (r) => (r?.loop ? `${r.loop.name.replace(/^loop /, '')}${r.loop.function ? ` (${r.loop.function})` : ''}` : r && !r.code ? 'as is' : '-');
184
+ const rows = [];
185
+ let prototype = false, invalid = false;
186
+ for (const it of items) {
187
+ cpuRows(it.result).forEach((r, k) => {
188
+ const lead = batch ? [k ? '' : text(it.file), k ? '' : text(loopOf(it.result))] : [];
189
+ if (r.code) { rows.push([...lead, text(r.arch ?? ''), text(r.name ?? ''), String(r.year ?? ''), '-', ...(per ? ['-'] : []), `error: ${text(String(r.error).split('\n')[0])}`, '']); return; }
190
+ // a CPU that cannot run the code (caveats.js cannotRun): its number struck through, and why (no bottleneck, no caveats)
191
+ const bad = cannotRunOf(r, {});
192
+ const bn = bad ? '-' : r.bottlenecks?.length ? r.bottlenecks.join(', ') : nearest(r) ? `- (nearest ${nearest(r).replace(/ [\d.]+$/, '')})` : '-';
193
+ const cav = bad ? [] : (r.caveats ?? r.insights?.caveats ?? []).map((c) => (typeof c === 'string' ? c : c.text));
194
+ prototype ||= !!r.prototype;
195
+ invalid ||= !!bad;
196
+ const gaps = bad ? 0 : Number(r.noData) || 0;
197
+ const notes = [bad ? `not a result: ${bad.reason}` : null, r.decodeErrors ? `${r.decodeErrors} undecodable (left out)` : null, gaps ? `${noDataText(gaps)} (cost left out)` : null, ...cav, r.prototype ? '[prototype]' : null].filter(Boolean).map(text).join('; ');
198
+ const strike = (t) => (bad ? `~~${t}~~` : t);
199
+ rows.push([...lead, text(r.arch), text(r.name ?? ''), String(r.year ?? ''), `${strike(f2(r.tp))}${r.decodeErrors ? '*' : ''}`, ...(per ? [strike(cycles(Number(r.tp) / per))] : []), text(bn), notes]);
200
+ });
201
+ }
202
+ const head = [...(batch ? ['File', 'Loop'] : []), 'CPU', 'Model', 'Year', 'TP', ...(per ? ['per el'] : []), 'Bottlenecks', 'Notes'];
203
+ const align = [...(batch ? ['l', 'l'] : []), 'l', 'l', 'l', 'r', ...(per ? ['r'] : []), 'l', 'l'];
204
+ const notes = [`TP: cycles per iteration${per ? `; per el: cycles per element (${per} per iteration)` : ''}. "-": unknown or failed.`];
205
+ if (rows.some((r) => /\*$/.test(r[batch ? 5 : 3]))) notes.push('*: some instructions could not be decoded for that CPU and are left out.');
206
+ if (invalid) notes.push('~~TP~~: not a result: the CPU cannot run some of the code (its number leaves it out).');
207
+ if (prototype) notes.push('[prototype]: experimental model of the fork jtl06/uiCA.');
208
+ return join([table(head, rows, align), notes.join(BR)]);
209
+ }
210
+
211
+ // ---- what if, loops -------------------------------------------------------------------------------------------------
212
+
213
+ // The what-if table of one CPU (the library's whatIf result; with elementsPerIteration, per element): variant, cycles,
214
+ // delta, speedup; the best number of accumulators.
215
+ export function whatIf(x) {
216
+ if (x?.code) return `**What if (${text(x.arch ?? '')}):** ${text(x.error)}\n`;
217
+ if (x?.unsupported) return `**What if (${text(x.arch)}):** not a result: ${text(x.unsupported)} (the base ~~${f2(x.tp)}~~ leaves out what the CPU cannot run): no variants\n`;
218
+ const per = x.elementsPerIteration > 0 ? x.elementsPerIteration : null;
219
+ const v = (n) => (per ? cycles(n / per) : f2(n));
220
+ // (a variant within sampling of its Ports or Issue limit at the limit, ≈: whatif-core.js shownOutcome)
221
+ const rows = x.variants.map((y) => { if (y.error) return [text(y.label), '-', '', '', text(y.error)];
222
+ const s = shownOutcome(y, x.tp);
223
+ return [text(y.label), `${y.estimate ? '>=' : y.approx ? '≈' : ''}${v(s.tp)}`, `${s.delta > 0 ? '+' : ''}${v(s.delta)}`, `${f2(s.speedup ?? 0)}x`,
224
+ y.estimate ? 'estimate' : y.approx ? `at its ${text(y.approx.limit)} limit (simulated ${per ? Number(y.tp / per).toPrecision(3) : f2(y.tp)})` : '']; });
225
+ const head = `**What if (${text(x.arch)})**, ${per ? `cycles per element (${per} per original iteration; base ${cycles(x.tp / per)})` : `cycles per original iteration (base ${f2(x.tp)})`}`;
226
+ const best = x.accumulators ? `best number of accumulators: ${x.accumulators.best}${x.accumulators.best === 1 ? ' (as it is)' : ''}` : null;
227
+ return join([head, table(['Variant', 'Cycles', 'Δ', 'Speedup', 'Note'], rows, ['l', 'r', 'r', 'r', 'l']), best]);
228
+ }
229
+
230
+ // The loops of assembly text (listLoops / the CLI's -loops): index, label, function, lines, instructions, depth, the
231
+ // loop "auto" picks.
232
+ export function loops(list) {
233
+ if (!list?.length) return 'no loops\n';
234
+ const rows = list.map((l) => [String(l.index), code(l.label), text(l.function ?? '-'), `${l.line}-${l.endLine}`, String(l.instructions), String(l.depth), l.auto ? 'auto' : '']);
235
+ return join([table(['#', 'Label', 'Function', 'Lines', 'Instructions', 'Depth', 'Pick'], rows, ['r', 'l', 'l', 'l', 'r', 'r', 'l'])]);
236
+ }
237
+
238
+ // ---- A-B ----------------------------------------------------------------------------------------------------------
239
+
240
+ const percent = (p) => (p === null || !Number.isFinite(p) ? '' : `${p < 0 ? '−' : '+'}${Math.abs(p) < 10 ? Math.abs(p).toFixed(1) : String(Math.round(Math.abs(p)))}%`);
241
+ // the page's marks (ab.js): • same instruction, other uops; ~ changed operands; + only in B; − only in A
242
+ const MARK = { same: '', changed: '•', modified: '~', added: '+', removed: '−' };
243
+ const MARK_TEXT = { changed: 'same instruction, other uops', modified: 'changed operands', added: 'only in B', removed: 'only in A' };
244
+
245
+ // Two results, A and B (ab-diff.js, as the page compares them): the summary line, the bottlenecks, the limits, and the
246
+ // instructions aligned with the change (B − A) of every shared column; with meta.cpus ([{arch, a, b}]: the throughputs of
247
+ // both sides per CPU) the A/B/Δ table per CPU.
248
+ // meta: {workA, workB (elements per iteration of each side), archA, archB, cpus, shownA | srcA, shownB | srcB
249
+ // (each side's branch labels, shownLabels)}
250
+ export function compare(a, b, meta = {}) {
251
+ const cmp = compareResponses(a, b, { workA: meta.workA ?? 1, workB: meta.workB ?? null });
252
+ const unit = cmp.perElement ? 'cycles per element' : 'cycles per iteration';
253
+ const blocks = [];
254
+ if (!cmp.tp) {
255
+ blocks.push(`**A–B:** one side has no result${a?.error ? ` (A: ${text(a.error)})` : ''}${b?.error ? ` (B: ${text(b.error)})` : ''}`);
256
+ return join(blocks);
257
+ }
258
+ const t = cmp.tp;
259
+ const sides = meta.archA || meta.archB ? ` (A: ${text(meta.archA ?? a.arch)}, B: ${text(meta.archB ?? b.arch)})` : '';
260
+ // a side whose CPU cannot run its code (caveats.js cannotRun): its number struck through, no Δ (not comparable)
261
+ const badA = cannotRunOf(a, { invalid: meta.invalidA, arch: meta.archA ?? a.arch }), badB = cannotRunOf(b, { invalid: meta.invalidB, arch: meta.archB ?? b.arch });
262
+ const bad = [['A', badA, meta.archA ?? a.arch], ['B', badB, meta.archB ?? b.arch]].filter(([, x]) => x);
263
+ const strike = (x, v) => (x ? `~~${cycles(v)}~~` : cycles(v));
264
+ const lines = [`**A ${strike(badA, t.a)} · B ${strike(badB, t.b)} ${unit}**${bad.length ? ` (not comparable: ${bad.map(([k, x, arch]) => `${k} ${text(x.reason)}${arch ? ` on ${text(arch)}` : ''}`).join(', ')})` : t.verdict === 'same' ? ' (the same)' : ` (Δ ${t.delta === 0 ? '0' : signedCycles(t.delta)}, ${percent(t.pct)})`}${sides}`];
265
+ const bn = cmp.bottlenecks;
266
+ const names = (xs) => (xs.length ? xs.join(', ') : 'unknown');
267
+ lines.push(bn.same && bn.a.length ? `bottleneck: ${bn.a.join(', ')} (both)` : `bottleneck: A ${names(bn.a)} → B ${names(bn.b)}`);
268
+ blocks.push(lines.join(BR));
269
+ if (cmp.limits.length) {
270
+ blocks.push(table(['Limit', 'A', 'B', 'Δ'], cmp.limits.map((l) => [`${text(l.name)}${l.bottleneckA || l.bottleneckB ? ' *' : ''}`, l.a === null ? '-' : cycles(l.a), l.b === null ? '-' : cycles(l.b), l.delta === null ? '' : l.delta === 0 ? '' : signedCycles(l.delta)]), ['l', 'r', 'r', 'r']));
271
+ }
272
+ const d = cmp.diff;
273
+ if (d?.rows?.length) {
274
+ const shown = new Map();
275
+ for (const [r, sh, src] of [[a, meta.shownA, meta.srcA], [b, meta.shownB, meta.srcB]]) shownLabels(r, { shown: sh, src }).forEach((l, i) => shown.set(r.rows[i], l));
276
+ const label = (u) => (u ? cell(u.row, shown.get(u.row) ?? u.label) : '');
277
+ // (a minor change of uops, ab-diff.js MINOR: as the same instruction; a total that changes by less: no change)
278
+ const rows = d.rows.map((x) => (x.minor ? ['', label(x.a), label(x.b), ...x.deltas.map(() => '')] : [MARK[x.status], label(x.a), label(x.b), ...x.deltas.map((v) => signed(v))]));
279
+ rows.push(['', '**Total**', '', ...d.totals.map((v) => (Math.abs(v) < MINOR ? '' : signed(v)))]);
280
+ blocks.push(table(['', 'A', 'B', ...d.columns.map((c) => (c.name === 'Issued' ? 'Δ uops' : `Δ ${text(c.name)}`))], rows, ['c', 'l', 'l', ...d.columns.map(() => 'r')]));
281
+ const minor = d.rows.filter((x) => x.minor).length;
282
+ const used = Object.keys(MARK_TEXT).filter((k) => d.counts[k] - (k === 'changed' ? minor : 0) > 0);
283
+ const legend = [used.length ? used.map((k) => `${MARK[k]} ${MARK_TEXT[k]}`).join(' · ') : 'no change', 'Δ: B − A, uops per iteration'];
284
+ if (minor) legend.push(`changes under ${MINOR} uops not shown (${minor} instruction${minor === 1 ? '' : 's'})`);
285
+ if (!d.portsComparable) legend.push('the two sides have different execution ports: uop counts only');
286
+ blocks.push(legend.join('; '));
287
+ }
288
+ if (meta.cpus?.length) {
289
+ // (a side its CPU cannot run, unsupportedA/B: struck through, no Δ)
290
+ blocks.push(table(['CPU', 'A', 'B', 'Δ', '%'], meta.cpus.map((c) => {
291
+ const okA = Number.isFinite(c.a), okB = Number.isFinite(c.b);
292
+ const no = c.unsupportedA || c.unsupportedB;
293
+ const dd = okA && okB && !no ? c.b - c.a : null;
294
+ const v = (x, why) => (Number.isFinite(x) ? (why ? `~~${cycles(x)}~~` : cycles(x)) : '-');
295
+ return [text(c.arch), v(c.a, c.unsupportedA), v(c.b, c.unsupportedB), no ? text([c.unsupportedA ? `A ${c.unsupportedA}` : '', c.unsupportedB ? `B ${c.unsupportedB}` : ''].filter(Boolean).join(', ')) : dd === null ? '' : Math.abs(dd) < 0.005 ? '0' : signedCycles(dd), dd === null || !(c.a > 0) ? '' : percent((100 * dd) / c.a)];
296
+ }), ['l', 'r', 'r', 'r', 'r']));
297
+ }
298
+ return join(blocks);
299
+ }
300
+
301
+ // ---- the page's other views: bound, bytes, deps, the sweep, a trace range, llvm-mca --------------------------------
302
+
303
+ /** @param {number} u */
304
+ const pct = (u) => `${Math.round(u * 100)}%`;
305
+
306
+ // The bound view (bound-core.js): how busy each resource is, the binding one, the next limit; the instructions with the
307
+ // largest share of the selected resource (an item's id, as the view's; default: the binding one). meta: the branch
308
+ // labels as the page shows them (shownLabels: {shown | src | source}); side: 'A' or 'B' in A–B (whose block it is).
309
+ /** @param {any} r a response (as analyze returns it) @param {string | null} [selected] @param {any} [meta] */
310
+ export function bound(r, selected = null, meta = {}) {
311
+ const m = boundModel(r);
312
+ if (!m) return '';
313
+ const sel = selected ?? m.binding[0] ?? null;
314
+ const it = m.items.find((x) => x.id === sel);
315
+ const name = (id) => m.items.find((x) => x.id === id)?.name ?? id;
316
+ const head = `**bound**${meta.side ? ` (${text(meta.side)})` : ''} · ${f2(m.tp)} cycles/iteration · binding ${m.binding.length ? m.binding.map(name).join(', ') : 'none'}`
317
+ + (m.next ? ` · next ${m.next.name} ${f2(m.next.tp)} (at most ${f2(m.next.speedup)}x faster)` : '');
318
+ const rows = m.items.map((x) => [text(x.name), x.group, f2(x.cycles), pct(x.util), m.binding.includes(x.id) ? 'yes' : '']);
319
+ const b = sel ? blame(r, sel) : null;
320
+ const top = topRows(b, 5);
321
+ const labels = shownLabels(r, meta);
322
+ const shares = b && top.length ? `top of ${text(it?.name ?? sel)} (by ${b.unit}):\n\n${table(['Instruction', 'Share'], top.map(({ row, share }) => [code(labels[row] ?? r.rows[row].label), pct(share)]), ['l', 'r'])}` : null;
323
+ return join([head, table(['Resource', 'Group', 'Cycles/iteration', 'Busy', 'Binding'], rows, ['l', 'l', 'r', 'r', 'c']), shares]);
324
+ }
325
+
326
+ // The bytes view: each instruction's place on the cache lines at the alignment offset (the page's codemap.js
327
+ // codeMapModel: {bytes, offset, instrs: [{row, label, start, end, fused, jcc, cross16, cross32, cross64}], counts}).
328
+ // shown: the label of each row of the response as the page shows it (branch targets: shownLabels), or null.
329
+ /**
330
+ * @param {{bytes: number, offset: number, counts: {cross16: number, cross32: number, cross64: number},
331
+ * instrs: {row?: number, label: string, start: number, end: number, fused?: boolean, jcc?: boolean, cross16?: boolean, cross32?: boolean, cross64?: boolean}[]} | null} m
332
+ * @param {{shown?: string[] | null}} [opts]
333
+ */
334
+ export function bytes(m, { shown = null } = {}) {
335
+ if (!m) return '';
336
+ const label = (/** @type {{row?: number, label: string}} */ x) => (shown && x.row !== undefined ? shown[x.row] ?? x.label : x.label);
337
+ const head = `**bytes** · ${m.bytes} bytes from offset ${m.offset} · crossing 16 B: ${m.counts.cross16}, 32 B: ${m.counts.cross32}, 64 B: ${m.counts.cross64}`;
338
+ const rows = m.instrs.map((x) => [code(label(x)), `0x${x.start.toString(16)}`, String(x.end - x.start),
339
+ [x.cross16 ? '16' : '', x.cross32 ? '32' : '', x.cross64 ? '64' : ''].filter(Boolean).join(' '), [x.fused ? 'fused' : '', x.jcc ? 'JCC' : ''].filter(Boolean).join(' ')]);
340
+ return join([head, table(['Instruction', 'Start', 'Bytes', 'Crosses', 'Notes'], rows, ['l', 'r', 'r', 'l', 'l'])]);
341
+ }
342
+
343
+ // The deps view: its arcs (producer → consumer, the iterations between them, the latency, the critical chain) and the
344
+ // slack of each instruction (the page's deps.js depGraph: {nodes: [{label}], edges: [{a, b, dist, lat, mem, critical}],
345
+ // slack: {period}}). slack: the slack of each node as the view writes it (deps-slack.js fmtSlack), or null; shown: the
346
+ // label of each row of the response as the page shows it (shownLabels), or null.
347
+ /**
348
+ * @param {{nodes: {row?: number, label: string}[], edges: {a: number, b: number, dist: number, lat?: number | null, mem?: boolean, critical?: boolean}[],
349
+ * slack?: {period: number} | null} | null} g
350
+ * @param {{slack?: string[] | null, shown?: string[] | null}} [opts]
351
+ */
352
+ export function deps(g, { slack = null, shown = null } = {}) {
353
+ if (!g) return '';
354
+ const label = (/** @type {{row?: number, label: string}} */ n) => (shown && n.row !== undefined ? shown[n.row] ?? n.label : n.label);
355
+ const carried = g.edges.filter((e) => e.dist).length;
356
+ const head = `**deps** · ${g.edges.length} arcs, ${carried} carried into a later iteration${g.slack ? ` · chain ${+Number(g.slack.period).toFixed(2)} cycles/iteration` : ''}`;
357
+ const lat = (e) => (e.lat === null || e.lat === undefined ? '' : String(+Number(e.lat).toFixed(2)));
358
+ const arcs = table(['From', 'To', 'Iterations', 'Latency', 'Chain'],
359
+ g.edges.map((e) => [code(label(g.nodes[e.a])), code(label(g.nodes[e.b])), String(e.dist), lat(e) + (e.mem ? ' (memory)' : ''), e.critical ? 'yes' : '']), ['l', 'l', 'r', 'r', 'c']);
360
+ const sl = slack ? table(['Instruction', 'Slack'], g.nodes.map((n, i) => [code(label(n)), text(slack[i])]), ['l', 'r']) : null;
361
+ return join([head, arcs, sl]);
362
+ }
363
+
364
+ // Offsets (ascending integers) with runs of three or more as ranges: [0..7, 9, 10, 32..39] -> "0–7, 9, 10, 32–39".
365
+ /** @param {number[]} list */
366
+ export function offsetRanges(list) {
367
+ const out = [];
368
+ for (let i = 0; i < list.length;) {
369
+ let j = i;
370
+ while (j + 1 < list.length && list[j + 1] === list[j] + 1) j++;
371
+ if (j - i >= 2) out.push(`${list[i]}–${list[j]}`); else for (let k = i; k <= j; k++) out.push(String(list[k]));
372
+ i = j + 1;
373
+ }
374
+ return out.join(', ');
375
+ }
376
+
377
+ // The sweep: cycles/iteration at each alignment offset (the page's compare.js sweepData: {n, values (null: none),
378
+ // failed, pending, complete, min, max, minAt, maxAt, flat}).
379
+ /**
380
+ * @param {{n: number, values: (number | null)[], failed: number[], pending: number, complete: boolean, min: number | null,
381
+ * max: number | null, minAt: number[], maxAt: number[], flat?: boolean} | null} d
382
+ * @param {string} [arch]
383
+ */
384
+ export function sweep(d, arch = '') {
385
+ if (!d) return '';
386
+ // (as the page says it: one value at every offset, else the minimum and the maximum with their offsets as ranges)
387
+ const spread = d.min === null ? '' : d.flat && d.complete ? ` · ${f2(d.min)} cycles/iteration at every offset`
388
+ : ` · min ${f2(d.min)} at ${offsetRanges(d.minAt)} · max ${f2(d.max)} at ${offsetRanges(d.maxAt)}`;
389
+ const head = `**sweep** · alignment 0–${d.n - 1}${arch ? ` · ${text(arch)}` : ''}${spread}${d.complete ? '' : ` · ${d.pending} pending`}`;
390
+ return join([head, table(['Offset', 'Cycles/iteration'], d.values.map((v, i) => [String(i), v === null ? (d.failed.includes(i) ? 'failed' : '') : f2(v)]), ['r', 'r'])]);
391
+ }
392
+
393
+ // A trace range: the shown rows of the trace view as a table (the page's trace.js TABLE_HEAD and tableRows); caption:
394
+ // what is shown.
395
+ /** @param {string[]} head @param {string[][]} rows @param {string} [caption] */
396
+ export function traceRange(head, rows, caption = '') {
397
+ if (!rows?.length) return '';
398
+ return join([caption ? `**trace** · ${text(caption)}` : '**trace**', table(head.map(text), rows.map((r) => r.map(text)), head.map((_, i) => (i === 1 || i === 2 || i === head.length - 1 ? 'l' : 'r')))]);
399
+ }
400
+
401
+ // llvm-mca's text, as it printed it
402
+ /** @param {string} out @param {string} [caption] */
403
+ export function mcaText(out, caption = '') {
404
+ if (!out) return '';
405
+ return join([caption ? `**llvm-mca** · ${text(caption)}` : '**llvm-mca**', fence(out)]);
406
+ }
407
+
408
+ // ---- CSV, JSON ------------------------------------------------------------------------------------------------------
409
+
410
+ // CSV (RFC 4180): instruction, opcode, notes and every column of the uop table; numbers as the analyzer gives them.
411
+ export function toCSV(r) {
412
+ const q = (s) => (/[",\n\r]/.test(String(s)) ? `"${String(s).replace(/"/g, '""')}"` : String(s));
413
+ const out = [['instruction', 'opcode', 'notes', ...r.columns].map(q).join(',')];
414
+ for (const x of r.rows) out.push([x.label, x.opcode ?? '', x.notes ?? '', ...r.columns.map((_, i) => String(Number(x.values?.[i]) || 0))].map(q).join(','));
415
+ return out.join('\r\n') + '\r\n';
416
+ }
417
+
418
+ // JSON: the request and the response (without the trace and the text report, which the page has elsewhere).
419
+ export function toJSON(r, request) {
420
+ const { trace, text: report_, ...rest } = r;
421
+ return JSON.stringify({ request: request ?? null, response: rest }, null, 1) + '\n';
422
+ }
423
+
424
+ // ---- the alignment variant of what-if (appended) ----------------------------------------------------------------------
425
+
426
+ // whatIf's table and, when the result has the variant align, its alignment over the 64 offsets (min, median, max, the
427
+ // best and the worst offset, the spread); the base's warnings (decode errors) as a list.
428
+ export function whatIfAlignment(x) {
429
+ const md = whatIf(x);
430
+ const warn = (x?.stderr ?? []).map((l) => `- ${text(l.text)}`).join('\n');
431
+ const v = x?.variants?.find((y) => y.alignment);
432
+ if (!v) return md + (warn ? `\n${warn}\n` : '');
433
+ const per = x.elementsPerIteration > 0 ? x.elementsPerIteration : null;
434
+ const c = (n) => (per ? cycles(n / per) : Number(n).toFixed(2));
435
+ const a = v.alignment;
436
+ return md + `\n**Alignment** over the 64 offsets${per ? ' (cycles per element)' : ''}: min ${c(a.min)} (offset ${a.best}), median ${c(a.median)}, max ${c(a.max)} (offset ${a.worst}), spread ${c(a.spread)}; this block at offset ${a.offset}\n` + (warn ? `\n${warn}\n` : '');
437
+ }