wuica-cli 0.0.0-stage → 0.1.7
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/LICENSE +661 -0
- package/README.md +436 -2
- package/bin/wuica-mcp.js +16 -0
- package/bin/wuica.js +25 -0
- package/dist/data/arch/ADL-P.json.br +0 -0
- package/dist/data/arch/BDW.json.br +0 -0
- package/dist/data/arch/CFL.json.br +0 -0
- package/dist/data/arch/CLX.json.br +0 -0
- package/dist/data/arch/HSW.json.br +0 -0
- package/dist/data/arch/ICL.json.br +0 -0
- package/dist/data/arch/ICX.json.br +0 -0
- package/dist/data/arch/IVB.json.br +0 -0
- package/dist/data/arch/KBL.json.br +0 -0
- package/dist/data/arch/RKL.json.br +0 -0
- package/dist/data/arch/SKL.json.br +0 -0
- package/dist/data/arch/SKX.json.br +0 -0
- package/dist/data/arch/SNB.json.br +0 -0
- package/dist/data/arch/TGL.json.br +0 -0
- package/dist/data/arch/ZEN3.json.br +0 -0
- package/dist/data/uarch.json.br +0 -0
- package/dist/manifest.json +81 -0
- package/dist/wuica_asm.wasm.br +0 -0
- package/dist/wuica_wasm.wasm.br +0 -0
- package/index.d.ts +372 -0
- package/lib/archs.js +44 -0
- package/lib/cli.js +430 -0
- package/lib/core.js +36 -0
- package/lib/details.js +60 -0
- package/lib/files.js +18 -0
- package/lib/index.js +474 -0
- package/lib/insights.js +100 -0
- package/lib/mcp.js +366 -0
- package/lib/thread-worker.js +46 -0
- package/lib/threads.js +224 -0
- package/lib/wasm.js +221 -0
- package/lib/web/accum.js +202 -0
- package/lib/web/asm-regions.js +415 -0
- package/lib/web/assembler.js +188 -0
- package/lib/web/caveats.js +206 -0
- package/lib/web/loop-find.js +492 -0
- package/lib/whatif.js +136 -0
- package/licenses/LICENSE-LLVM.txt +279 -0
- package/licenses/LICENSE-XED.txt +178 -0
- package/package.json +58 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
// wuica: x86-64 basic-block throughput prediction (a Rust/WebAssembly port of uiCA) for Node.
|
|
2
|
+
//
|
|
3
|
+
// import { createWuica } from 'wuica-cli';
|
|
4
|
+
// const w = await createWuica();
|
|
5
|
+
// const r = await w.analyze('SKL', { source: 'add rax, rbx\nadd rbx, rax' });
|
|
6
|
+
// console.log(r.code, r.tp, r.bottlenecks, r.text);
|
|
7
|
+
//
|
|
8
|
+
// The request/response shapes follow Compiler Explorer's API style and are the contract for a REST server with the
|
|
9
|
+
// same shape (README.md, "API contract"): list = archs(), POST /api/analyze/<arch> = analyze(arch, request), etc.
|
|
10
|
+
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
import { Analyzer, Assembler, parseDiagnostics, codeModeError } from './wasm.js';
|
|
14
|
+
import { archList, DEFAULT_ARCH, ARCH_INFO, ARCH_ORDER } from './archs.js';
|
|
15
|
+
import { insights } from './insights.js';
|
|
16
|
+
import { instrDetails, detailInsights } from './details.js';
|
|
17
|
+
export { detailInsights };
|
|
18
|
+
import { readMaybeCompressed } from './files.js';
|
|
19
|
+
import { CODES, WARM_HEX, failure, tableFailure, analysisResult, compareFields } from './core.js';
|
|
20
|
+
import { ThreadPool, threadLimit, threadOption, threadsFor } from './threads.js';
|
|
21
|
+
// the web page's reading of pasted assembly (copies of web/js in lib/web: tests-js/web_pkg_copies.mjs): the loop of a whole function, objdump lines,
|
|
22
|
+
// exits as not taken, ';' comments, region markers
|
|
23
|
+
import { assembleMarked, commentFixes, separatorNotes } from './web/asm-regions.js';
|
|
24
|
+
import { normalizeText, detectSyntax, preparePaste, syntaxSigns } from './web/loop-find.js';
|
|
25
|
+
export { detectSyntax };
|
|
26
|
+
|
|
27
|
+
// The loops of assembly text, as `loop` and `func` choose among them: [{index, label, function, line, endLine,
|
|
28
|
+
// instructions, depth, auto}] (auto: the one "auto" analyzes) or {error}. No assembling.
|
|
29
|
+
export function listLoops(source, { func = null } = {}) {
|
|
30
|
+
const p = preparePaste(normalizeText(source), { loop: 'auto', func });
|
|
31
|
+
if (p.error) return { error: p.error };
|
|
32
|
+
return p.loops.map((l, index) => ({ index, label: l.label, function: l.function, line: l.begin, endLine: l.end, instructions: l.instructions, depth: l.depth, auto: p.choice === index }));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export { ARCH_INFO, ARCH_ORDER, DEFAULT_ARCH, CODES, WARM_HEX, parseDiagnostics, insights };
|
|
36
|
+
export { whatIf, VARIANTS as WHAT_IF_VARIANTS } from './whatif.js';
|
|
37
|
+
|
|
38
|
+
const DIST = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'dist');
|
|
39
|
+
|
|
40
|
+
export const OPTION_DEFAULTS = Object.freeze({
|
|
41
|
+
alignmentOffset: 0,
|
|
42
|
+
initPolicy: 'diff',
|
|
43
|
+
simpleFrontEnd: false,
|
|
44
|
+
noMicroFusion: false,
|
|
45
|
+
noMacroFusion: false,
|
|
46
|
+
minIterations: 10,
|
|
47
|
+
minCycles: 500,
|
|
48
|
+
includeTrace: false,
|
|
49
|
+
details: false, // per instruction allowed ports, latencies, front-end facts; port set; issue slots (docs/WASM-API.md)
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
export const ARCH_FIELDS = Object.freeze(['id', 'name', 'year', 'prototype', 'table', 'xedChip']);
|
|
53
|
+
|
|
54
|
+
// Accepts "4801d8", "48 01 d8", "0x48, 0x01, 0xd8", "\x48\x01\xd8". Returns lower-case hex or null.
|
|
55
|
+
export function normalizeHex(input) {
|
|
56
|
+
if (input instanceof Uint8Array) return Buffer.from(input).toString('hex');
|
|
57
|
+
const s = String(input).replace(/0x|\\x/gi, '').replace(/[\s,;]+/g, '').toLowerCase();
|
|
58
|
+
return /^(?:[0-9a-f]{2})+$/.test(s) ? s : null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// 0 Intel, 1 AT&T, 2 auto (detected from the text: loop-find.js, detectSyntax); -1 unknown. Missing: auto.
|
|
62
|
+
function syntaxCode(syntax) {
|
|
63
|
+
if (syntax === undefined || syntax === null || syntax === 'auto') return 2;
|
|
64
|
+
if (syntax === 'intel' || syntax === 0) return 0;
|
|
65
|
+
if (syntax === 'att' || syntax === 1) return 1;
|
|
66
|
+
return -1;
|
|
67
|
+
}
|
|
68
|
+
// {code: 0 | 1, name: 'intel' | 'att', detected: true if it was auto}
|
|
69
|
+
function syntaxOf(syntax, text) {
|
|
70
|
+
const c = syntaxCode(syntax);
|
|
71
|
+
if (c !== 2) return { code: c, name: c === 1 ? 'att' : 'intel', detected: false };
|
|
72
|
+
const d = detectSyntax(text) ?? 'intel';
|
|
73
|
+
return { code: d === 'att' ? 1 : 0, name: d, detected: true };
|
|
74
|
+
}
|
|
75
|
+
const SYNTAX_ERROR = (syntax) => `unknown syntax "${syntax}" (use "auto", "intel" or "att")`;
|
|
76
|
+
|
|
77
|
+
// After an assembler error: a line with the other syntax's operands (AT&T's %registers or $immediates in text read as
|
|
78
|
+
// Intel, Intel's [registers] or "ptr [" in text read as AT&T: mixed lines, a directive that does not match the code,
|
|
79
|
+
// "mov rdx, $8"), as a one-line hint, or null. name: the syntax the text was read as.
|
|
80
|
+
export function syntaxHint(text, name) {
|
|
81
|
+
const lines = String(text).split('\n');
|
|
82
|
+
let att = 0, intel = 0, dollar = 0;
|
|
83
|
+
for (let i = 0; i < lines.length; i++) {
|
|
84
|
+
const code = lines[i].replace(/(?:#|\/\/|;).*$/, '');
|
|
85
|
+
if (/^\s*\./.test(code)) continue;
|
|
86
|
+
const n = syntaxSigns(code);
|
|
87
|
+
// "mov rdx, $8": an Intel line with an AT&T immediate
|
|
88
|
+
if (n.att && n.intel && !/%/.test(code)) { dollar ||= i + 1; continue; }
|
|
89
|
+
if (n.att && !att) att = i + 1;
|
|
90
|
+
else if (n.intel && !n.att && !intel) intel = i + 1;
|
|
91
|
+
}
|
|
92
|
+
if (dollar && name === 'intel' && !att) return `hint: line ${dollar} has an AT&T immediate ($) in Intel code: in Intel syntax an immediate has no $ (if the text is AT&T, -att, syntax "att", reads it so)`;
|
|
93
|
+
if (att && intel) return `hint: the text mixes AT&T (line ${att}) and Intel (line ${intel}) operands; the assembler reads one syntax per text: -att or -intel (syntax "att" or "intel")`;
|
|
94
|
+
if (name === 'intel' && att) return `hint: line ${att} has AT&T operands (%register or $immediate) but the text is read as Intel; if it is AT&T, -att (syntax "att") reads it so`;
|
|
95
|
+
if (name === 'att' && intel) return `hint: line ${intel} has Intel operands but the text is read as AT&T; if it is Intel, -intel (syntax "intel") reads it so`;
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// AArch64 assembly (a common mistake on an Arm Mac): its registers and mnemonics on several lines
|
|
100
|
+
export function looksAArch64(text) {
|
|
101
|
+
let n = 0;
|
|
102
|
+
for (const l of String(text).split('\n')) {
|
|
103
|
+
const code = l.replace(/(?:\/\/|;|@).*$/, '').trim();
|
|
104
|
+
if (/^(?:ldr|str|ldp|stp|adrp|cbz|cbnz|b\.\w+|fmadd|fmla|ld1|st1|csel|madd|msub|subs|adds|ldur|stur|fmov|movk)\b/i.test(code) || /(?:^|[\s,\[])[xw](?:[12]?\d|30)\b/.test(code)) n++;
|
|
105
|
+
}
|
|
106
|
+
return n >= 3;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// llvm-mc's diagnostics as stderr lines; lines with a position carry a tag {line, column, severity, text}.
|
|
110
|
+
export function stderrLines(message) {
|
|
111
|
+
const lines = String(message ?? '').replace(/\n+$/, '').split('\n').filter((l) => l !== '');
|
|
112
|
+
return lines.map((text) => {
|
|
113
|
+
const d = parseDiagnostics(text)[0];
|
|
114
|
+
return d && d.line !== null ? { text, tag: { line: d.line, column: d.column, severity: d.severity, text: d.message } } : { text };
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const REQUEST_KEYS = ['source', 'asm', 'hex', 'syntax', 'loop', 'func', 'options'];
|
|
119
|
+
|
|
120
|
+
// `loop` of a request: what of the source is analyzed (web/js/loop-find.js). null if it is not one of these.
|
|
121
|
+
export const LOOP_CHOICES = Object.freeze(['auto', 'whole']);
|
|
122
|
+
// (a string other than these is a loop's label: ".LBB0_12", "0x10")
|
|
123
|
+
const loopChoice = (v) => (v === undefined || v === null ? 'auto' : LOOP_CHOICES.includes(v) || (Number.isSafeInteger(v) && v >= 0) || (typeof v === 'string' && v.trim() !== '') ? v : null);
|
|
124
|
+
const LOOP_ERROR = '`loop` must be "auto", "whole", the index of a loop (0-based) or its label';
|
|
125
|
+
|
|
126
|
+
// Diagnostics ({line, column, severity, message}) as stderr lines in llvm-mc's form, with tags.
|
|
127
|
+
function diagnosticLines(diagnostics) {
|
|
128
|
+
return diagnostics.map((d) => ({
|
|
129
|
+
text: `<input>:${d.line ?? 0}:${d.column ?? 0}: ${d.severity}: ${d.message}`,
|
|
130
|
+
...(d.line ? { tag: { line: d.line, column: d.column ?? 0, severity: d.severity, text: d.message } } : {}),
|
|
131
|
+
}));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// The simulation options of a request: `options`, and (as a convenience) option keys at the top level of the request;
|
|
135
|
+
// `options` wins. Unknown keys, at the top level or in `options`, are an error rather than being ignored.
|
|
136
|
+
function pickOptions(req, extraKeys) {
|
|
137
|
+
const options = req.options;
|
|
138
|
+
if (options !== undefined && options !== null && (typeof options !== 'object' || Array.isArray(options))) return { error: '`options` must be an object' };
|
|
139
|
+
const allowed = new Set([...REQUEST_KEYS, ...extraKeys, ...Object.keys(OPTION_DEFAULTS)]);
|
|
140
|
+
const unknownTop = Object.keys(req).filter((k) => !allowed.has(k));
|
|
141
|
+
if (unknownTop.length) return { error: `unknown request field(s): ${unknownTop.join(', ')} (known: ${[...REQUEST_KEYS, ...extraKeys].join(', ')}; simulation options go in \`options\`)` };
|
|
142
|
+
const unknown = Object.keys(options ?? {}).filter((k) => !Object.hasOwn(OPTION_DEFAULTS, k));
|
|
143
|
+
if (unknown.length) return { error: `unknown option(s): ${unknown.join(', ')} (known: ${Object.keys(OPTION_DEFAULTS).join(', ')})` };
|
|
144
|
+
const out = {};
|
|
145
|
+
for (const [k, d] of Object.entries(OPTION_DEFAULTS)) {
|
|
146
|
+
const v = options?.[k] ?? req[k] ?? d;
|
|
147
|
+
// a value of the wrong kind is a bad request (code 1), like an unknown option, not a failed analysis
|
|
148
|
+
const bad = typeof d === 'number' ? !Number.isSafeInteger(v) : typeof d === 'boolean' ? typeof v !== 'boolean'
|
|
149
|
+
: k === 'initPolicy' && !['diff', 'same', 'stack'].includes(v);
|
|
150
|
+
if (bad) return { error: `option ${k}: ${JSON.stringify(v)} is not ${typeof d === 'number' ? 'an integer' : typeof d === 'boolean' ? 'true or false' : 'one of "diff", "same", "stack"'}` };
|
|
151
|
+
out[k] = v;
|
|
152
|
+
}
|
|
153
|
+
return { options: out };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
// A list of arch names without repeats (the same id, or the same unknown name), in the order of their first appearance.
|
|
158
|
+
function uniqueArchs(list, resolve) {
|
|
159
|
+
const seen = new Set();
|
|
160
|
+
return list.filter((a) => {
|
|
161
|
+
const key = resolve(a) ?? `?${String(a).trim()}`;
|
|
162
|
+
if (seen.has(key)) return false;
|
|
163
|
+
seen.add(key);
|
|
164
|
+
return true;
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
class Wuica {
|
|
168
|
+
#analyzer;
|
|
169
|
+
#configs;
|
|
170
|
+
#archs;
|
|
171
|
+
#dataDir;
|
|
172
|
+
#asmWasm;
|
|
173
|
+
#assembler = null; // promise of an Assembler
|
|
174
|
+
#loading = new Map(); // table name -> promise
|
|
175
|
+
#wasm; // bytes of the analyzer module (the threads compile it with a memory limit of their own)
|
|
176
|
+
#uarch; // bytes of uarch.json
|
|
177
|
+
#threads; // the most threads compare() uses (1: none)
|
|
178
|
+
#threadsAuto; // no number given: at most one thread per two microarchitectures (threads.js, threadsFor)
|
|
179
|
+
#pool = null; // ThreadPool, started by the first compare() that uses threads
|
|
180
|
+
|
|
181
|
+
constructor(analyzer, configs, dataDir, asmWasm, { wasm, uarch, threads, threadsAuto }) {
|
|
182
|
+
this.#analyzer = analyzer;
|
|
183
|
+
this.#configs = configs;
|
|
184
|
+
this.#archs = archList(configs);
|
|
185
|
+
this.#dataDir = dataDir;
|
|
186
|
+
this.#asmWasm = asmWasm;
|
|
187
|
+
this.#wasm = wasm;
|
|
188
|
+
this.#uarch = uarch;
|
|
189
|
+
this.#threads = threads;
|
|
190
|
+
this.#threadsAuto = threadsAuto;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// The microarchitectures in order of release (like CE's /api/compilers); `fields` selects fields (default: all).
|
|
194
|
+
archs(fields) {
|
|
195
|
+
const list = fields === undefined || fields === null || fields === 'all' ? ARCH_FIELDS : (typeof fields === 'string' ? fields.split(',') : fields).map((f) => f.trim());
|
|
196
|
+
return this.#archs.map((a) => Object.fromEntries(list.filter((f) => Object.hasOwn(a, f)).map((f) => [f, a[f]])));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Exact id, else case-insensitive and ignoring "-" and surrounding whitespace (adlp -> ADL-P). Empty -> DEFAULT_ARCH;
|
|
200
|
+
// unknown -> null.
|
|
201
|
+
resolveArch(arch) {
|
|
202
|
+
if (arch === undefined || arch === null) return DEFAULT_ARCH;
|
|
203
|
+
const s = String(arch).trim();
|
|
204
|
+
if (s === '') return DEFAULT_ARCH;
|
|
205
|
+
if (Object.hasOwn(this.#configs, s)) return s;
|
|
206
|
+
const norm = (k) => k.toUpperCase().replace(/-/g, '');
|
|
207
|
+
return Object.keys(this.#configs).find((k) => norm(k) === norm(s)) ?? null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
#info(id) {
|
|
211
|
+
return this.#archs.find((a) => a.id === id) ?? { id, name: id, year: null, prototype: !!this.#configs[id]?.experimental };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async #ensureTable(name) {
|
|
215
|
+
if (this.#analyzer.hasArch(name)) return;
|
|
216
|
+
let p = this.#loading.get(name);
|
|
217
|
+
if (!p) {
|
|
218
|
+
p = (async () => {
|
|
219
|
+
const bytes = await readMaybeCompressed(path.join(this.#dataDir, 'arch', `${name}.json`));
|
|
220
|
+
if (!this.#analyzer.hasArch(name)) this.#analyzer.loadArch(name, bytes);
|
|
221
|
+
})();
|
|
222
|
+
this.#loading.set(name, p);
|
|
223
|
+
p.finally(() => this.#loading.delete(name)).catch(() => {});
|
|
224
|
+
}
|
|
225
|
+
await p;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async #getAssembler() {
|
|
229
|
+
if (!this.#assembler) {
|
|
230
|
+
this.#assembler = readMaybeCompressed(this.#asmWasm)
|
|
231
|
+
.then((bytes) => WebAssembly.compile(bytes))
|
|
232
|
+
.then((m) => new Assembler(m));
|
|
233
|
+
this.#assembler.catch(() => { this.#assembler = null; });
|
|
234
|
+
}
|
|
235
|
+
return this.#assembler;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// POST /api/assemble {source, syntax}
|
|
239
|
+
async assemble(source, syntax = 'auto') {
|
|
240
|
+
if (typeof source !== 'string') return failure(CODES.REQUEST, '`source` must be a string');
|
|
241
|
+
if (syntaxCode(syntax) < 0) return failure(CODES.REQUEST, SYNTAX_ERROR(syntax));
|
|
242
|
+
// a byte order mark (a file saved by some Windows editors) is not part of the code: LLVM would reject it
|
|
243
|
+
const asm = await this.#getAssembler();
|
|
244
|
+
// (CRLF and a lone CR are line feeds)
|
|
245
|
+
let text = normalizeText(source).replace(/^\uFEFF/, '');
|
|
246
|
+
const s = syntaxOf(syntax, text).code;
|
|
247
|
+
let r = asm.assemble(text, s);
|
|
248
|
+
// ';' comments: a ';' whose rest the assembler rejects is retried as '#' (web/js/asm-regions.js)
|
|
249
|
+
const notes = [];
|
|
250
|
+
for (let round = 0; !r.ok && r.status !== 'trap' && round < 8; round++) {
|
|
251
|
+
const { fixes, notes: n } = commentFixes(parseDiagnostics(r.message), text);
|
|
252
|
+
notes.push(...n);
|
|
253
|
+
if (!fixes.size) break;
|
|
254
|
+
const lines = text.split('\n');
|
|
255
|
+
for (const [l, t] of fixes) lines[l - 1] = t;
|
|
256
|
+
text = lines.join('\n');
|
|
257
|
+
r = asm.assemble(text, s);
|
|
258
|
+
}
|
|
259
|
+
if (!r.ok) {
|
|
260
|
+
if (r.status === 'trap') return failure(CODES.ASSEMBLER, r.message, undefined, { trapped: true });
|
|
261
|
+
const first = parseDiagnostics(r.message).find((d) => d.severity === 'error');
|
|
262
|
+
const error = first ? `assembly failed: ${first.line !== null ? `line ${first.line}: ` : ''}${first.message}` : 'assembly failed';
|
|
263
|
+
return failure(CODES.ASSEMBLER, error, stderrLines(r.message));
|
|
264
|
+
}
|
|
265
|
+
return { code: CODES.OK, hex: Buffer.from(r.bytes).toString('hex'), length: r.bytes.length, bytes: r.bytes,
|
|
266
|
+
stderr: [...stderrLines(r.message), ...diagnosticLines([...notes, ...separatorNotes(text)])] };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// The machine code an analysis of assembly text gets (as the web page reads it): the loop of a whole function, objdump
|
|
270
|
+
// lines, exits as not taken, ';' comments, a marked region (web/js/loop-find.js, asm-regions.js). loop: 'auto',
|
|
271
|
+
// 'whole', a loop's index or its label; func: the function whose loops count (or null).
|
|
272
|
+
// -> {code: 0, hex, bytes, stderr, loop, syntax} (loop: what was picked, or null; syntax: {name, detected}) or a failure.
|
|
273
|
+
async machineCode(source, syntax = 'auto', loop = 'auto', func = null) {
|
|
274
|
+
if (typeof source !== 'string') return failure(CODES.REQUEST, '`source` must be a string');
|
|
275
|
+
if (syntaxCode(syntax) < 0) return failure(CODES.REQUEST, SYNTAX_ERROR(syntax));
|
|
276
|
+
if (loopChoice(loop) === null) return failure(CODES.REQUEST, LOOP_ERROR);
|
|
277
|
+
if (func !== null && func !== undefined && typeof func !== 'string') return failure(CODES.REQUEST, '`func` must be the name of a function');
|
|
278
|
+
const syn = syntaxOf(syntax, normalizeText(source));
|
|
279
|
+
const s = syn.code;
|
|
280
|
+
const asm = await this.#getAssembler();
|
|
281
|
+
let trap = null;
|
|
282
|
+
const assemble = async (t) => {
|
|
283
|
+
const r = asm.assemble(t, s);
|
|
284
|
+
if (!r.ok && r.status === 'trap') trap = r.message;
|
|
285
|
+
return { ok: r.ok, bytes: r.bytes, diagnostics: parseDiagnostics(r.message) };
|
|
286
|
+
};
|
|
287
|
+
const text = normalizeText(source).replace(/^\uFEFF/, '');
|
|
288
|
+
const r = await assembleMarked(assemble, text, { loop: loopChoice(loop), func });
|
|
289
|
+
if (trap) return failure(CODES.ASSEMBLER, trap, undefined, { trapped: true });
|
|
290
|
+
if (!r.ok) {
|
|
291
|
+
const bad = r.diagnostics.find((d) => /^(?:loop|func): /.test(d.message));
|
|
292
|
+
if (bad) return failure(CODES.REQUEST, bad.message);
|
|
293
|
+
if (looksAArch64(text)) return failure(CODES.ASSEMBLER, 'this looks like AArch64 assembly; wuica analyzes x86-64 (compile with --target=x86_64-linux-gnu)');
|
|
294
|
+
const first = r.diagnostics.find((d) => d.severity === 'error');
|
|
295
|
+
const error = first ? `assembly failed: ${first.line ? `line ${first.line}: ` : ''}${first.message}` : 'assembly failed';
|
|
296
|
+
// llvm-mc's own lines (with the source line and the caret) when the text alone fails on the same line
|
|
297
|
+
const plain = asm.assemble(text, s);
|
|
298
|
+
const same = !plain.ok && first && parseDiagnostics(plain.message).find((d) => d.severity === 'error')?.line === first.line;
|
|
299
|
+
const hint = syntaxHint(text, syn.name);
|
|
300
|
+
return failure(CODES.ASSEMBLER, error, [...(same ? stderrLines(plain.message) : diagnosticLines(r.diagnostics)), ...(hint ? [{ text: hint }] : [])]);
|
|
301
|
+
}
|
|
302
|
+
// what was analyzed, if not the whole text as it is: the loop (or body) picked, or the alignment from addresses
|
|
303
|
+
const picked = r.loop ?? (r.alignment !== null ? { index: null, count: r.loops.length, name: 'whole', line: null, endLine: null, address: null, alignment: r.alignment } : null);
|
|
304
|
+
const info = picked && Number.isInteger(picked.index) ? r.loops[picked.index] : null;
|
|
305
|
+
const loopInfo = picked && { index: picked.index, count: picked.count, name: picked.name, line: picked.line, endLine: picked.endLine, ...(picked.lines ? { lines: picked.lines } : {}),
|
|
306
|
+
...(info ? { function: info.function, depth: info.depth, instructions: info.instructions } : {}),
|
|
307
|
+
...(picked.address !== null && picked.address !== undefined ? { address: picked.address } : {}), ...(r.alignment !== null ? { alignmentOffset: r.alignment } : {}) };
|
|
308
|
+
return { code: CODES.OK, hex: Buffer.from(r.bytes).toString('hex'), bytes: r.bytes, stderr: diagnosticLines(r.diagnostics), loop: loopInfo, syntax: { name: syn.name, detected: syn.detected } };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// {source | asm | hex, syntax, loop} -> {hex, assembled, stderr, loop} or a failure.
|
|
312
|
+
async #code(req) {
|
|
313
|
+
const source = req.source ?? req.asm;
|
|
314
|
+
const hasSource = source !== undefined && source !== null;
|
|
315
|
+
const hasHex = req.hex !== undefined && req.hex !== null;
|
|
316
|
+
if (hasSource === hasHex) return failure(CODES.REQUEST, 'give exactly one of `source` (assembly text) and `hex` (machine code)');
|
|
317
|
+
if (loopChoice(req.loop) === null) return failure(CODES.REQUEST, LOOP_ERROR);
|
|
318
|
+
if (hasHex) {
|
|
319
|
+
if (req.syntax !== undefined && syntaxCode(req.syntax) < 0) return failure(CODES.REQUEST, SYNTAX_ERROR(req.syntax));
|
|
320
|
+
const hex = normalizeHex(req.hex);
|
|
321
|
+
if (hex === null && typeof req.hex === 'string' && normalizeHex(req.hex + '00') === '00') return failure(CODES.REQUEST, '`hex` is empty: no machine code');
|
|
322
|
+
if (hex === null) return failure(CODES.REQUEST, '`hex`: expected an even number of hex digits (spaces, commas and 0x prefixes are allowed)');
|
|
323
|
+
return { hex, assembled: false, stderr: [] };
|
|
324
|
+
}
|
|
325
|
+
// 16- or 32-bit code would be analyzed as 64-bit code (the analyzer only models 64-bit mode)
|
|
326
|
+
const mode = typeof source === 'string' ? codeModeError(source) : null;
|
|
327
|
+
if (mode) return failure(CODES.REQUEST, `line ${mode.line}: ${mode.message}`);
|
|
328
|
+
const a = await this.machineCode(source, req.syntax ?? 'auto', loopChoice(req.loop), req.func ?? null);
|
|
329
|
+
if (a.code !== CODES.OK) return a;
|
|
330
|
+
if (a.bytes.length === 0) return failure(CODES.REQUEST, 'the source contains no instructions');
|
|
331
|
+
return { hex: a.hex, assembled: true, stderr: a.stderr, loop: a.loop, syntax: a.syntax.name };
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// The options of a request with the alignment offset of the code's addresses (objdump input), unless it was given.
|
|
335
|
+
static #withAlignment(req, options, code) {
|
|
336
|
+
const given = req.options?.alignmentOffset !== undefined || req.alignmentOffset !== undefined;
|
|
337
|
+
return !given && code.loop?.alignmentOffset !== undefined ? { ...options, alignmentOffset: code.loop.alignmentOffset } : options;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
async #run(hex, arch, options) {
|
|
341
|
+
const id = this.resolveArch(arch);
|
|
342
|
+
if (!id) return failure(CODES.REQUEST, `unknown microarchitecture: ${arch} (known: ${this.#archs.map((a) => a.id).join(', ')})`);
|
|
343
|
+
try {
|
|
344
|
+
await this.#ensureTable(this.#configs[id].name);
|
|
345
|
+
} catch (e) {
|
|
346
|
+
return tableFailure(id, e);
|
|
347
|
+
}
|
|
348
|
+
return analysisResult(this.#analyzer.analyze({ hex, arch: id, ...options }));
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// POST /api/analyze/<arch> {source | hex, syntax, options}. Also analyze({arch, source | hex, ...}).
|
|
352
|
+
async analyze(arch, request) {
|
|
353
|
+
let req = request;
|
|
354
|
+
if (typeof arch === 'object' && arch !== null && request === undefined) { req = arch; arch = req.arch; }
|
|
355
|
+
req ??= {};
|
|
356
|
+
if (typeof req !== 'object') return failure(CODES.REQUEST, 'the request must be an object');
|
|
357
|
+
const opts = pickOptions(req, ['arch']);
|
|
358
|
+
if (opts.error) return failure(CODES.REQUEST, opts.error);
|
|
359
|
+
const code = await this.#code(req);
|
|
360
|
+
if (code.code !== undefined) return code;
|
|
361
|
+
const r = await this.#run(code.hex, arch, Wuica.#withAlignment(req, opts.options, code));
|
|
362
|
+
if (r.code !== undefined) return r;
|
|
363
|
+
const stderr = [...code.stderr];
|
|
364
|
+
if (r.decodeErrors > 0) stderr.push({ text: `Warning: ${r.decodeErrors} position(s) could not be decoded` });
|
|
365
|
+
return { code: CODES.OK, ...r, ...(code.assembled ? { hex: code.hex, syntax: code.syntax } : {}), ...(code.loop ? { loop: code.loop } : {}), stderr };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// POST /api/compare {source | hex, syntax, archs?, options}: one block on several microarchitectures (default: all).
|
|
369
|
+
async compare(request = {}) {
|
|
370
|
+
const opts = pickOptions(request, ['archs']);
|
|
371
|
+
if (opts.error) return failure(CODES.REQUEST, opts.error);
|
|
372
|
+
const code = await this.#code(request);
|
|
373
|
+
if (code.code !== undefined) return code;
|
|
374
|
+
if (request.archs !== undefined && !Array.isArray(request.archs)) return failure(CODES.REQUEST, '`archs` must be an array of ids');
|
|
375
|
+
const ids = request.archs?.length ? uniqueArchs(request.archs, (a) => this.resolveArch(a)) : this.#archs.map((a) => a.id);
|
|
376
|
+
const options = { ...Wuica.#withAlignment(request, opts.options, code), includeTrace: false, details: false };
|
|
377
|
+
const resolved = ids.map((arch) => this.resolveArch(arch));
|
|
378
|
+
// the microarchitectures in threads (if that means at least two threads), each as #run() would on this thread;
|
|
379
|
+
// whatever the threads do not do (unknown ids, a thread that failed) is done here, one after another
|
|
380
|
+
const fields = new Array(ids.length).fill(null);
|
|
381
|
+
const known = resolved.flatMap((id, i) => (id ? [{ i, table: this.#configs[id].name, request: { hex: code.hex, arch: id, ...options } }] : []));
|
|
382
|
+
const threads = threadsFor(new Set(known.map((j) => j.table)).size, this.#threads, this.#threadsAuto);
|
|
383
|
+
if (threads > 1) {
|
|
384
|
+
this.#pool ??= new ThreadPool({ wasm: this.#wasm, uarch: this.#uarch, dataDir: this.#dataDir, limit: this.#threads });
|
|
385
|
+
if (!this.#pool.broken) {
|
|
386
|
+
const done = await this.#pool.run(known, threads);
|
|
387
|
+
known.forEach((j, k) => { fields[j.i] = done[k]; });
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
const results = [];
|
|
391
|
+
for (const [i, arch] of ids.entries()) {
|
|
392
|
+
const id = resolved[i];
|
|
393
|
+
const { name, year, prototype } = id ? this.#info(id) : { name: String(arch), year: null, prototype: false };
|
|
394
|
+
const row = { arch: id ?? String(arch), name, year, prototype };
|
|
395
|
+
results.push({ ...row, ...(fields[i] ?? compareFields(await this.#run(code.hex, arch, options))) });
|
|
396
|
+
}
|
|
397
|
+
// a CPU that could not decode some instructions (FMA on SNB): its throughput leaves them out
|
|
398
|
+
const decode = results.filter((r) => r.code === CODES.OK && r.decodeErrors > 0)
|
|
399
|
+
.map((r) => ({ text: `Warning: ${r.arch}: ${r.decodeErrors} position(s) could not be decoded (instructions it does not have): its throughput leaves them out` }));
|
|
400
|
+
return { code: CODES.OK, ...(code.assembled ? { hex: code.hex, syntax: code.syntax } : {}), ...(code.loop ? { loop: code.loop } : {}), stderr: [...code.stderr, ...decode], results };
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// Stops compare()'s threads, if any (they also stop by themselves when idle, and never keep the process alive while
|
|
404
|
+
// idle). The instance stays usable: the next compare() starts them again.
|
|
405
|
+
async close() {
|
|
406
|
+
await this.#pool?.close();
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// The number of threads compare() has running now (0 if none).
|
|
410
|
+
get threads() { return this.#pool?.threads ?? 0; }
|
|
411
|
+
|
|
412
|
+
// The derived diagnosis of an analyze() response (insights.js) with this CPU's configuration (the split-load caveat
|
|
413
|
+
// depends on it); null for a failure.
|
|
414
|
+
insights(r) {
|
|
415
|
+
return r?.code === CODES.OK ? insights(r, this.#configs[r.arch] ?? null) : null;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// The compact form of an analyze() response (used by the MCP server): uop table reduced to non-zero values, plus the
|
|
419
|
+
// derived diagnosis of the web page's bound view (insights.js).
|
|
420
|
+
summarize(r) {
|
|
421
|
+
if (r.code !== CODES.OK) return r;
|
|
422
|
+
const { name, year, prototype } = this.#info(r.arch);
|
|
423
|
+
const round = (x) => Math.round(x * 100) / 100;
|
|
424
|
+
const sources = new Set(['MITE', 'MS', 'DSB', 'LSD']);
|
|
425
|
+
const instructions = r.rows.map((row, k) => {
|
|
426
|
+
const e = { instr: row.label };
|
|
427
|
+
if (row.opcode) e.bytes = row.opcode.toLowerCase();
|
|
428
|
+
if (row.kind !== 'instr') e.kind = row.kind;
|
|
429
|
+
const uopSource = {}, ports = {};
|
|
430
|
+
r.columns.forEach((c, i) => {
|
|
431
|
+
const v = row.values[i];
|
|
432
|
+
if (!v) return;
|
|
433
|
+
if (sources.has(c)) uopSource[c] = round(v);
|
|
434
|
+
else if (c === 'Issued') e.issued = round(v);
|
|
435
|
+
else if (c === 'Exec.') e.executed = round(v);
|
|
436
|
+
else ports[c] = round(v);
|
|
437
|
+
});
|
|
438
|
+
if (Object.keys(uopSource).length) e.uopSource = uopSource;
|
|
439
|
+
if (Object.keys(ports).length) e.ports = ports;
|
|
440
|
+
if (row.notes) e.notes = row.notes;
|
|
441
|
+
if (row.instrStr) e.uopsInfo = row.instrStr;
|
|
442
|
+
const det = instrDetails(r.details?.rows?.[k]);
|
|
443
|
+
if (det) Object.assign(e, det);
|
|
444
|
+
return e;
|
|
445
|
+
});
|
|
446
|
+
const base = this.insights(r);
|
|
447
|
+
const ins = base ? { ...base, ...detailInsights(r) } : null;
|
|
448
|
+
return {
|
|
449
|
+
code: r.code, arch: r.arch, name, year, prototype, tp: r.tp, unit: 'cycles per iteration', mode: r.mode,
|
|
450
|
+
bottlenecks: r.bottlenecks, limits: r.limits, decodeErrors: r.decodeErrors, ...(r.hex ? { hex: r.hex } : {}), ...(r.loop ? { loop: r.loop } : {}),
|
|
451
|
+
stderr: r.stderr, instructions, ...(ins ? { insights: ins } : {}),
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
get restarts() { return this.#analyzer.restarts; }
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// options.dataDir: directory with uarch.json and arch/<NAME>.json (plain or .br); default: the package's tables.
|
|
459
|
+
// options.analyzerWasm / options.assemblerWasm: paths of the modules (plain or .br).
|
|
460
|
+
// options.threads: the most worker threads compare() uses, one per microarchitecture (default: the environment variable
|
|
461
|
+
// WUICA_THREADS, else "auto": os.availableParallelism(), and one thread per two microarchitectures; 1 = none, every
|
|
462
|
+
// microarchitecture one after another on this thread).
|
|
463
|
+
export async function createWuica(options = {}) {
|
|
464
|
+
const threads = threadLimit(options.threads);
|
|
465
|
+
const threadsAuto = threadOption(options.threads) === 'auto';
|
|
466
|
+
const dataDir = options.dataDir ?? path.join(DIST, 'data');
|
|
467
|
+
const analyzerWasm = options.analyzerWasm ?? path.join(DIST, 'wuica_wasm.wasm.br');
|
|
468
|
+
const asmWasm = options.assemblerWasm ?? path.join(DIST, 'wuica_asm.wasm.br');
|
|
469
|
+
const [wasm, uarchBytes] = await Promise.all([readMaybeCompressed(analyzerWasm), readMaybeCompressed(path.join(dataDir, 'uarch.json'))]);
|
|
470
|
+
const analyzer = new Analyzer(await WebAssembly.compile(wasm));
|
|
471
|
+
analyzer.loadUarch(uarchBytes);
|
|
472
|
+
const configs = JSON.parse(new TextDecoder().decode(uarchBytes)).configs;
|
|
473
|
+
return new Wuica(analyzer, configs, dataDir, asmWasm, { wasm, uarch: uarchBytes, threads, threadsAuto });
|
|
474
|
+
}
|
package/lib/insights.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
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
|
+
}
|