wuica-cli 0.1.7 → 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.
Files changed (64) hide show
  1. package/README.md +233 -57
  2. package/dist/data/arch/ADL-P.bin.br +0 -0
  3. package/dist/data/arch/BDW.bin.br +0 -0
  4. package/dist/data/arch/CFL.bin.br +0 -0
  5. package/dist/data/arch/CLX.bin.br +0 -0
  6. package/dist/data/arch/HSW.bin.br +0 -0
  7. package/dist/data/arch/ICL.bin.br +0 -0
  8. package/dist/data/arch/ICX.bin.br +0 -0
  9. package/dist/data/arch/IVB.bin.br +0 -0
  10. package/dist/data/arch/KBL.bin.br +0 -0
  11. package/dist/data/arch/RKL.bin.br +0 -0
  12. package/dist/data/arch/SKL.bin.br +0 -0
  13. package/dist/data/arch/SKX.bin.br +0 -0
  14. package/dist/data/arch/SNB.bin.br +0 -0
  15. package/dist/data/arch/TGL.bin.br +0 -0
  16. package/dist/data/arch/ZEN3.bin.br +0 -0
  17. package/dist/data/uarch.json.br +0 -0
  18. package/dist/manifest.json +145 -66
  19. package/dist/wuica_wasm.wasm.br +0 -0
  20. package/index.d.ts +205 -13
  21. package/lib/cli.js +467 -49
  22. package/lib/core.js +9 -1
  23. package/lib/details.js +4 -23
  24. package/lib/examples.js +27 -0
  25. package/lib/files.js +26 -3
  26. package/lib/index.js +228 -42
  27. package/lib/mcp.js +107 -84
  28. package/lib/objfile.js +218 -0
  29. package/lib/thread-worker.js +15 -9
  30. package/lib/threads.js +40 -23
  31. package/lib/wasm.js +42 -11
  32. package/lib/web/ab-diff.js +217 -0
  33. package/lib/web/accum.js +10 -2
  34. package/lib/web/asm-regions.js +24 -17
  35. package/lib/web/asm-tokens.js +357 -0
  36. package/lib/web/assembler.js +36 -6
  37. package/lib/web/block-diff.js +165 -0
  38. package/lib/web/bound-core.js +211 -0
  39. package/lib/web/branch-label.js +155 -0
  40. package/lib/web/caveats.js +115 -3
  41. package/lib/web/details.js +91 -0
  42. package/lib/web/examples.js +103 -0
  43. package/lib/web/loop-find.js +139 -16
  44. package/lib/web/markdown.js +437 -0
  45. package/lib/web/showcase.js +368 -0
  46. package/lib/web/whatif-core.js +339 -0
  47. package/package.json +3 -1
  48. package/dist/data/arch/ADL-P.json.br +0 -0
  49. package/dist/data/arch/BDW.json.br +0 -0
  50. package/dist/data/arch/CFL.json.br +0 -0
  51. package/dist/data/arch/CLX.json.br +0 -0
  52. package/dist/data/arch/HSW.json.br +0 -0
  53. package/dist/data/arch/ICL.json.br +0 -0
  54. package/dist/data/arch/ICX.json.br +0 -0
  55. package/dist/data/arch/IVB.json.br +0 -0
  56. package/dist/data/arch/KBL.json.br +0 -0
  57. package/dist/data/arch/RKL.json.br +0 -0
  58. package/dist/data/arch/SKL.json.br +0 -0
  59. package/dist/data/arch/SKX.json.br +0 -0
  60. package/dist/data/arch/SNB.json.br +0 -0
  61. package/dist/data/arch/TGL.json.br +0 -0
  62. package/dist/data/arch/ZEN3.json.br +0 -0
  63. package/lib/insights.js +0 -100
  64. package/lib/whatif.js +0 -136
@@ -0,0 +1,165 @@
1
+ // Two blocks, A (before) and B (after), on one microarchitecture: one result object for `wuica diff`, the MCP tool
2
+ // diff_blocks and POST /api/diff/<arch>. Throughput before and after, speed-up, per element when both sides give their
3
+ // elements per iteration, bottlenecks and limits before and after, the change of each port's uops, the instructions that
4
+ // were added, removed or changed (ab-diff.js: the alignment of the page's A–B view), and each side's decode errors and
5
+ // warnings. No DOM; the package's copy is in packages/wuica/lib/web (web-modules.json).
6
+ //
7
+ // Numbers as compare and what-if give them: tp and the limits as the analyzer gives them (two decimals), delta and
8
+ // speedup rounded to two decimals, perElement tp / per unrounded (as compare's and what-if's perElement), the uop changes
9
+ // rounded to two decimals as the uop table shows them.
10
+
11
+ import { compareResponses, MINOR } from './ab-diff.js';
12
+ import { compare as compareMarkdown, shownLabels, text as mdText } from './markdown.js';
13
+
14
+ const r2 = (v) => (typeof v === 'number' && Number.isFinite(v) ? Math.round(v * 100) / 100 : null);
15
+ const side = (r, per) => ({
16
+ tp: r.tp, mode: r.mode, bottlenecks: r.bottlenecks, decodeErrors: r.decodeErrors ?? 0,
17
+ ...(r.unsupported ? { unsupported: r.unsupported } : {}), // (the CPU cannot run this side's code: caveats.js cannotRun)
18
+ ...(per ? { perElement: r.tp / per } : {}), ...(r.loop ? { loop: r.loop } : {}),
19
+ ...(r.stderr?.length ? { stderr: r.stderr } : {}),
20
+ });
21
+
22
+ // A's and B's modes differ (a loop against a block run unrolled): not comparable, as what-if says of such a variant.
23
+ const modeName = (m) => (m === 'loop' ? 'as a loop' : 'unrolled (it does not end with a branch)');
24
+ function notComparable(ra, rb) {
25
+ const error = `not comparable: A is analyzed ${modeName(ra.mode)}, B ${modeName(rb.mode)}`;
26
+ return { code: 1, error, stderr: [{ text: error }] };
27
+ }
28
+
29
+ // The result from the two analyze() responses (or the failure for a mode mismatch). opts: {per: [elements per iteration
30
+ // of A, of B] (both or none), sourceA, sourceB (the assembly text: branch targets as its labels)}.
31
+ /** @param {any} ra @param {any} rb @param {{per?: number[] | null, sourceA?: string | null, sourceB?: string | null}} [opts] @returns {any} */
32
+ export function diffResult(ra, rb, { per = null, sourceA = null, sourceB = null } = {}) {
33
+ if (ra.mode !== rb.mode) return notComparable(ra, rb);
34
+ const [pa, pb] = per ?? [null, null];
35
+ const cmp = compareResponses(ra, rb);
36
+ const t = cmp.tp;
37
+ // a side the CPU cannot run (unsupported, caveats.js cannotRun): its number is no result, so neither are the change
38
+ // and the speedup: verdict "not comparable", no delta, no speedup, in every form
39
+ const no = !!(ra.unsupported || rb.unsupported);
40
+ /** @type {any} */
41
+ const out = { code: 0, arch: ra.arch, a: side(ra, pa), b: side(rb, pb), ...(no ? { verdict: 'not comparable' } : { delta: r2(t.delta), speedup: r2(t.speedup), verdict: t.verdict }) };
42
+ if (pa && pb) {
43
+ const pe = compareResponses(ra, rb, { workA: pa, workB: pb }).tp;
44
+ out.perElement = { a: ra.tp / pa, b: rb.tp / pb, ...(no ? { verdict: 'not comparable' } : { delta: pe.delta, speedup: r2(pe.speedup), verdict: pe.verdict }) };
45
+ }
46
+ out.bottlenecks = { a: cmp.bottlenecks.a, b: cmp.bottlenecks.b, gone: cmp.bottlenecks.gone, new: cmp.bottlenecks.new };
47
+ out.limits = cmp.limits.map((l) => ({ name: l.name, a: l.a, b: l.b, delta: r2(l.delta) }));
48
+ // uops per iteration of each port (the ports both sides have), and the change
49
+ const d = cmp.diff;
50
+ const total = (r, i) => Number(r2(r.rows.reduce((s, x) => s + (Number(x.values?.[i]) || 0), 0)));
51
+ out.ports = d.portsComparable ? d.columns.filter((c) => c.kind === 'port').map((c) => ({ port: c.name, a: total(ra, c.ia), b: total(rb, c.ib), delta: r2(total(rb, c.ib) - total(ra, c.ia)) })) : [];
52
+ // the instructions that differ (branch targets as labels where the text gives them)
53
+ const labels = new Map();
54
+ for (const [r, source] of [[ra, sourceA], [rb, sourceB]]) shownLabels(r, typeof source === 'string' ? { source } : {}).forEach((l, i) => labels.set(r.rows[i], l));
55
+ const label = (u) => (u ? labels.get(u.row) ?? u.label : null);
56
+ out.instructions = {
57
+ counts: d.counts,
58
+ changes: d.rows.filter((x) => x.status !== 'same').map((x) => ({
59
+ status: x.status, a: label(x.a), b: label(x.b),
60
+ uops: Object.fromEntries(d.columns.map((c, k) => [c.name === 'Issued' ? 'issued' : c.name, r2(x.deltas[k])]).filter(([, v]) => v !== 0)),
61
+ ...(x.minor ? { minor: true } : {}), // (ab-diff.js MINOR: left out of the Markdown and the text)
62
+ })),
63
+ };
64
+ // the warnings of each side (decode errors, assembler warnings, the exits taken as not taken), named
65
+ const warnings = [...(ra.stderr ?? []).map((l) => ({ ...l, text: `A: ${l.text}` })), ...(rb.stderr ?? []).map((l) => ({ ...l, text: `B: ${l.text}` }))];
66
+ if (warnings.length) out.stderr = warnings;
67
+ return out;
68
+ }
69
+
70
+ // The two analyses and the result: {result, a, b} (a, b: the analyze() responses), or {failure}. request: {a: {source
71
+ // | hex, syntax, loop, func, options?}, b: {...}, options?, per?: N | [A, B]}; `options` apply to both sides unless a
72
+ // side has its own. w: anything with analyze(arch, request) (and resolveArch). A failure names the side ("A: ", "B: ")
73
+ // only when it belongs to that side.
74
+ /** @param {any} w @param {string} arch @param {any} request @returns {Promise<any>} */
75
+ export async function diffAnalyses(w, arch, request) {
76
+ const bad = (error, code = 1) => ({ failure: { code, error, stderr: [{ text: error }] } });
77
+ if (request === null || typeof request !== 'object' || Array.isArray(request)) return bad('the request must be an object');
78
+ const unknown = Object.keys(request).filter((k) => !['a', 'b', 'options', 'per'].includes(k));
79
+ if (unknown.length) return bad(`unknown request field(s): ${unknown.join(', ')} (known: a, b, options, per)`);
80
+ for (const k of ['a', 'b']) {
81
+ const x = request[k];
82
+ if (x === null || typeof x !== 'object' || Array.isArray(x)) return bad(`\`${k}\` must be a block: {source | hex, syntax?, loop?, func?, options?}`);
83
+ }
84
+ if (request.options !== undefined && (request.options === null || typeof request.options !== 'object' || Array.isArray(request.options))) return bad('`options` must be an object');
85
+ let per = request.per ?? null;
86
+ if (per !== null) {
87
+ if (typeof per === 'number') per = [per, per];
88
+ const ok = Array.isArray(per) && per.length === 2 && per.every((n) => typeof n === 'number' && Number.isFinite(n) && n > 0);
89
+ if (!ok) return bad('`per` must be a positive number (elements per iteration of both) or [A, B]');
90
+ }
91
+ if (typeof w.resolveArch === 'function' && !w.resolveArch(arch)) {
92
+ const r = await w.analyze(arch, request.a); // the library's message for an unknown microarchitecture
93
+ if (r.code) return { failure: r };
94
+ }
95
+ const one = (x) => (request.options !== undefined && x.options === undefined ? { ...x, options: request.options } : x);
96
+ // an error of the options both sides share is the request's, not a side's
97
+ const named = (k, r) => {
98
+ const shared = request.options !== undefined && request[k].options === undefined && /option/.test(r.error ?? '');
99
+ return { failure: shared ? r : { ...r, error: `${k.toUpperCase()}: ${r.error}` } };
100
+ };
101
+ const ra = await w.analyze(arch, one(request.a));
102
+ if (ra.code) return named('a', ra);
103
+ const rb = await w.analyze(arch, one(request.b));
104
+ if (rb.code) return named('b', rb);
105
+ const text = (x) => (typeof x.source === 'string' ? x.source : null);
106
+ const result = diffResult(ra, rb, { per, sourceA: text(request.a), sourceB: text(request.b) });
107
+ if (result.code) return { failure: result };
108
+ return { result, a: ra, b: rb, per, sourceA: text(request.a), sourceB: text(request.b) };
109
+ }
110
+
111
+ // diffAnalyses' result alone, or its failure.
112
+ /** @param {any} w @param {string} arch @param {any} request @returns {Promise<any>} */
113
+ export async function diffRequest(w, arch, request) {
114
+ const x = await diffAnalyses(w, arch, request);
115
+ return x.failure ?? x.result;
116
+ }
117
+
118
+ // Markdown of diffAnalyses' result (markdown.js compare: the page's A–B tables) with the microarchitecture named
119
+ // (opts.archTitle, e.g. "SKL · Skylake (2015)") and each side's warnings, or of its failure.
120
+ /** @param {any} x @param {{archTitle?: string}} [opts] */
121
+ export function diffMarkdown(x, { archTitle } = {}) {
122
+ if (x.failure) return `**diff failed:** ${mdText(x.failure.error)}\n`;
123
+ const [pa, pb] = x.per ?? [1, 1];
124
+ const shownA = shownLabels(x.a, typeof x.sourceA === 'string' ? { source: x.sourceA } : {});
125
+ const shownB = shownLabels(x.b, typeof x.sourceB === 'string' ? { source: x.sourceB } : {});
126
+ const head = `**A–B on ${mdText(archTitle ?? x.result.arch)}**\n\n`;
127
+ const warnings = (x.result.stderr ?? []).map((l) => `- ${mdText(l.text)}`).join('\n');
128
+ return head + compareMarkdown(x.a, x.b, { workA: pa, workB: pb, shownA, shownB }) + (warnings ? `\n${warnings}\n` : '');
129
+ }
130
+
131
+ // The result as text (the CLI without -md, the REST API's text/plain): cycles with two decimals, per element as the CLI
132
+ // prints it (three significant digits below 0.1).
133
+ const f2 = (v) => (v === null || v === undefined ? '-' : Number(v).toFixed(2));
134
+ const fe = (v) => (v === null || v === undefined ? '-' : v !== 0 && Math.abs(v) < 0.1 ? Number(v).toPrecision(3) : f2(v));
135
+ const sg = (v, f = f2) => (v === null || v === undefined ? '' : `${v > 0 ? '+' : ''}${f(v)}`);
136
+ export function diffText(r) {
137
+ if (r.code) return `diff failed: ${r.error}\n`;
138
+ const pct = r.a.tp > 0 ? ` ${sg((100 * (r.b.tp - r.a.tp)) / r.a.tp, (v) => Number(v).toFixed(1))}%` : '';
139
+ // a side whose code the CPU cannot run (unsupported): its number is no result, so no verdict
140
+ const bad = [['A', r.a.unsupported], ['B', r.b.unsupported]].filter(([, x]) => x).map(([k, x]) => `${k} ${x}`);
141
+ const verdict = (v, same) => (bad.length ? `not comparable: ${bad.join(', ')}` : same ? 'the same' : v);
142
+ const lines = [`${r.arch}: A ${f2(r.a.tp)} B ${f2(r.b.tp)} cycles per iteration (${verdict(`${sg(r.delta)},${pct}; speedup ${f2(r.speedup)}x`, r.verdict === 'same')})`];
143
+ if (r.perElement) lines.push(`per element: A ${fe(r.perElement.a)} B ${fe(r.perElement.b)} (${verdict(`${sg(r.perElement.delta, fe)}; speedup ${f2(r.perElement.speedup)}x`, r.perElement.verdict === 'same')})`);
144
+ const names = (xs) => (xs.length ? xs.join(', ') : 'unknown');
145
+ lines.push(`bottleneck: A ${names(r.bottlenecks.a)} -> B ${names(r.bottlenecks.b)}`);
146
+ for (const l of r.stderr ?? []) lines.push(`warning: ${l.text.replace(/^([AB]: )Warning: /, '$1')}`);
147
+ const w = Math.max(5, ...r.limits.map((l) => l.name.length));
148
+ lines.push('', ` ${'limit'.padEnd(w)} ${'A'.padStart(7)} ${'B'.padStart(7)} ${'delta'.padStart(7)}`);
149
+ for (const l of r.limits) lines.push(` ${l.name.padEnd(w)} ${f2(l.a).padStart(7)} ${f2(l.b).padStart(7)} ${(l.delta ? sg(l.delta) : '').padStart(7)}`.trimEnd());
150
+ const moved = r.ports.filter((p) => Math.abs(p.delta) >= MINOR); // (a change under MINOR, as the instructions': not listed)
151
+ lines.push('', `ports (uops per iteration): ${moved.length ? moved.map((p) => `${p.port} ${f2(p.a)} -> ${f2(p.b)}`).join(', ') : 'no change'}`);
152
+ // (minor changes of uops, ab-diff.js MINOR, are counted as the same and not listed)
153
+ const minor = r.instructions.changes.filter((x) => x.minor).length;
154
+ const c = { ...r.instructions.counts, changed: r.instructions.counts.changed - minor };
155
+ const said = [['modified', 'with other operands'], ['changed', 'with other uops'], ['added', 'only in B'], ['removed', 'only in A']].filter(([k]) => c[k]).map(([k, t]) => `${c[k]} ${t}`);
156
+ lines.push(`instructions: ${said.length ? said.join('; ') : 'the same'}${minor ? ` (changes under ${MINOR} uops not listed: ${minor})` : ''}`);
157
+ const MARK = { changed: '*', modified: '~', added: '+', removed: '-' };
158
+ for (const x of r.instructions.changes.filter((y) => !y.minor)) {
159
+ const what = x.status === 'added' ? x.b : x.status === 'removed' ? x.a : x.status === 'modified' ? `${x.a} -> ${x.b}` : x.a;
160
+ const uops = Object.entries(x.uops).map(([k, v]) => `${k} ${sg(v)}`).join(', ');
161
+ lines.push(` ${MARK[x.status]} ${what}${uops ? ` (${uops})` : ''}`);
162
+ }
163
+ if (said.length) lines.push(` (~ other operands, * same instruction with other uops, + only in B, - only in A; uops per iteration, B - A)`);
164
+ return lines.join('\n') + '\n';
165
+ }
@@ -0,0 +1,211 @@
1
+ // The bound model of a response, without the DOM: how busy each resource is as a share of the predicted cycles, the
2
+ // binding resource, the next limit after it, which instructions use a resource (blame), and the compact form of all
3
+ // that the npm package returns as `insights` (REST, MCP, the CLI's -json). One module for the page (bound.js, icard.js,
4
+ // srcmap.js render it) and the package (its copy in packages/wuica/lib/web, web-modules.json).
5
+
6
+ import { caveats } from './caveats.js';
7
+
8
+ const EPS = 0.005; // values are shown with two decimals
9
+ const LIMIT_GROUP = { Issue: 'issue', Ports: 'ports', Dependencies: 'deps' }; // the rest: front end
10
+ const FE_COLUMN = { DSB: 'DSB', LSD: 'LSD', MS: 'MS' };
11
+ const SATURATED = 0.95; // "Ports": the ports at least this busy relative to the busiest one
12
+ const FRONT_END = ['MITE', 'MS', 'DSB', 'LSD'];
13
+ const COUNTS = ['Issued', 'Exec.'];
14
+
15
+ const sum = (a) => a.reduce((s, x) => s + x, 0);
16
+ const pct = (u) => `${Math.round(u * 100)}%`;
17
+ const f2 = (x) => Number(x).toFixed(2);
18
+ const round = (x) => Math.round(x * 100) / 100;
19
+
20
+ // The kind of a column of the uop table: 'front' (uops from the decoders, the DSB, the LSD, the MS), 'count' (issued,
21
+ // executed), 'port' ("Port 0", "ALU0", "FP2", "Div", ...: every other column is an execution resource).
22
+ export function columnKind(name) {
23
+ if (FRONT_END.includes(name)) return 'front';
24
+ if (COUNTS.includes(name)) return 'count';
25
+ return 'port';
26
+ }
27
+
28
+ // "Port 0" -> "p0"; Zen 3's names (ALU0, FP2, ...) and Div as they are
29
+ export function shortPort(name) {
30
+ const m = /^Port (\w+)$/.exec(name);
31
+ return m ? `p${m[1]}` : name === 'Div' ? 'div' : name;
32
+ }
33
+
34
+ function columnTotal(r, i) {
35
+ let t = 0;
36
+ for (const x of r.rows) t += Number(x.values?.[i]) || 0;
37
+ return t;
38
+ }
39
+
40
+ // The resources of a response:
41
+ // {tp, items: [{id, name, title, group, cycles, util, limit, bottleneck}], binding: [ids], next: {name, tp, speedup} | null,
42
+ // gap}. util = cycles / tp (1: busy every cycle; above 1: uiCA's bound is above the simulated throughput).
43
+ // binding: the bottlenecks uiCA names that are resources here (the divider: its Div column); when it names none, the
44
+ // largest limit(s), the nearest bound. A bottleneck without a limit of its own ("Scheduling") binds nothing here: no
45
+ // resource is marked and there is no next limit (until 0.1.9 the page then took the largest limits as binding and showed
46
+ // the next limit below them, which is no bound once the scheduling goes; the package's insights had it right).
47
+ // next: the largest limit below the binding one; speedup = tp / next.tp is an upper bound (the next limit is a lower
48
+ // bound of the cycles). gap: cycles that no single limit explains (interactions), 0 if none.
49
+ export function boundModel(r) {
50
+ const tp = Number(r?.tp);
51
+ if (!(tp > 0) || !Array.isArray(r.limits) || !Array.isArray(r.columns) || !Array.isArray(r.rows)) return null;
52
+ const bottlenecks = Array.isArray(r.bottlenecks) ? r.bottlenecks : [];
53
+ const items = [];
54
+ for (const l of r.limits) {
55
+ const c = Number(l.tp);
56
+ if (!Number.isFinite(c)) continue;
57
+ items.push({
58
+ id: l.name, name: l.name, group: LIMIT_GROUP[l.name] ?? 'front', cycles: c, util: c / tp, limit: true,
59
+ bottleneck: bottlenecks.includes(l.name),
60
+ title: `${l.name}: ${f2(c)} cycles/iteration if it were the only bottleneck (${pct(c / tp)} of ${f2(tp)})`,
61
+ });
62
+ }
63
+ r.columns.forEach((name, i) => {
64
+ if (columnKind(name) !== 'port') return;
65
+ const c = columnTotal(r, i);
66
+ if (c <= 0) return;
67
+ const div = name === 'Div';
68
+ items.push({
69
+ id: `col:${name}`, name: shortPort(name), group: 'ports', cycles: c, util: c / tp, limit: false, bottleneck: false,
70
+ title: div ? `divider: busy ${f2(c)} cycles/iteration (${pct(c / tp)})` : `${name}: ${f2(c)} uops/iteration, busy ${pct(c / tp)} of the cycles`,
71
+ });
72
+ });
73
+ const limits = items.filter((x) => x.limit);
74
+ const max = limits.length ? Math.max(...limits.map((x) => x.cycles)) : 0;
75
+ const gap = limits.length && tp - max > EPS ? tp - max : 0;
76
+ if (gap) {
77
+ items.push({ id: 'other', name: 'unexplained', group: 'other', cycles: gap, util: gap / tp, limit: false, bottleneck: false,
78
+ title: `${f2(gap)} cycles/iteration that no single limit explains (interactions between front end, ports and dependencies)` });
79
+ }
80
+ const binding = bottlenecks.map((b) => resourceId(r, b)).filter((b) => items.some((x) => x.id === b));
81
+ if (!bottlenecks.length) for (const x of limits) if (x.cycles >= max - EPS) binding.push(x.id);
82
+ const bindValue = Math.max(...binding.map((b) => items.find((x) => x.id === b).cycles), 0);
83
+ /** @type {{name: string, tp: number, speedup?: number} | null} */
84
+ let next = null;
85
+ for (const x of limits) if (!binding.includes(x.id) && x.cycles < bindValue - EPS && (!next || x.cycles > next.tp)) next = { name: x.name, tp: x.cycles };
86
+ if (next) next.speedup = next.tp > 0 ? tp / next.tp : Infinity;
87
+ return { tp, items, binding, next, gap };
88
+ }
89
+
90
+ // The resource of a bottleneck's name: the divider (no limit of its own) is its Div column
91
+ const resourceId = (r, name) => (name === 'Divider' && r.columns.includes('Div') ? 'col:Div' : name);
92
+
93
+ // The share of each row of the response in a resource: {weights, total, max, unit, ports, portColumns} or null (nothing
94
+ // to attribute).
95
+ // col:<name> the row's uops on that port (or cycles on the divider)
96
+ // Ports its uops on the saturated ports (at least 95 % as busy as the busiest port); ports: their short names,
97
+ // portColumns: the columns
98
+ // Issue its issued (fused) uops; DSB, LSD, MS: its uops from there
99
+ // Decoder its uops from the legacy decoders (MITE); every instruction once if none come from there
100
+ // Predecoder its bytes
101
+ // Dependencies the latency of the chain's edges that start at it
102
+ export function blame(r, id) {
103
+ const n = r.rows.length;
104
+ const w = new Float64Array(n);
105
+ const col = (name) => r.columns.indexOf(name);
106
+ const fromColumn = (i) => { for (let k = 0; k < n; k++) w[k] = Number(r.rows[k].values?.[i]) || 0; };
107
+ let unit = 'uops';
108
+ if (id.startsWith('col:')) {
109
+ const i = col(id.slice(4));
110
+ if (i < 0) return null;
111
+ fromColumn(i);
112
+ if (id === 'col:Div') unit = 'cycles';
113
+ } else if (id === 'Ports') {
114
+ const ports = r.columns.map((name, i) => ({ i, name, t: columnKind(name) === 'port' && name !== 'Div' ? columnTotal(r, i) : 0 })).filter((p) => p.t > 0);
115
+ if (!ports.length) return null;
116
+ const top = Math.max(...ports.map((p) => p.t));
117
+ const hot = ports.filter((p) => p.t >= SATURATED * top);
118
+ for (let k = 0; k < n; k++) w[k] = sum(hot.map((p) => Number(r.rows[k].values?.[p.i]) || 0));
119
+ return finish(w, unit, hot.map((p) => p.name));
120
+ } else if (id === 'Issue') {
121
+ const i = col('Issued');
122
+ if (i < 0) return null;
123
+ fromColumn(i);
124
+ } else if (FE_COLUMN[id]) {
125
+ const i = col(FE_COLUMN[id]);
126
+ if (i < 0) return null;
127
+ fromColumn(i);
128
+ } else if (id === 'Decoder') {
129
+ const i = col('MITE');
130
+ if (i >= 0 && columnTotal(r, i) > 0) fromColumn(i);
131
+ else { unit = 'instructions'; r.rows.forEach((x, k) => { w[k] = x.kind === 'instr' && x.notes !== 'M' ? 1 : 0; }); }
132
+ } else if (id === 'Predecoder') {
133
+ unit = 'bytes';
134
+ r.rows.forEach((x, k) => { w[k] = x.kind === 'instr' ? String(x.opcode ?? '').length / 2 : 0; });
135
+ } else if (id === 'Dependencies') {
136
+ const edges = r.criticalPath?.edges;
137
+ if (!Array.isArray(edges) || !edges.length) return null;
138
+ unit = 'cycles';
139
+ for (const e of edges) if (e.from >= 0 && e.from < n) w[e.from] += Number(e.latency) || 0;
140
+ } else {
141
+ return null;
142
+ }
143
+ return finish(w, unit, null);
144
+ }
145
+
146
+ function finish(w, unit, columns) {
147
+ let total = 0, max = 0;
148
+ for (const x of w) { total += x; if (x > max) max = x; }
149
+ if (!(total > 0)) return null;
150
+ return { weights: w, total, max, unit, ports: columns ? columns.map(shortPort) : null, portColumns: columns };
151
+ }
152
+
153
+ // The rows with the largest shares: [{row, share}], largest first (ties: in table order).
154
+ export function topRows(b, count = 5) {
155
+ if (!b) return [];
156
+ const out = [];
157
+ b.weights.forEach((x, row) => { if (x > 0) out.push({ row, share: x / b.total }); });
158
+ out.sort((a, c) => c.share - a.share || a.row - c.row);
159
+ return out.slice(0, count);
160
+ }
161
+
162
+ // The resource selected by default: the first bottleneck (or the largest limit).
163
+ export const defaultResource = (m) => m?.binding[0] ?? null;
164
+
165
+ // The package's insights (the bound model in its compact form):
166
+ // {utilization, binding, largest?, next?, unexplained?, chain?, hot?, caveats?} or null.
167
+ // utilization: {limit or port column: cycles / tp} (1 = busy every cycle; above 1: uiCA's bound is above the simulation)
168
+ // binding: the bottlenecks uiCA names (the response's `bottlenecks`; [] when it names none: no single limit explains
169
+ // tp, the page says "unknown")
170
+ // largest: when uiCA names none, the largest limit(s): the nearest bound, which alone does not reach tp
171
+ // next: {limit, tp, maxSpeedup}: the largest limit below the binding one; tp / next.tp is an upper bound of the speedup
172
+ // unexplained: cycles per iteration that no single limit explains
173
+ // chain: the critical loop-carried chain: [{index, instr, operand, latency, carried}] (index into `instructions`)
174
+ // hot: {resource, ports?, instructions: [{index, instr, share}]}: the largest shares of the binding resource (top 5)
175
+ // caveats: [{id, text, title, instructions: [index]}]: known blind spots the block meets (caveats.js); absent if none
176
+ // config: the CPU's configuration in uarch.json (configs[r.arch]), for the caveats; without it, split warns as on a CPU
177
+ // without a split-load cost.
178
+ // where a row's instruction came from, if the response says (the package's analyze: `line`, `loc`)
179
+ const sourceOf = (row) => ({ ...(row?.line ? { line: row.line } : {}), ...(row?.loc ? { loc: row.loc } : {}) });
180
+
181
+ /** @param {any} r @param {{splitLoadCycles?: number} | null} [config] */
182
+ export function insights(r, config = null) {
183
+ const m = boundModel(r);
184
+ if (!m) return null;
185
+ const tp = m.tp;
186
+ const utilization = {};
187
+ for (const l of r.limits) utilization[l.name] = round(l.tp / tp);
188
+ for (const x of m.items) if (x.id.startsWith('col:')) utilization[x.id.slice(4)] = round(x.util);
189
+ const binding = [...(r.bottlenecks ?? [])];
190
+ const largest = binding.length ? [] : m.binding;
191
+ /** @type {Record<string, any>} */
192
+ const out = { utilization, binding };
193
+ if (largest.length) out.largest = largest;
194
+ if (m.next) out.next = { limit: m.next.name, tp: m.next.tp, maxSpeedup: m.next.tp > 0 ? round(tp / m.next.tp) : null };
195
+ if (m.gap) out.unexplained = round(m.gap);
196
+ const edges = r.criticalPath?.edges;
197
+ if (Array.isArray(edges) && edges.length) {
198
+ out.chain = edges.map((e) => ({ index: e.from, instr: r.rows[e.from]?.label, ...sourceOf(r.rows[e.from]), operand: String(e.operand).toLowerCase(), latency: e.latency, carried: !!e.carried }));
199
+ }
200
+ const top = binding.length ? binding : largest;
201
+ if (top[0]) {
202
+ const b = blame(r, resourceId(r, top[0]));
203
+ if (b) {
204
+ const instructions = topRows(b).map((x) => ({ index: x.row, instr: r.rows[x.row].label, ...sourceOf(r.rows[x.row]), share: round(x.share) }));
205
+ out.hot = { resource: top[0], ...(b.portColumns ? { ports: b.portColumns } : {}), instructions };
206
+ }
207
+ }
208
+ const cv = caveats(r, config);
209
+ if (cv.length) out.caveats = cv.map((c) => ({ id: c.id, text: c.text, title: c.title, instructions: c.rows }));
210
+ return out;
211
+ }
@@ -0,0 +1,155 @@
1
+ // Branch targets in the uop table as labels. The analyzer disassembles every instruction at address 0, so a loop
2
+ // branch reads "jnz 0xfffffffffffffff4": its target relative to the instruction. Added to the instruction's offset in
3
+ // the block, that is the target in the block. Shown as:
4
+ // - the operand as written in the pasted assembly when it is a symbol that the analyzed code does not define (an exit
5
+ // of a picked loop, "call sink@PLT"), wherever the bytes go: an undefined symbol's displacement is a placeholder;
6
+ // - the label written in the pasted assembly, when the branch's own operand names the target (a label defined there,
7
+ // a GNU numeric "1b" / "1f" as written);
8
+ // - else a label of the pasted text defined exactly at the target; else the nearest one before it plus the offset
9
+ // ("loop+0x10");
10
+ // - else (machine code, or no label before the target) the offset in the block ("jnz 0x0");
11
+ // - a target outside the block, or a call or jump whose 32-bit displacement is 0 (the placeholder of a relocation in an
12
+ // object file), relative to the instruction (".+0xc", ".-0x10"): its address is not known. The row's own label (its
13
+ // tooltip, exports) is unchanged.
14
+ // The labels' offsets come from the text's statements matched one to one with the instruction rows; when the text
15
+ // cannot be matched that way (data or alignment directives in the code, a macro), only offsets are shown.
16
+ // No DOM (tests-js/web_branch_label.mjs).
17
+
18
+ import { statements } from './loop-find.js';
19
+
20
+ const BRANCH = /^((?:(?:bnd|notrack)\s+)?(?:j[a-z]{1,4}|loop[a-z]{0,2}|jrcxz|jecxz|xbegin|call))\s+(0x[0-9a-f]{1,16})$/i;
21
+ const LABEL_ONE = /\s*([A-Za-z_.$@][\w.$@]*|\d+)\s*:(?!:)/y;
22
+ const SYMBOL = /^[A-Za-z_.$@][\w.$@]*$/;
23
+ const NUMERIC_REF = /^\d+[bf]$/i;
24
+ const INTERNAL = /^\.Lwuica_/; // labels the page itself puts into the text (asm-regions.js, loop-find.js)
25
+ // directives that put bytes into the code (or repeat it): the statements no longer match the rows one to one
26
+ const EMITS = /^\.(?:byte|2byte|4byte|8byte|word|short|hword|int|long|quad|octa|value|ascii|asciz|string\d*|fill|skip|space|zero|align|balign[wl]?|p2align[wl]?|rept|irp|irpc|endr|macro|endm|insn|inst|org|incbin|nops?)\b/i;
27
+ const SECTION = /^\.(?:section|data|bss|rodata|pushsection|popsection|previous)\b/i;
28
+
29
+ // The code of lines from..to (1-based, inclusive) of assembly text: [{kind: 'label', name} | {kind: 'instr', operand}]
30
+ // in order, or null if the statements cannot be matched with machine code one to one.
31
+ export function codeStatements(text, from = 1, to = Infinity) {
32
+ const lines = String(text ?? '').replace(/\r\n?/g, '\n').split('\n');
33
+ const out = [];
34
+ for (let i = Math.max(1, from); i <= Math.min(lines.length, to); i++) {
35
+ const raw = lines[i - 1];
36
+ if (/^\s*;/.test(raw)) continue; // a comment line (loop-find.js)
37
+ for (const st of statements(raw)) {
38
+ let t = st.text;
39
+ LABEL_ONE.lastIndex = 0;
40
+ let m;
41
+ while ((m = LABEL_ONE.exec(t))) { out.push({ kind: 'label', name: m[1] }); t = t.slice(LABEL_ONE.lastIndex); LABEL_ONE.lastIndex = 0; }
42
+ t = t.trim();
43
+ if (!t) continue;
44
+ if (t[0] === '.') {
45
+ if (EMITS.test(t) || SECTION.test(t)) return null;
46
+ continue; // .loc, .cfi_*, .type, ...: no code
47
+ }
48
+ if (/^[\w.$@]+\s*=/.test(t)) continue; // a symbol assignment
49
+ const op = /^\S+\s+(.*)$/.exec(t.replace(/^(?:(?:lock|rep\w*|bnd|notrack|data16|data32|addr32|[cdefgs]s)\s+)+/i, ''));
50
+ out.push({ kind: 'instr', operand: op ? op[1].trim() : '' });
51
+ }
52
+ }
53
+ return out;
54
+ }
55
+
56
+ // A target relative to the instruction's start, as an assembler reads it: ".+0xc", ".-0x10"
57
+ /** @param {number} rel */
58
+ export const relativeTarget = (rel) => (rel < 0 ? `.-0x${(-rel).toString(16)}` : `.+0x${rel.toString(16)}`);
59
+
60
+ // The direct branches and calls of the rows: per row null, or {mnemonic, rel (the target relative to the instruction's
61
+ // start: what the analyzer prints), offset (the instruction's in the block), target (offset + rel), inside (0 <= target
62
+ // <= the block's size), external (a call or jump with a 32-bit displacement of 0: a relocation's placeholder, as
63
+ // asm-text.js itemsOf)}. Also {size, starts, instrRows}.
64
+ export function branchTargets(rows) {
65
+ const list = Array.isArray(rows) ? rows : [];
66
+ const starts = [], instrRows = [];
67
+ let offset = 0;
68
+ list.forEach((r, i) => {
69
+ starts.push(offset);
70
+ if (r?.kind === 'instr' && typeof r.opcode === 'string') { instrRows.push(i); offset += r.opcode.length >> 1; }
71
+ });
72
+ const size = offset;
73
+ const targets = list.map((r, i) => {
74
+ if (r?.kind !== 'instr' || typeof r.opcode !== 'string') return null;
75
+ const m = BRANCH.exec(String(r.label ?? '').trim());
76
+ if (!m) return null;
77
+ let t = BigInt(m[2]);
78
+ if (t >= 1n << 63n) t -= 1n << 64n;
79
+ const rel = Number(t);
80
+ if (!Number.isSafeInteger(rel)) return null;
81
+ const target = starts[i] + rel;
82
+ const b = (r.opcode.match(/[0-9a-f]{2}/gi) ?? []).map((x) => parseInt(x, 16)), n = b.length;
83
+ const external = n >= 5 && b.slice(n - 4).every((x) => x === 0)
84
+ && (b[n - 5] === 0xe8 || b[n - 5] === 0xe9 || (n >= 6 && b[n - 6] === 0x0f && (b[n - 5] & 0xf0) === 0x80));
85
+ return { mnemonic: m[1], rel, offset: starts[i], target, inside: target >= 0 && target <= size, external };
86
+ });
87
+ return { targets, size, starts, instrRows };
88
+ }
89
+
90
+ // The shown label of each row (an array as long as rows): a branch with its target shown as above, else null (the row's
91
+ // own label). src: {text, from, to} (assembly; the lines of the analyzed code) or null (machine code).
92
+ /** @param {{text: string, from?: number, to?: number} | null} [src] */
93
+ export function branchLabels(rows, src = null) {
94
+ const list = Array.isArray(rows) ? rows : [];
95
+ const out = new Array(list.length).fill(null);
96
+ const { targets, size, starts, instrRows } = branchTargets(list);
97
+ // the text's labels at their offsets, and each instruction row's operand as written
98
+ const at = new Map(); // offset -> [label] (in the order of the text)
99
+ const placed = []; // [{name, off}] in order
100
+ const written = new Map(); // row index -> operand
101
+ const inside = new Set(); // labels defined in the analyzed code
102
+ const code = src ? codeStatements(src.text, src.from ?? 1, src.to ?? Infinity) : null;
103
+ if (code && code.filter((x) => x.kind === 'instr').length === instrRows.length) {
104
+ let k = 0, pending = [];
105
+ for (const x of code) {
106
+ if (x.kind === 'label') { pending.push(x.name); inside.add(x.name); continue; }
107
+ const off = starts[instrRows[k]];
108
+ written.set(instrRows[k], x.operand);
109
+ for (const n of pending) { (at.get(off) ?? at.set(off, []).get(off)).push(n); placed.push({ name: n, off }); }
110
+ pending = [];
111
+ k++;
112
+ }
113
+ for (const n of pending) { (at.get(size) ?? at.set(size, []).get(size)).push(n); placed.push({ name: n, off: size }); }
114
+ }
115
+ const real = (n) => !INTERNAL.test(n) && !/^\d+$/.test(n);
116
+ targets.forEach((b, i) => {
117
+ if (!b) return;
118
+ const { target } = b;
119
+ const show = (s) => { out[i] = `${b.mnemonic} ${s}`; };
120
+ const w = written.get(i);
121
+ const here = (at.get(target) ?? []);
122
+ if (w && NUMERIC_REF.test(w)) return show(w);
123
+ // a symbol the analyzed code does not define: as written (its displacement may be a placeholder)
124
+ if (w && SYMBOL.test(w) && !INTERNAL.test(w) && !inside.has(w)) return show(w);
125
+ if (!b.inside || b.external) return show(relativeTarget(b.rel));
126
+ if (w && SYMBOL.test(w) && !INTERNAL.test(w) && here.includes(w)) return show(w);
127
+ const exact = here.find(real);
128
+ if (exact) return show(exact);
129
+ const before = placed.filter((p) => real(p.name) && p.off < target).pop();
130
+ if (before) return show(`${before.name}+0x${(target - before.off).toString(16)}`);
131
+ show(`0x${target.toString(16)}`);
132
+ });
133
+ return out;
134
+ }
135
+
136
+ // The lines of the analyzed code of an assembly result (asm-regions.js): the picked loop or body, a marked region, or
137
+ // the whole text. {text, from, to, lines?: the line of each instruction of a picked loop or body}.
138
+ export function analyzedLines(text, r) {
139
+ const t = String(text ?? '');
140
+ if (r?.loop?.line) return { text: t, from: r.loop.line, to: r.loop.endLine ?? r.loop.line, ...(r.loop.lines ? { lines: r.loop.lines } : {}) };
141
+ if (r?.region?.line) {
142
+ const lines = t.split('\n');
143
+ let to = lines.length;
144
+ for (let i = r.region.line; i < lines.length; i++) if (/(?:LLVM-MCA-END|wuica-end)/i.test(lines[i])) { to = i; break; }
145
+ return { text: t, from: r.region.line + 1, to };
146
+ }
147
+ return { text: t, from: 1, to: Infinity };
148
+ }
149
+ // The text of those lines (the analyzed assembly), or null for none: caveats.js cannotRun names the extension a CPU lacks
150
+ // from it
151
+ export function analyzedText(src) {
152
+ if (!src) return null;
153
+ const lines = String(src.text).split('\n');
154
+ return lines.slice(Math.max(0, src.from - 1), Number.isFinite(src.to) ? src.to : lines.length).join('\n');
155
+ }