wuica-cli 0.0.0-stage → 0.1.9

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 (48) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +546 -2
  3. package/bin/wuica-mcp.js +16 -0
  4. package/bin/wuica.js +25 -0
  5. package/dist/data/arch/ADL-P.bin.br +0 -0
  6. package/dist/data/arch/BDW.bin.br +0 -0
  7. package/dist/data/arch/CFL.bin.br +0 -0
  8. package/dist/data/arch/CLX.bin.br +0 -0
  9. package/dist/data/arch/HSW.bin.br +0 -0
  10. package/dist/data/arch/ICL.bin.br +0 -0
  11. package/dist/data/arch/ICX.bin.br +0 -0
  12. package/dist/data/arch/IVB.bin.br +0 -0
  13. package/dist/data/arch/KBL.bin.br +0 -0
  14. package/dist/data/arch/RKL.bin.br +0 -0
  15. package/dist/data/arch/SKL.bin.br +0 -0
  16. package/dist/data/arch/SKX.bin.br +0 -0
  17. package/dist/data/arch/SNB.bin.br +0 -0
  18. package/dist/data/arch/TGL.bin.br +0 -0
  19. package/dist/data/arch/ZEN3.bin.br +0 -0
  20. package/dist/data/uarch.json.br +0 -0
  21. package/dist/manifest.json +160 -0
  22. package/dist/wuica_asm.wasm.br +0 -0
  23. package/dist/wuica_wasm.wasm.br +0 -0
  24. package/index.d.ts +410 -0
  25. package/lib/archs.js +44 -0
  26. package/lib/cli.js +693 -0
  27. package/lib/core.js +36 -0
  28. package/lib/details.js +60 -0
  29. package/lib/examples.js +26 -0
  30. package/lib/files.js +40 -0
  31. package/lib/index.js +577 -0
  32. package/lib/insights.js +100 -0
  33. package/lib/mcp.js +366 -0
  34. package/lib/objfile.js +216 -0
  35. package/lib/thread-worker.js +49 -0
  36. package/lib/threads.js +235 -0
  37. package/lib/wasm.js +246 -0
  38. package/lib/web/accum.js +202 -0
  39. package/lib/web/asm-regions.js +415 -0
  40. package/lib/web/assembler.js +188 -0
  41. package/lib/web/caveats.js +214 -0
  42. package/lib/web/examples.js +99 -0
  43. package/lib/web/loop-find.js +492 -0
  44. package/lib/web/showcase.js +368 -0
  45. package/lib/whatif.js +136 -0
  46. package/licenses/LICENSE-LLVM.txt +279 -0
  47. package/licenses/LICENSE-XED.txt +178 -0
  48. package/package.json +58 -4
package/lib/cli.js ADDED
@@ -0,0 +1,693 @@
1
+ // The command-line tool: `wuica [options] [FILE | - | HEX]`. Options follow uiCA's and the Rust CLI's (crates/wuica-cli);
2
+ // every flag also takes "--" and "=value" spellings, and flag names are case-insensitive.
3
+
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { createWuica, normalizeHex, listLoops, whatIf, WHAT_IF_VARIANTS, CODES, examples, findExample, objectKind } from './index.js';
7
+
8
+ export const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
9
+
10
+ export const USAGE = `Usage: wuica [options] [FILE | - | HEX]
11
+ wuica [options] FILE FILE... several inputs in one run: one table (-files LIST reads the names from a file)
12
+ wuica mcp start the MCP server (stdio)
13
+
14
+ Predicts the throughput of an x86-64 basic block with uiCA's pipeline model (this is wuica ${VERSION}, a WebAssembly
15
+ port of uiCA). One input per run: assembly from FILE (gcc -S, clang -S, objdump -d output, or a hand-written loop),
16
+ or from stdin if FILE is - or missing. A HEX argument that is not a file (e.g. 4801d84801c349ffcf75f5) is machine code.
17
+ Built-in examples (no file needed): -examples lists them, -example saxpy analyzes one (every option applies),
18
+ -example saxpy -show prints its assembly to save and edit.
19
+
20
+ Input:
21
+ -examples list the built-in examples (name, title, instructions)
22
+ -example NAME analyze a built-in example as if its text were the input file (case-insensitive; with -att
23
+ its AT&T text)
24
+ -show with -example: print its assembly (machine code for sha256) instead of analyzing it
25
+ -files LIST also analyze the files named in LIST, one per line (- reads the names from stdin); with
26
+ several inputs the output is one table (a row per file, or per file and CPU), -TPonly gives
27
+ "file<TAB>[CPU<TAB>]cycles" lines, -json {code, files: [{file, ...as a single run}]}
28
+ -report with several inputs: also uiCA's report of each file
29
+ -att, -intel the assembly's syntax (default: detected from the text: %registers mean AT&T)
30
+ -hex the input is machine code as hex digits (spaces, commas, 0x prefixes allowed)
31
+ -raw FILE read the machine code from a binary file that contains only the code (not an object
32
+ file: for those, objdump -d FILE | wuica)
33
+ -loops list the loops of the assembly (index, label, function, lines, instructions, depth, auto)
34
+ -loop L what is analyzed: auto (default: the deepest loop, among equals the first; clang's
35
+ "Inner Loop Header" notes count), whole (all the text), a loop's index (0-based, as
36
+ -loops lists them) or its label (-loop .LBB0_12)
37
+ -func NAME only the loops of function NAME (with -loop: its index or label among them); in an object
38
+ file its symbol, or a unique part of it
39
+ -funcs list the functions of an object file (name, section, address, size)
40
+ Object files: an ELF or Mach-O x86-64 object, executable or shared object is read directly (wuica dot.o -func dot):
41
+ its code as llvm-objdump -d prints it, the loop at its address.
42
+
43
+ Output:
44
+ -arch NAME microarchitecture (default: SKL; case-insensitive); "all" prints a table for every one,
45
+ a comma-separated list (e.g. SKL,ICL,ZEN3) a table for those
46
+ -list list the microarchitectures (same as -arch list)
47
+ -TPonly print only the throughput (with -per: also cycles per element; with -whatif: one
48
+ "variant cycles" line per variant)
49
+ -per N the loop does N elements (bytes, floats, ...) per iteration: also print cycles per element
50
+ (what-if values too)
51
+ -whatif the what-if variants (unrolled, N accumulators, front end, fusion) per microarchitecture
52
+ -json print the response as JSON
53
+ -trace with -json: include the cycle-by-cycle events (large)
54
+ -details with -json: include the details (allowed ports, latencies, port set, issue slots)
55
+
56
+ Simulation (as in uiCA):
57
+ -alignmentOffset N alignment offset relative to a 64-byte cache line (default: 0; objdump input: from the
58
+ loop's address)
59
+ -initPolicy P initial register state: diff (default), same, stack
60
+ -simpleFrontEnd simulate a front end that is only limited by the issue width
61
+ -noMicroFusion, -noMacroFusion
62
+ -minIterations N simulate at least N iterations (default: 10)
63
+ -minCycles N simulate at least N cycles (default: 500)
64
+
65
+ Other:
66
+ -threads N with several microarchitectures or files: up to N threads (default: the environment variable
67
+ WUICA_THREADS, else by the amount of work: none below about 0.3 s, else 2 to 8; 1 = one
68
+ after another)
69
+ -data DIR directory with uarch.json and arch/*.bin or *.json (default: the tables in the package)
70
+ -h, --help this text
71
+ -v, --version the version (with -json: also the uiCA commit of the data and model)
72
+
73
+ Exit status: 0 ok, 1 bad request or usage, 2 assembler error, 3 the analysis failed for this input; with several
74
+ microarchitectures, the largest of their codes (also the JSON's "code"). A reader that closes the output early
75
+ (| head) does not change it.
76
+
77
+ Throughput is in cycles per iteration of the loop as written (a compiler's unrolled loop does several elements per
78
+ iteration: -per N). A block that ends with a branch is analyzed as a loop, otherwise as if repeated back to back.
79
+ Assumes all data in L1 and no branch mispredictions. "-" in a table means unknown. ZEN3, ADL-P and ICX are
80
+ prototype models (from the fork jtl06/uiCA), less validated than the Intel models of uiCA.`;
81
+
82
+ export const MCP_USAGE = `Usage: wuica-mcp (or: wuica mcp)
83
+
84
+ The wuica MCP server on stdio (JSON-RPC): tools list_archs, analyze, what_if, compare_archs, assemble.
85
+ Configure it in an MCP client as the command "wuica-mcp" (or "npx -y wuica-cli mcp"). Options: --help, --version.
86
+ `;
87
+
88
+ class UsageError extends Error {}
89
+
90
+ // What a bare run on a terminal prints (no input and stdin is a terminal: nothing to read), on stderr, exit 1.
91
+ export const SHORT_USAGE = `wuica: no input. Usage: wuica [options] FILE (assembly, objdump -d output; - or a pipe for stdin)
92
+ wuica loop.s -arch SKL,ZEN3 objdump -d f.o | wuica wuica -examples (built-in loops) wuica -h
93
+ Try: wuica -example saxpy -arch SKL,ZEN3,ADL-P
94
+ `;
95
+
96
+ // A bare run on a terminal: no input argument, no example or binary file, and stdin a terminal (piped stdin is read).
97
+ export function bareTerminalRun(o, stdinIsTTY) {
98
+ return o.input === null && o.files === undefined && o.example === undefined && o.raw === undefined && !o.examples && !!stdinIsTTY;
99
+ }
100
+
101
+ // flag (lower case, without dashes) -> [canonical, takes a value]
102
+ const FLAGS = {
103
+ h: ['help'], help: ['help'], v: ['version'], version: ['version'],
104
+ examples: ['examples'], example: ['example', 1], show: ['show'], files: ['files', 1], report: ['report'], funcs: ['funcs'],
105
+ arch: ['arch', 1], list: ['list'], hex: ['hex'], att: ['att'], intel: ['intel'], raw: ['raw', 1], data: ['data', 1],
106
+ loop: ['loop', 1], loops: ['loops'], func: ['func', 1], per: ['per', 1], whatif: ['whatif'], threads: ['threads', 1],
107
+ tponly: ['tpOnly'], json: ['json'], trace: ['trace'], details: ['details'],
108
+ alignmentoffset: ['alignmentOffset', 1], initpolicy: ['initPolicy', 1], simplefrontend: ['simpleFrontEnd'],
109
+ nomicrofusion: ['noMicroFusion'], nomacrofusion: ['noMacroFusion'], miniterations: ['minIterations', 1], mincycles: ['minCycles', 1],
110
+ };
111
+
112
+ export function parseArgs(argv) {
113
+ const o = { arch: 'SKL', options: {}, input: null, inputs: [], syntax: 'auto' };
114
+ const int = (s, name) => {
115
+ if (!/^-?\d+$/.test(s)) throw new UsageError(`-${name}: not an integer: ${s}`);
116
+ return Number(s);
117
+ };
118
+ for (let i = 0; i < argv.length; i++) {
119
+ const a = argv[i];
120
+ if (!a.startsWith('-') || a === '-') {
121
+ // several inputs: a batch (batch(); o.input is the first)
122
+ o.inputs.push(a);
123
+ o.input ??= a;
124
+ continue;
125
+ }
126
+ const m = /^--?([^=]+)(?:=(.*))?$/.exec(a);
127
+ const f = FLAGS[m[1].toLowerCase()];
128
+ if (!f) throw new UsageError(`unknown option ${a}`);
129
+ const [name, takes] = f;
130
+ let v = m[2];
131
+ if (takes && v === undefined) { if (i + 1 >= argv.length) throw new UsageError(`-${name} needs a value`); v = argv[++i]; }
132
+ if (!takes && v !== undefined) throw new UsageError(`-${name} takes no value`);
133
+ switch (name) {
134
+ case 'att': case 'intel': o.syntax = name; break;
135
+ case 'loop': o.loop = /^\d+$/.test(v) ? Number(v) : v; break;
136
+ case 'per': o.per = Number(v); if (!(o.per > 0)) throw new UsageError(`-per: a positive number of elements per iteration: ${v}`); break;
137
+ case 'threads': o.threads = int(v, name); if (o.threads < 1) throw new UsageError('-threads: at least 1'); break;
138
+ case 'trace': o.options.includeTrace = true; break;
139
+ case 'details': o.options.details = true; break;
140
+ case 'alignmentOffset': case 'minIterations': case 'minCycles': o.options[name] = int(v, name); break;
141
+ case 'initPolicy': o.options.initPolicy = v; break;
142
+ case 'simpleFrontEnd': case 'noMicroFusion': case 'noMacroFusion': o.options[name] = true; break;
143
+ default: o[name] = takes ? v : true;
144
+ }
145
+ }
146
+ o.arch = o.arch.trim();
147
+ if (o.arch.toLowerCase() === 'list') o.list = true;
148
+ // several microarchitectures: all, or a comma-separated list
149
+ if (o.arch.toLowerCase() === 'all') o.archs = [];
150
+ else if (o.arch.includes(',')) {
151
+ o.archs = o.arch.split(',').map((x) => x.trim()).filter((x) => x !== '');
152
+ if (o.archs.length === 0) throw new UsageError(`-arch: no microarchitecture in "${o.arch}"`);
153
+ if (o.archs.some((x) => x.toLowerCase() === 'all')) throw new UsageError('-arch: "all" cannot be part of a list');
154
+ }
155
+ return o;
156
+ }
157
+
158
+ async function readStdin(stdin) {
159
+ const chunks = [];
160
+ for await (const c of stdin) chunks.push(typeof c === 'string' ? Buffer.from(c) : c);
161
+ return Buffer.concat(chunks).toString('utf8');
162
+ }
163
+
164
+ // The format of a file that is not bare machine code, from its first bytes, or null.
165
+ export function binaryFormat(b) {
166
+ const at = (i, ...xs) => xs.every((x, k) => b[i + k] === x);
167
+ if (at(0, 0x7f, 0x45, 0x4c, 0x46)) return 'an ELF file';
168
+ if (at(0, 0xcf, 0xfa, 0xed, 0xfe) || at(0, 0xce, 0xfa, 0xed, 0xfe) || at(0, 0xfe, 0xed, 0xfa, 0xcf) || at(0, 0xfe, 0xed, 0xfa, 0xce) || at(0, 0xca, 0xfe, 0xba, 0xbe)) return 'a Mach-O file';
169
+ if (at(0, 0x21, 0x3c, 0x61, 0x72, 0x63, 0x68, 0x3e, 0x0a)) return 'an archive (.a)';
170
+ if (at(0, 0x4d, 0x5a)) return 'a PE (Windows) executable';
171
+ if (at(0, 0x64, 0x86) && b.length >= 20) return 'a COFF object file';
172
+ return null;
173
+ }
174
+ // mostly printable text
175
+ const looksText = (b) => b.length > 0 && [...b.subarray(0, 4096)].filter((x) => x === 9 || x === 10 || x === 13 || (x >= 32 && x < 127)).length >= 0.95 * Math.min(b.length, 4096);
176
+
177
+ // Reads a file for -raw or as the input: its bytes, or a UsageError that says what is wrong.
178
+ function readFile(file) {
179
+ let st;
180
+ try { st = fs.statSync(file); } catch { throw new UsageError(`no such file: ${file}`); }
181
+ if (st.isDirectory()) throw new UsageError(`${file} is a directory, not a file`);
182
+ return fs.readFileSync(file);
183
+ }
184
+
185
+ // {request: {hex} | {source, syntax}, name: what the diagnostics call it, notes: [stderr lines]}
186
+ async function readInput(o, io, w = null) {
187
+ const notes = [];
188
+ if (o.example !== undefined) {
189
+ if (o.input !== null || o.raw !== undefined) throw new UsageError(`-example and an input (${o.input ?? `-raw ${o.raw}`}) cannot be combined`);
190
+ const e = exampleOf(o.example);
191
+ const syntax = o.syntax === 'att' ? 'att' : 'intel';
192
+ notes.push(`example ${e.name}: ${e.title}${e.intel ? `, ${syntax === 'att' ? 'AT&T' : 'Intel'} syntax` : ', machine code'} (-example ${e.name} -show prints it)`);
193
+ if (!e.intel) return { request: { hex: e.hex }, name: `example ${e.name}`, notes };
194
+ return { request: { source: e[syntax], syntax, ...(o.loop !== undefined ? { loop: o.loop } : {}), ...(o.func ? { func: o.func } : {}) }, name: `example ${e.name}`, notes };
195
+ }
196
+ if (o.raw !== undefined) {
197
+ if (o.input !== null) throw new UsageError(`-raw and an input (${o.input}) cannot be combined`);
198
+ const b = readFile(o.raw);
199
+ const fmt = binaryFormat(b);
200
+ if (fmt) throw new UsageError(`${o.raw} is ${fmt}, not bare machine code: give it without -raw (wuica ${o.raw} reads ELF and Mach-O object files and executables)`);
201
+ if (looksText(b)) notes.push(`warning: ${o.raw} looks like text, not machine code (without -raw it is read as assembly)`);
202
+ return { request: { hex: b.toString('hex') }, name: o.raw, notes };
203
+ }
204
+ let text, name;
205
+ if (o.input === null || o.input === '-') {
206
+ if (o.input === null && io.stdin.isTTY) throw new UsageError('no input');
207
+ text = await readStdin(io.stdin);
208
+ name = '<stdin>';
209
+ } else if (fs.existsSync(o.input)) {
210
+ const b = readFile(o.input);
211
+ name = o.input;
212
+ // an object file or executable: llvm-objdump -d's text of its code (Wuica.disassemble), read as objdump output
213
+ if (objectKind(b) && !o.hex) {
214
+ const d = w.disassemble(new Uint8Array(b.buffer, b.byteOffset, b.byteLength), { name: path.basename(name), func: o.func ?? null });
215
+ if (d.code) throw new UsageError(/^func: /.test(d.error) ? d.error : `${name}: ${d.error}`);
216
+ return { request: { source: d.text, syntax: 'intel', ...(o.loop !== undefined ? { loop: o.loop } : {}), ...(d.func ? { func: d.func } : {}) }, name, notes, object: d };
217
+ }
218
+ text = b.toString('utf8');
219
+ } else if (normalizeHex(o.input) !== null) {
220
+ const n = normalizeHex(o.input).length / 2;
221
+ notes.push(`analyzed: ${n} byte${n === 1 ? '' : 's'} of machine code from the argument "${o.input}" (not a file)`);
222
+ return { request: { hex: o.input }, name: 'the argument', notes };
223
+ } else {
224
+ readFile(o.input); // the error
225
+ }
226
+ if (o.hex) return { request: { hex: text }, name, notes };
227
+ return { request: { source: text, syntax: o.syntax, ...(o.loop !== undefined ? { loop: o.loop } : {}), ...(o.func ? { func: o.func } : {}) }, name, notes };
228
+ }
229
+
230
+ // The -loops table
231
+ function printLoops(ls, out) {
232
+ const lw = Math.max(5, ...ls.map((l) => l.label.length)), fw = Math.max(8, ...ls.map((l) => String(l.function ?? '-').length));
233
+ out.write(`${'#'.padStart(3)} ${'label'.padEnd(lw)} ${'function'.padEnd(fw)} ${'lines'.padEnd(9)} instrs depth\n`);
234
+ for (const l of ls) out.write(`${String(l.index).padStart(3)} ${l.label.padEnd(lw)} ${String(l.function ?? '-').padEnd(fw)} ${`${l.line}-${l.endLine}`.padEnd(9)} ${String(l.instructions).padStart(6)} ${String(l.depth).padStart(5)}${l.auto ? ' auto' : ''}\n`);
235
+ out.write('\n-loop N (0-based) or -loop LABEL analyzes one; "auto" is what runs without -loop.\n');
236
+ }
237
+
238
+ // The built-in example called name, or a UsageError that lists the names.
239
+ function exampleOf(name) {
240
+ const e = findExample(name);
241
+ if (!e) throw new UsageError(`unknown example: ${name} (known: ${examples().map((x) => x.name).join(', ')})`);
242
+ return e;
243
+ }
244
+
245
+ function printExamples(o, out) {
246
+ const list = examples();
247
+ if (o.json) { out.write(JSON.stringify(list.map(({ name, title, group, arch, instructions }) => ({ name, title, group, arch, instructions }))) + '\n'); return; }
248
+ const nw = Math.max(...list.map((e) => e.name.length)), tw = Math.max(...list.map((e) => e.title.length));
249
+ for (const e of list) out.write(`${e.name.padEnd(nw)} ${e.title.padEnd(tw)} ${String(e.instructions).padStart(4)} instructions\n`);
250
+ out.write('\nwuica -example NAME [options] analyzes one; -example NAME -show prints its assembly.\n');
251
+ }
252
+
253
+ const fmt = (x) => Number(x).toFixed(2);
254
+ // cycles per element: 3 significant digits under 0.1 (0.0625, 0.0313), else as fmt
255
+ const fmtEl = (x) => (x !== 0 && Math.abs(x) < 0.1 ? Number(x).toPrecision(3) : fmt(x));
256
+ const MAX_ERRORS = 10;
257
+
258
+ function printList(w, o, out) {
259
+ const archs = w.archs();
260
+ if (o.json) { out.write(JSON.stringify(archs, null, 1) + '\n'); return; }
261
+ const width = Math.max(...archs.map((a) => a.id.length));
262
+ for (const a of archs) out.write(`${a.id.padEnd(width)} ${a.name}${a.year ? ` (${a.year})` : ''}${a.prototype ? ' [prototype]' : ''}\n`);
263
+ }
264
+
265
+ // stderr lines with the input's name for <input>; after MAX_ERRORS errors (each with its source and caret lines), one
266
+ // line for the rest
267
+ function printStderr(r, err, name) {
268
+ let errors = 0, skipping = false;
269
+ const hints = [];
270
+ for (const l of r.stderr ?? []) {
271
+ if (/^hint: /.test(l.text)) { hints.push(l.text); continue; } // last, after the count of the errors left out
272
+ if (l.tag?.severity === 'error') { errors++; skipping = errors > MAX_ERRORS; }
273
+ else if (l.tag) skipping = false;
274
+ if (!skipping) err.write(String(l.text).replace(/^<input>:/, `${name}:`) + '\n');
275
+ }
276
+ if (errors > MAX_ERRORS) err.write(`… and ${errors - MAX_ERRORS} more error${errors - MAX_ERRORS === 1 ? '' : 's'}\n`);
277
+ for (const h of hints) err.write(`${h}\n`);
278
+ }
279
+
280
+ // What of the text was analyzed, the syntax, the other loops; the alignment offset from addresses.
281
+ function printAnalyzed(r, err, o) {
282
+ const p = r.loop;
283
+ const syn = r.syntax ? `${r.syntax === 'att' ? 'AT&T' : 'Intel'} syntax${o.syntax === 'auto' ? ' (detected)' : ''}` : null;
284
+ if (p && p.line) {
285
+ const others = (p.count ?? 1) - (Number.isInteger(p.index) ? 1 : 0);
286
+ err.write(`analyzed: ${p.name} (${o.objectInput ? '' : `lines ${p.line}-${p.endLine}`}${p.function ? `${o.objectInput ? '' : ', '}in ${p.function}` : ''}${p.address !== undefined ? `, address 0x${p.address.toString(16)}` : ''})${syn ? `, ${syn}` : ''}`
287
+ + `${others > 0 ? `; ${others} other loop${others === 1 ? '' : 's'}: -loops lists them, -loop picks one` : ''}; -loop whole for the whole text\n`);
288
+ } else if (syn && r.syntax === 'att' && o.syntax === 'auto') {
289
+ err.write(`analyzed: the whole text, ${syn}; -intel forces Intel\n`);
290
+ }
291
+ if (p && p.alignmentOffset !== undefined && o.options.alignmentOffset === undefined) err.write(`alignment offset ${p.alignmentOffset} (from the addresses)\n`);
292
+ }
293
+
294
+ // The registers a loop advances by a constant and uses in an address or a compare, with what the step counts: "rcx +=
295
+ // 8 per iteration (index; ×4 bytes in [rdi+rcx*4])" (an index register: elements of that size), "r13 += 64 per iteration
296
+ // (bytes; the base of [r13+0x20])", or "(register step)" when no address says (a counter only compared).
297
+ export function inductionSteps(r) {
298
+ if (r?.mode !== 'loop') return [];
299
+ const step = new Map(), other = new Set(), used = new Set(), unit = new Map();
300
+ for (const x of r.rows ?? []) {
301
+ if (x.kind !== 'instr') continue;
302
+ const t = String(x.label).trim().toLowerCase().replace(/\s+/g, ' ');
303
+ const [mn, rest = ''] = t.split(/ (.*)/);
304
+ const ops = rest.split(',').map((s) => s.trim());
305
+ for (const m of t.matchAll(/\[([^\]]*)\]/g)) {
306
+ const regs = m[1].split(/[+-]/).map((p) => p.trim()).filter((p) => /^[a-z]\w*(?:\*\d)?$/.test(p) && !/^0x/.test(p));
307
+ regs.forEach((p, k) => {
308
+ const [reg, scale] = p.split('*');
309
+ used.add(reg);
310
+ if (unit.has(reg)) return;
311
+ // the first register without a scale is the base (bytes); a scaled one is an index (elements of that size)
312
+ if (scale && scale !== '1') unit.set(reg, `index; ×${scale} bytes in [${m[1]}]`);
313
+ else unit.set(reg, k === 0 && !scale ? `bytes; the base of [${m[1]}]` : `bytes; the index of [${m[1]}]`);
314
+ });
315
+ }
316
+ if (mn === 'cmp' || mn === 'test') for (const op of ops) used.add(op);
317
+ const reg = /^(?:r(?:[abcd]x|[sd]i|bp|[89]|1[0-5]))$/.test(ops[0]) ? ops[0] : null;
318
+ if (!reg) continue;
319
+ const imm = /^-?(?:0x[0-9a-f]+|\d+)$/.test(ops[1] ?? '') ? Number(ops[1].startsWith('-') ? -Number(ops[1].slice(1)) : Number(ops[1])) : null;
320
+ if (mn === 'add' && imm !== null) step.set(reg, (step.get(reg) ?? 0) + imm);
321
+ else if (mn === 'sub' && imm !== null) step.set(reg, (step.get(reg) ?? 0) - imm);
322
+ else if (mn === 'inc' && ops.length === 1) step.set(reg, (step.get(reg) ?? 0) + 1);
323
+ else if (mn === 'dec' && ops.length === 1) step.set(reg, (step.get(reg) ?? 0) - 1);
324
+ else if (!['cmp', 'test', 'push', 'bt'].includes(mn)) other.add(reg); // written otherwise
325
+ }
326
+ return [...step].filter(([reg, s]) => s !== 0 && !other.has(reg) && used.has(reg)).map(([reg, s]) => `${reg} ${s < 0 ? '-=' : '+='} ${Math.abs(s)} per iteration (${unit.get(reg) ?? 'register step'})`);
327
+ }
328
+ const stepLine = (steps) => `step: ${steps.join(', ')}; -per N (N elements per iteration): cycles per element\n`;
329
+
330
+ // The diagnosis after the report: the nearest limit when uiCA names no bottleneck, the next limit, the caveats.
331
+ function diagnosis(ins, r) {
332
+ const lines = [];
333
+ if (!ins) return lines;
334
+ if (ins.largest) lines.push(`Bottleneck: unknown (nearest ${ins.largest.join(', ')} ${fmt(Math.max(...r.limits.filter((l) => ins.largest.includes(l.name)).map((l) => l.tp)))}${ins.unexplained ? `; ${fmt(ins.unexplained)} cycles/iteration no single limit explains` : ''})`);
335
+ else if (ins.next && ins.binding.length) lines.push(`Next limit: ${ins.next.limit} ${fmt(ins.next.tp)} (at most ${fmt(ins.next.maxSpeedup)}x faster without ${ins.binding.join(', ')})`);
336
+ for (const c of ins.caveats ?? []) lines.push(`Not modelled: ${c.text}: ${c.title}`);
337
+ return lines;
338
+ }
339
+
340
+ // A what-if result with cycles per element (-per N): elementsPerIteration and perElement on it, perElement on each
341
+ // variant with a tp.
342
+ function whatIfPer(x, per) {
343
+ if (!per || x.code) return x;
344
+ return { ...x, elementsPerIteration: per, perElement: x.tp / per, variants: x.variants.map((v) => (v.tp !== undefined ? { ...v, perElement: v.tp / per } : v)) };
345
+ }
346
+
347
+ const VARIANT_W = 18;
348
+ function whatIfTable(x) {
349
+ const per = x.elementsPerIteration;
350
+ const f = per ? (v) => fmtEl(v / per) : fmt;
351
+ const rows = x.variants.map((v) => (v.error ? ` ${v.label.padEnd(VARIANT_W)} ${'-'.padStart(8)} ${v.error}`
352
+ : ` ${v.label.padEnd(VARIANT_W)} ${`${v.estimate ? '>=' : ''}${f(v.tp)}`.padStart(8)} ${`${v.delta > 0 ? '+' : ''}${f(v.delta)}`.padStart(8)} ${`${fmt(v.speedup ?? 0)}x`.padStart(7)}`));
353
+ return [per ? `What if (${x.arch}), cycles per element (${per} per original iteration; base ${fmtEl(x.tp / per)}):` : `What if (${x.arch}), cycles per original iteration (base ${fmt(x.tp)}):`,
354
+ ` ${'variant'.padEnd(VARIANT_W)} ${'cycles'.padStart(8)} ${'delta'.padStart(8)} ${'speedup'.padStart(7)}`, ...rows,
355
+ ...(x.accumulators ? [` best number of accumulators: ${x.accumulators.best}${x.accumulators.best === 1 ? ' (as it is)' : ''}`] : [])].join('\n') + '\n';
356
+ }
357
+ // -TPonly -whatif: one "variant cycles [per element]" line per variant (prefix: the CPU, with several)
358
+ function whatIfTerse(x, prefix = '') {
359
+ if (x.code) return `${prefix}what-if error: ${x.error}\n`;
360
+ return x.variants.map((v) => `${prefix}${v.id} ${v.error ? 'error' : `${fmt(v.tp)}${v.perElement !== undefined ? ` ${fmtEl(v.perElement)}` : ''}`}\n`).join('');
361
+ }
362
+
363
+ // argv: the arguments after the program name. io: {stdin, stdout, stderr}. Returns the exit code: the result's
364
+ // `code` (0 ok, 1 bad request or usage, 2 assembler error, 3 analysis error).
365
+ export async function main(argv, io = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr }) {
366
+ const { stdout: out, stderr: err } = io;
367
+ let o = null;
368
+ const fail = (code, msg) => {
369
+ if (o?.json) out.write(JSON.stringify({ code, error: msg, stderr: [{ text: msg }] }) + '\n');
370
+ else err.write(`${msg}\n`);
371
+ return code;
372
+ };
373
+ try {
374
+ o = parseArgs(argv);
375
+ if (o.help) { out.write(USAGE + '\n'); return 0; }
376
+ if (o.version) {
377
+ // -json: with the uiCA reference whose data and model this is (dist/manifest.json, from ci/data-asset.txt)
378
+ if (o.json) {
379
+ let uiCA = null;
380
+ try { uiCA = JSON.parse(fs.readFileSync(new URL('../dist/manifest.json', import.meta.url), 'utf8')).uiCA ?? null; } catch { /* not built */ }
381
+ out.write(JSON.stringify({ wuica: VERSION, uiCA, node: process.versions.node }) + '\n');
382
+ } else out.write(`wuica ${VERSION}\n`);
383
+ return 0;
384
+ }
385
+ if (o.examples) { printExamples(o, out); return 0; }
386
+ if (o.show) {
387
+ if (o.example === undefined) throw new UsageError('-show: with -example NAME (prints that example\'s assembly)');
388
+ const e = exampleOf(o.example);
389
+ out.write(e.intel ? e[o.syntax === 'att' ? 'att' : 'intel'] : e.hex.replace(/(.{64})/g, '$1\n').replace(/\n?$/, '\n'));
390
+ if (!e.intel) err.write(`example ${e.name} is machine code: wuica -hex FILE reads it\n`);
391
+ return 0;
392
+ }
393
+ if (bareTerminalRun(o, io.stdin?.isTTY)) { err.write(SHORT_USAGE); return 1; }
394
+ const w = await createWuica({ ...(o.data ? { dataDir: o.data } : {}), ...(o.threads ? { threads: o.threads } : {}) });
395
+ if (o.list) { printList(w, o, out); return 0; }
396
+ // the microarchitectures before the input (stdin is not read for a mistyped name)
397
+ const names = o.archs ?? [o.arch];
398
+ const unknown = names.filter((a) => !w.resolveArch(a));
399
+ if (unknown.length) return fail(CODES.REQUEST, `unknown microarchitecture${unknown.length > 1 ? 's' : ''}: ${unknown.join(', ')} (known: ${w.archs('id').map((a) => a.id).join(', ')})`);
400
+ if (o.options.details && (!o.json || o.archs)) err.write('-details: shown only with -json and one microarchitecture; ignored\n');
401
+ if (o.options.includeTrace && (!o.json || o.archs)) { err.write('-trace: shown only with -json and one microarchitecture; ignored\n'); delete o.options.includeTrace; }
402
+ if (o.inputs.length > 1 || o.files !== undefined) {
403
+ if (o.raw !== undefined) throw new UsageError('-raw: one input per run (not with several inputs)');
404
+ return await batch(w, o, io);
405
+ }
406
+ if (o.report) err.write('-report: with several inputs (one input prints its report anyway); ignored\n');
407
+ const input = await readInput(o, io, w);
408
+ for (const n of input.notes) err.write(`${n}\n`);
409
+ if (input.object) o.objectInput = true;
410
+ if (o.funcs) {
411
+ if (!input.object) return fail(CODES.REQUEST, '-funcs: lists the functions of an object file (for assembly, -loops lists the loops with their functions)');
412
+ const fs_ = input.object.functions;
413
+ if (o.json) { out.write(JSON.stringify({ code: 0, format: input.object.format, functions: fs_ }) + '\n'); return 0; }
414
+ const nw = Math.max(4, ...fs_.map((f) => f.name.length)), sw = Math.max(7, ...fs_.map((f) => f.section.length));
415
+ out.write(`${'name'.padEnd(nw)} ${'section'.padEnd(sw)} ${'address'.padStart(10)} ${'size'.padStart(6)}\n`);
416
+ for (const f of fs_) out.write(`${f.name.padEnd(nw)} ${f.section.padEnd(sw)} ${`0x${f.address.toString(16)}`.padStart(10)} ${String(f.size).padStart(6)}\n`);
417
+ return 0;
418
+ }
419
+ const req = { ...input.request, options: o.options };
420
+
421
+ if (o.loops) {
422
+ if (!req.source) return fail(CODES.REQUEST, '-loops: needs assembly (not machine code)');
423
+ const ls = listLoops(req.source, { func: o.func ?? null });
424
+ if (ls.error) return fail(CODES.REQUEST, ls.error);
425
+ if (o.json) { out.write(JSON.stringify({ code: 0, loops: ls }) + '\n'); return 0; }
426
+ if (!ls.length) { out.write('no loops\n'); return 0; }
427
+ printLoops(ls, out);
428
+ return 0;
429
+ }
430
+ const per = (tp) => (o.per ? tp / o.per : undefined);
431
+ const bound = { analyze: (a, r) => w.analyze(a, r), assemble: (t) => w.assemble(t, 'intel') };
432
+ const whatIfs = async (archs) => {
433
+ const res = {};
434
+ for (const a of archs) res[w.resolveArch(a)] = whatIfPer(await whatIf(bound.analyze, a, req, WHAT_IF_VARIANTS, { assemble: bound.assemble }), o.per);
435
+ return res;
436
+ };
437
+
438
+ if (o.archs) {
439
+ const c = await w.compare({ ...req, ...(o.archs.length ? { archs: o.archs } : {}) });
440
+ const status = c.code || Math.max(0, ...(c.results ?? []).map((r) => r.code));
441
+ if (c.code) {
442
+ if (o.json) { out.write(JSON.stringify(c) + '\n'); return status; }
443
+ printStderr(c, err, input.name);
444
+ return status;
445
+ }
446
+ // the caveats per CPU: one analysis for the instructions, each CPU's configuration (the split-load cost)
447
+ const first = c.results.find((r) => r.code === 0);
448
+ const base = !o.tpOnly && first ? await w.analyze(first.arch, req) : null;
449
+ const insOf = (r) => (base?.code === 0 && r.code === 0 ? w.insights({ ...base, arch: r.arch, tp: r.tp, limits: r.limits, bottlenecks: r.bottlenecks }) : null);
450
+ const extra = c.results.map((r) => ({ ins: insOf(r), per: r.code === 0 ? per(r.tp) : undefined }));
451
+ const wi = o.whatif ? await whatIfs(c.results.filter((r) => r.code === 0).map((r) => r.arch)) : null;
452
+ if (o.json) {
453
+ const results = c.results.map((r, k) => ({ ...r, ...(extra[k].per !== undefined ? { perElement: extra[k].per } : {}), ...(extra[k].ins?.caveats ? { caveats: extra[k].ins.caveats } : {}) }));
454
+ out.write(JSON.stringify({ ...c, code: status, results, ...(wi ? { whatIf: wi } : {}) }) + '\n');
455
+ return status;
456
+ }
457
+ printStderr(c, err, input.name);
458
+ printAnalyzed(c, err, o);
459
+ const kw = Math.max(4, ...c.results.map((r) => r.arch.length));
460
+ const nw = Math.max(5, ...c.results.map((r) => r.name.length));
461
+ const bns = c.results.map((r, k) => (r.code ? `error: ${r.error.split('\n')[0]}` : r.bottlenecks.join(', ') || (extra[k].ins?.largest ? `- (nearest ${extra[k].ins.largest.join(', ')})` : '-')));
462
+ // the Bottlenecks column as wide as its widest entry (an error's message, the last thing on its row, not counted)
463
+ const bw = Math.max(11, ...bns.filter((b, k) => !c.results[k].code).map((b) => b.length));
464
+ if (!o.tpOnly) out.write(`${'Arch'.padEnd(kw)} ${'Model'.padEnd(nw)} Year ${'TP'.padStart(6)}${o.per ? ` ${'per el'.padStart(6)}` : ''} ${'Bottlenecks'.padEnd(bw)} Notes\n`);
465
+ c.results.forEach((r, k) => {
466
+ const { ins, per: pe } = extra[k];
467
+ if (o.tpOnly) {
468
+ out.write(`${r.arch.padEnd(kw)} ${r.code ? 'error' : fmt(r.tp)}${pe !== undefined ? ` ${fmtEl(pe)}` : ''}\n`);
469
+ if (wi?.[r.arch]) out.write(whatIfTerse(wi[r.arch], `${r.arch.padEnd(kw)} `));
470
+ return;
471
+ }
472
+ const year = String(r.year ?? '').padEnd(4);
473
+ const tp = (r.code ? '-' : `${fmt(r.tp)}${r.decodeErrors ? '*' : ''}`).padStart(6);
474
+ const notes = [r.decodeErrors ? `${r.decodeErrors} undecodable (left out)` : null, ...(ins?.caveats ?? []).map((x) => x.text), r.prototype ? '[prototype]' : null].filter(Boolean).join('; ');
475
+ out.write(`${r.arch.padEnd(kw)} ${r.name.padEnd(nw)} ${year} ${tp}${o.per ? ` ${(pe !== undefined ? fmtEl(pe) : '-').padStart(6)}` : ''} ${bns[k].padEnd(bw)}${notes ? ` ${notes}` : ''}`.trimEnd() + '\n');
476
+ });
477
+ if (!o.tpOnly) {
478
+ out.write(`\nTP: cycles per iteration${o.per ? `; per el: per element (${o.per} per iteration)` : ''}. "-": unknown. *: some instructions could not be decoded for that CPU and are left out.\n`);
479
+ if (c.results.some((r) => r.prototype)) out.write('[prototype]: experimental model of the fork jtl06/uiCA.\n');
480
+ if (base?.code === 0 && !o.per) { const s = inductionSteps(base); if (s.length) err.write(stepLine(s)); }
481
+ for (const x of Object.values(wi ?? {})) out.write('\n' + (x.code ? `What if (${x.arch}): ${x.error}\n` : whatIfTable(x)));
482
+ }
483
+ return status;
484
+ }
485
+
486
+ const r = await w.analyze(o.arch, req);
487
+ const ins = r.code === 0 ? w.insights(r) : null;
488
+ const wi = o.whatif && r.code === 0 ? await whatIfs([o.arch]) : null;
489
+ if (o.json) {
490
+ out.write(JSON.stringify(r.code ? r : { ...r, ...(o.per ? { perElement: per(r.tp) } : {}), ...(ins ? { insights: ins } : {}), ...(wi ? { whatIf: wi } : {}) }) + '\n');
491
+ return r.code;
492
+ }
493
+ printStderr(r, err, input.name);
494
+ if (r.code) return r.code;
495
+ printAnalyzed(r, err, o);
496
+ if (o.tpOnly) {
497
+ out.write(`${fmt(r.tp)}${o.per ? ` ${fmtEl(per(r.tp))}` : ''}\n`);
498
+ for (const x of Object.values(wi ?? {})) out.write(whatIfTerse(x));
499
+ return 0;
500
+ }
501
+ // uiCA's "Bottleneck: unknown" line says what is nearest (the diagnosis's first line)
502
+ const d = diagnosis(ins, r);
503
+ let text = r.text;
504
+ if (ins?.largest && /^Bottleneck: unknown$/m.test(text)) text = text.replace(/^Bottleneck: unknown$/m, d.shift());
505
+ out.write(text);
506
+ if (o.per) d.push(`Per element: ${fmtEl(per(r.tp))} cycles (${fmt(r.tp)} cycles/iteration, ${o.per} elements per iteration)`);
507
+ if (d.length) out.write(`\n${d.join('\n')}\n`);
508
+ const steps = !o.per ? inductionSteps(r) : [];
509
+ if (steps.length) err.write(stepLine(steps));
510
+ for (const x of Object.values(wi ?? {})) out.write('\n' + (x.code ? `What if (${x.arch}): ${x.error}\n` : whatIfTable(x)));
511
+ return 0;
512
+ } catch (e) {
513
+ if (e instanceof UsageError) {
514
+ if (e.message === 'no input') { err.write(`${USAGE}\n`); return 1; }
515
+ return o?.json ? fail(1, `wuica: ${e.message}`) : (err.write(`wuica: ${e.message}\nRun "wuica -h" for the options.\n`), 1);
516
+ }
517
+ return fail(1, `wuica: ${e?.message ?? e}`);
518
+ }
519
+ }
520
+
521
+ // ---- several inputs in one run ---------------------------------------------------------------------------------------
522
+ // wuica a.s b.s ... / -files LIST (one path per line; - for stdin): each input as a single run would read it, the
523
+ // analyses of all of them (x the CPUs) as one set of jobs for the threads, the output in input order:
524
+ // text one table: a row per file (one CPU), or a row per file and CPU (several: grouped by file, a CPU column,
525
+ // so that any number of CPUs fits in 80 columns); -report adds uiCA's report per file, -whatif the what-if
526
+ // table per file, each after a "==> FILE <==" line
527
+ // -TPonly tab-separated lines: file, [CPU,] [variant,] cycles [, cycles per element]
528
+ // -json {code, files: [{file, ...}]}: each entry is what a single run prints for that file, with its name
529
+ // The exit status (and the JSON's code) is the largest of the files' statuses.
530
+
531
+ // The input names of a run: the arguments, then those of -files (blank lines and # comments left out).
532
+ async function inputNames(o, io) {
533
+ const names = [...o.inputs];
534
+ if (o.files !== undefined) {
535
+ const text = o.files === '-' ? await readStdin(io.stdin) : readFile(o.files).toString('utf8');
536
+ const listed = text.split(/\r?\n/).map((s) => s.trim()).filter((s) => s && !s.startsWith('#'));
537
+ if (!listed.length) throw new UsageError(`-files ${o.files}: no file names in it`);
538
+ names.push(...listed);
539
+ }
540
+ if (names.filter((n) => n === '-').length + (o.files === '-' ? 1 : 0) > 1) throw new UsageError('stdin (-) can be read only once');
541
+ return names;
542
+ }
543
+
544
+ const STATUS = (r) => r.code || Math.max(0, ...(r.results ?? []).map((x) => x.code));
545
+
546
+ async function batch(w, o, io) {
547
+ const { stdout: out, stderr: err } = io;
548
+ if (o.example !== undefined) throw new UsageError('-example: one input per run (not with several inputs)');
549
+ const names = await inputNames(o, io);
550
+ const items = [];
551
+ for (const name of names) {
552
+ try {
553
+ const input = await readInput({ ...o, input: name }, io, w);
554
+ for (const n of input.notes) err.write(`${name}: ${n}\n`);
555
+ items.push({ name, req: { ...input.request, options: o.options } });
556
+ } catch (e) {
557
+ if (!(e instanceof UsageError)) throw e;
558
+ items.push({ name, failure: { code: CODES.REQUEST, error: e.message, stderr: [{ text: e.message }] } });
559
+ }
560
+ }
561
+ const good = items.filter((x) => x.req);
562
+
563
+ if (o.loops) {
564
+ let worst = 0;
565
+ const docs = [];
566
+ for (const it of items) {
567
+ const ls = it.failure ? it.failure : !it.req.source ? { error: '-loops: needs assembly (not machine code)' } : listLoops(it.req.source, { func: o.func ?? null });
568
+ const code = ls.error ? CODES.REQUEST : 0;
569
+ worst = Math.max(worst, code);
570
+ if (o.json) { docs.push({ file: it.name, ...(ls.error ? { code, error: ls.error, stderr: [{ text: ls.error }] } : { code: 0, loops: ls }) }); continue; }
571
+ out.write(`==> ${it.name} <==\n`);
572
+ if (ls.error) err.write(`${it.name}: ${ls.error}\n`);
573
+ else if (!ls.length) out.write('no loops\n');
574
+ else printLoops(ls, out);
575
+ }
576
+ if (o.json) out.write(JSON.stringify({ code: worst, files: docs }) + '\n');
577
+ return worst;
578
+ }
579
+
580
+ const per = (tp) => (o.per ? tp / o.per : undefined);
581
+ const bound = { analyze: (a, r) => w.analyze(a, r), assemble: (t) => w.assemble(t, 'intel') };
582
+ const whatIfs = async (req, archs) => {
583
+ const res = {};
584
+ for (const a of archs) res[w.resolveArch(a)] = whatIfPer(await whatIf(bound.analyze, a, req, WHAT_IF_VARIANTS, { assemble: bound.assemble }), o.per);
585
+ return res;
586
+ };
587
+ const docs = new Map(); // item -> {doc (as a single run's JSON), status, rows: [{cpu, tp, pe, bn, notes, code}], report, wi}
588
+
589
+ if (!o.archs) {
590
+ const rs = await w.analyzeMany(o.arch, good.map((x) => x.req));
591
+ for (const [k, it] of good.entries()) {
592
+ const r = rs[k];
593
+ const ins = r.code === 0 ? w.insights(r) : null;
594
+ const wi = o.whatif && r.code === 0 ? await whatIfs(it.req, [o.arch]) : null;
595
+ const doc = r.code ? r : { ...r, ...(o.per ? { perElement: per(r.tp) } : {}), ...(ins ? { insights: ins } : {}), ...(wi ? { whatIf: wi } : {}) };
596
+ docs.set(it, { doc, status: r.code, r, ins, wi, rows: [rowOf(r, ins, per)] });
597
+ }
598
+ } else {
599
+ const cs = await w.compareMany(good.map((x) => x.req), o.archs.length ? { archs: o.archs } : {});
600
+ // the caveats per CPU: one analysis per file on its first CPU that worked (as a single run does), grouped by that CPU
601
+ const bases = new Array(good.length).fill(null);
602
+ if (!o.tpOnly) {
603
+ const byArch = new Map();
604
+ cs.forEach((c, k) => { const first = c.code ? null : c.results.find((r) => r.code === 0); if (first) (byArch.get(first.arch) ?? byArch.set(first.arch, []).get(first.arch)).push(k); });
605
+ for (const [arch, ks] of byArch) (await w.analyzeMany(arch, ks.map((k) => good[k].req))).forEach((b, j) => { bases[ks[j]] = b; });
606
+ }
607
+ for (const [k, it] of good.entries()) {
608
+ const c = cs[k];
609
+ const status = STATUS(c);
610
+ if (c.code) { docs.set(it, { doc: c, status, rows: [rowOf(c, null, per)] }); continue; }
611
+ const base = bases[k];
612
+ const insOf = (r) => (base?.code === 0 && r.code === 0 ? w.insights({ ...base, arch: r.arch, tp: r.tp, limits: r.limits, bottlenecks: r.bottlenecks }) : null);
613
+ const extra = c.results.map((r) => ({ ins: insOf(r), per: r.code === 0 ? per(r.tp) : undefined }));
614
+ const wi = o.whatif ? await whatIfs(it.req, c.results.filter((r) => r.code === 0).map((r) => r.arch)) : null;
615
+ const results = c.results.map((r, j) => ({ ...r, ...(extra[j].per !== undefined ? { perElement: extra[j].per } : {}), ...(extra[j].ins?.caveats ? { caveats: extra[j].ins.caveats } : {}) }));
616
+ const doc = { ...c, code: status, results, ...(wi ? { whatIf: wi } : {}) };
617
+ docs.set(it, { doc, status, c, wi, rows: c.results.map((r, j) => ({ ...rowOf(r, extra[j].ins, per), cpu: r.arch, prototype: r.prototype })) });
618
+ }
619
+ }
620
+ for (const it of items) if (it.failure) docs.set(it, { doc: it.failure, status: it.failure.code, rows: [rowOf(it.failure, null, per)] });
621
+ const worst = Math.max(0, ...items.map((it) => docs.get(it).status));
622
+
623
+ if (o.json) {
624
+ out.write(JSON.stringify({ code: worst, files: items.map((it) => ({ file: it.name, ...docs.get(it).doc })) }) + '\n');
625
+ return worst;
626
+ }
627
+ // diagnostics: each file's stderr lines, with its name
628
+ for (const it of items) printStderr(prefixed(docs.get(it).doc, it.name), err, it.name);
629
+
630
+ if (o.tpOnly) {
631
+ for (const it of items) {
632
+ const d = docs.get(it);
633
+ for (const row of d.rows) out.write(`${[it.name, ...(o.archs ? [row.cpu ?? '-'] : []), row.code ? 'error' : fmt(row.tp), ...(row.pe !== undefined ? [fmtEl(row.pe)] : [])].join('\t')}\n`);
634
+ for (const [cpu, x] of Object.entries(d.wi ?? {})) {
635
+ if (x.code) { out.write(`${[it.name, ...(o.archs ? [cpu] : []), 'what-if error'].join('\t')}\n`); continue; }
636
+ for (const v of x.variants) out.write(`${[it.name, ...(o.archs ? [cpu] : []), v.id, v.error ? 'error' : fmt(v.tp), ...(v.perElement !== undefined ? [fmtEl(v.perElement)] : [])].join('\t')}\n`);
637
+ }
638
+ }
639
+ return worst;
640
+ }
641
+
642
+ // the table
643
+ const loopOf = (it) => { const d = docs.get(it).doc; return d.code && !d.results ? '-' : d.loop ? (d.loop.name.replace(/^loop /, '') + (d.loop.function ? ` (${d.loop.function})` : '')) : 'as is'; };
644
+ const fw = Math.max(4, ...items.map((it) => it.name.length)), lw = Math.max(4, ...items.map((it) => loopOf(it).length));
645
+ const all = items.flatMap((it) => docs.get(it).rows);
646
+ const cw = o.archs ? Math.max(3, ...all.map((r) => String(r.cpu ?? '-').length)) : 0;
647
+ const bw = Math.max(11, ...all.filter((r) => !r.code).map((r) => r.bn.length));
648
+ out.write(`${'File'.padEnd(fw)} ${'Loop'.padEnd(lw)} ${o.archs ? `${'CPU'.padEnd(cw)} ` : ''}${'TP'.padStart(6)}${o.per ? ` ${'per el'.padStart(6)}` : ''} ${'Bottlenecks'.padEnd(bw)} Notes`.trimEnd() + '\n');
649
+ for (const it of items) {
650
+ docs.get(it).rows.forEach((row, j) => {
651
+ const tp = (row.code ? '-' : `${fmt(row.tp)}${row.decodeErrors ? '*' : ''}`).padStart(6);
652
+ const notes = [...row.notes, row.prototype ? '[prototype]' : null].filter(Boolean).join('; ');
653
+ out.write(`${(j ? '' : it.name).padEnd(fw)} ${(j ? '' : loopOf(it)).padEnd(lw)} ${o.archs ? `${String(row.cpu ?? '-').padEnd(cw)} ` : ''}${tp}${o.per ? ` ${(row.pe !== undefined ? fmtEl(row.pe) : '-').padStart(6)}` : ''} ${row.bn.padEnd(bw)}${notes ? ` ${notes}` : ''}`.trimEnd() + '\n');
654
+ });
655
+ }
656
+ out.write(`\nTP: cycles per iteration${o.archs ? '' : ` on ${w.resolveArch(o.arch)}`}${o.per ? `; per el: per element (${o.per} per iteration)` : ''}. "-": unknown or failed.\n`
657
+ + 'Loop: what was analyzed ("as is": all of it). *: undecodable code left out.\n');
658
+ if (all.some((r) => r.prototype)) out.write('[prototype]: experimental model of the fork jtl06/uiCA.\n');
659
+ if (o.report) {
660
+ for (const it of items) {
661
+ const d = docs.get(it);
662
+ if (d.r?.code === 0) { out.write(`\n==> ${it.name} <==\n${d.r.text}`); continue; }
663
+ if (d.c) for (const r of d.c.results.filter((x) => x.code === 0)) {
664
+ const full = await w.analyze(r.arch, it.req);
665
+ if (full.code === 0) out.write(`\n==> ${it.name} (${r.arch}) <==\n${full.text}`);
666
+ }
667
+ }
668
+ }
669
+ for (const it of items) {
670
+ const wi = docs.get(it).wi;
671
+ if (!wi) continue;
672
+ out.write(`\n==> ${it.name} <==\n`);
673
+ Object.values(wi).forEach((x, k) => out.write((k ? '\n' : '') + (x.code ? `What if (${x.arch}): ${x.error}\n` : whatIfTable(x))));
674
+ }
675
+ return worst;
676
+ }
677
+
678
+ // A table row of a result (analyze, a compare() row, or a failure): tp, per element, bottlenecks, notes
679
+ function rowOf(r, ins, per) {
680
+ if (r.code) return { code: r.code, bn: `error: ${String(r.error).split('\n')[0]}`, notes: [] };
681
+ return {
682
+ code: 0, tp: r.tp, pe: per(r.tp), decodeErrors: r.decodeErrors,
683
+ bn: r.bottlenecks.join(', ') || (ins?.largest ? `- (nearest ${ins.largest.join(', ')})` : '-'),
684
+ notes: [r.decodeErrors ? `${r.decodeErrors} undecodable (left out)` : null, ...(ins?.caveats ?? []).map((x) => x.text)].filter(Boolean),
685
+ };
686
+ }
687
+
688
+ // a result's stderr lines, those without the input's name (warnings of the whole input) with it in front
689
+ function prefixed(doc, name) {
690
+ const lines = doc.stderr ?? [];
691
+ const alone = lines.length === 1 && !lines[0].tag; // a failure's one line (no such file, ...)
692
+ return { stderr: lines.map((l) => ((alone || /^Warning\b/.test(l.text)) && !l.text.startsWith(`${name}:`) ? { ...l, text: `${name}: ${l.text}` } : l)) };
693
+ }