wuica-cli 0.1.7 → 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 (46) hide show
  1. package/README.md +140 -30
  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/manifest.json +140 -61
  18. package/dist/wuica_wasm.wasm.br +0 -0
  19. package/index.d.ts +41 -3
  20. package/lib/cli.js +280 -17
  21. package/lib/examples.js +26 -0
  22. package/lib/files.js +25 -3
  23. package/lib/index.js +131 -28
  24. package/lib/objfile.js +216 -0
  25. package/lib/thread-worker.js +8 -5
  26. package/lib/threads.js +32 -21
  27. package/lib/wasm.js +30 -5
  28. package/lib/web/caveats.js +8 -0
  29. package/lib/web/examples.js +99 -0
  30. package/lib/web/showcase.js +368 -0
  31. package/package.json +1 -1
  32. package/dist/data/arch/ADL-P.json.br +0 -0
  33. package/dist/data/arch/BDW.json.br +0 -0
  34. package/dist/data/arch/CFL.json.br +0 -0
  35. package/dist/data/arch/CLX.json.br +0 -0
  36. package/dist/data/arch/HSW.json.br +0 -0
  37. package/dist/data/arch/ICL.json.br +0 -0
  38. package/dist/data/arch/ICX.json.br +0 -0
  39. package/dist/data/arch/IVB.json.br +0 -0
  40. package/dist/data/arch/KBL.json.br +0 -0
  41. package/dist/data/arch/RKL.json.br +0 -0
  42. package/dist/data/arch/SKL.json.br +0 -0
  43. package/dist/data/arch/SKX.json.br +0 -0
  44. package/dist/data/arch/SNB.json.br +0 -0
  45. package/dist/data/arch/TGL.json.br +0 -0
  46. package/dist/data/arch/ZEN3.json.br +0 -0
package/lib/cli.js CHANGED
@@ -2,18 +2,30 @@
2
2
  // every flag also takes "--" and "=value" spellings, and flag names are case-insensitive.
3
3
 
4
4
  import fs from 'node:fs';
5
- import { createWuica, normalizeHex, listLoops, whatIf, WHAT_IF_VARIANTS, CODES } from './index.js';
5
+ import path from 'node:path';
6
+ import { createWuica, normalizeHex, listLoops, whatIf, WHAT_IF_VARIANTS, CODES, examples, findExample, objectKind } from './index.js';
6
7
 
7
8
  export const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
8
9
 
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)
10
12
  wuica mcp start the MCP server (stdio)
11
13
 
12
14
  Predicts the throughput of an x86-64 basic block with uiCA's pipeline model (this is wuica ${VERSION}, a WebAssembly
13
15
  port of uiCA). One input per run: assembly from FILE (gcc -S, clang -S, objdump -d output, or a hand-written loop),
14
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.
15
19
 
16
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
17
29
  -att, -intel the assembly's syntax (default: detected from the text: %registers mean AT&T)
18
30
  -hex the input is machine code as hex digits (spaces, commas, 0x prefixes allowed)
19
31
  -raw FILE read the machine code from a binary file that contains only the code (not an object
@@ -22,7 +34,11 @@ Input:
22
34
  -loop L what is analyzed: auto (default: the deepest loop, among equals the first; clang's
23
35
  "Inner Loop Header" notes count), whole (all the text), a loop's index (0-based, as
24
36
  -loops lists them) or its label (-loop .LBB0_12)
25
- -func NAME only the loops of function NAME (with -loop: its index or label among them)
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.
26
42
 
27
43
  Output:
28
44
  -arch NAME microarchitecture (default: SKL; case-insensitive); "all" prints a table for every one,
@@ -47,9 +63,10 @@ Simulation (as in uiCA):
47
63
  -minCycles N simulate at least N cycles (default: 500)
48
64
 
49
65
  Other:
50
- -threads N with several microarchitectures: analyze them on up to N threads (default: the environment
51
- variable WUICA_THREADS, else one thread per two microarchitectures; 1 = one after another)
52
- -data DIR directory with uarch.json and arch/*.json (default: the tables in the package)
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)
53
70
  -h, --help this text
54
71
  -v, --version the version (with -json: also the uiCA commit of the data and model)
55
72
 
@@ -70,9 +87,21 @@ Configure it in an MCP client as the command "wuica-mcp" (or "npx -y wuica-cli m
70
87
 
71
88
  class UsageError extends Error {}
72
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
+
73
101
  // flag (lower case, without dashes) -> [canonical, takes a value]
74
102
  const FLAGS = {
75
103
  h: ['help'], help: ['help'], v: ['version'], version: ['version'],
104
+ examples: ['examples'], example: ['example', 1], show: ['show'], files: ['files', 1], report: ['report'], funcs: ['funcs'],
76
105
  arch: ['arch', 1], list: ['list'], hex: ['hex'], att: ['att'], intel: ['intel'], raw: ['raw', 1], data: ['data', 1],
77
106
  loop: ['loop', 1], loops: ['loops'], func: ['func', 1], per: ['per', 1], whatif: ['whatif'], threads: ['threads', 1],
78
107
  tponly: ['tpOnly'], json: ['json'], trace: ['trace'], details: ['details'],
@@ -81,7 +110,7 @@ const FLAGS = {
81
110
  };
82
111
 
83
112
  export function parseArgs(argv) {
84
- const o = { arch: 'SKL', options: {}, input: null, syntax: 'auto' };
113
+ const o = { arch: 'SKL', options: {}, input: null, inputs: [], syntax: 'auto' };
85
114
  const int = (s, name) => {
86
115
  if (!/^-?\d+$/.test(s)) throw new UsageError(`-${name}: not an integer: ${s}`);
87
116
  return Number(s);
@@ -89,8 +118,9 @@ export function parseArgs(argv) {
89
118
  for (let i = 0; i < argv.length; i++) {
90
119
  const a = argv[i];
91
120
  if (!a.startsWith('-') || a === '-') {
92
- if (o.input !== null) throw new UsageError(`more than one input: ${o.input}, ${a} (one input per run)`);
93
- o.input = a;
121
+ // several inputs: a batch (batch(); o.input is the first)
122
+ o.inputs.push(a);
123
+ o.input ??= a;
94
124
  continue;
95
125
  }
96
126
  const m = /^--?([^=]+)(?:=(.*))?$/.exec(a);
@@ -153,13 +183,21 @@ function readFile(file) {
153
183
  }
154
184
 
155
185
  // {request: {hex} | {source, syntax}, name: what the diagnostics call it, notes: [stderr lines]}
156
- async function readInput(o, io) {
186
+ async function readInput(o, io, w = null) {
157
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
+ }
158
196
  if (o.raw !== undefined) {
159
197
  if (o.input !== null) throw new UsageError(`-raw and an input (${o.input}) cannot be combined`);
160
198
  const b = readFile(o.raw);
161
199
  const fmt = binaryFormat(b);
162
- if (fmt) throw new UsageError(`${o.raw} is ${fmt}, not bare machine code: disassemble it and pipe the listing (objdump -d ${o.raw} | wuica)`);
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)`);
163
201
  if (looksText(b)) notes.push(`warning: ${o.raw} looks like text, not machine code (without -raw it is read as assembly)`);
164
202
  return { request: { hex: b.toString('hex') }, name: o.raw, notes };
165
203
  }
@@ -169,8 +207,15 @@ async function readInput(o, io) {
169
207
  text = await readStdin(io.stdin);
170
208
  name = '<stdin>';
171
209
  } else if (fs.existsSync(o.input)) {
172
- text = readFile(o.input).toString('utf8');
210
+ const b = readFile(o.input);
173
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');
174
219
  } else if (normalizeHex(o.input) !== null) {
175
220
  const n = normalizeHex(o.input).length / 2;
176
221
  notes.push(`analyzed: ${n} byte${n === 1 ? '' : 's'} of machine code from the argument "${o.input}" (not a file)`);
@@ -182,6 +227,29 @@ async function readInput(o, io) {
182
227
  return { request: { source: text, syntax: o.syntax, ...(o.loop !== undefined ? { loop: o.loop } : {}), ...(o.func ? { func: o.func } : {}) }, name, notes };
183
228
  }
184
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
+
185
253
  const fmt = (x) => Number(x).toFixed(2);
186
254
  // cycles per element: 3 significant digits under 0.1 (0.0625, 0.0313), else as fmt
187
255
  const fmtEl = (x) => (x !== 0 && Math.abs(x) < 0.1 ? Number(x).toPrecision(3) : fmt(x));
@@ -215,7 +283,7 @@ function printAnalyzed(r, err, o) {
215
283
  const syn = r.syntax ? `${r.syntax === 'att' ? 'AT&T' : 'Intel'} syntax${o.syntax === 'auto' ? ' (detected)' : ''}` : null;
216
284
  if (p && p.line) {
217
285
  const others = (p.count ?? 1) - (Number.isInteger(p.index) ? 1 : 0);
218
- err.write(`analyzed: ${p.name} (lines ${p.line}-${p.endLine}${p.function ? `, in ${p.function}` : ''}${p.address !== undefined ? `, address 0x${p.address.toString(16)}` : ''})${syn ? `, ${syn}` : ''}`
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}` : ''}`
219
287
  + `${others > 0 ? `; ${others} other loop${others === 1 ? '' : 's'}: -loops lists them, -loop picks one` : ''}; -loop whole for the whole text\n`);
220
288
  } else if (syn && r.syntax === 'att' && o.syntax === 'auto') {
221
289
  err.write(`analyzed: the whole text, ${syn}; -intel forces Intel\n`);
@@ -314,6 +382,15 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
314
382
  } else out.write(`wuica ${VERSION}\n`);
315
383
  return 0;
316
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; }
317
394
  const w = await createWuica({ ...(o.data ? { dataDir: o.data } : {}), ...(o.threads ? { threads: o.threads } : {}) });
318
395
  if (o.list) { printList(w, o, out); return 0; }
319
396
  // the microarchitectures before the input (stdin is not read for a mistyped name)
@@ -322,8 +399,23 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
322
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(', ')})`);
323
400
  if (o.options.details && (!o.json || o.archs)) err.write('-details: shown only with -json and one microarchitecture; ignored\n');
324
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; }
325
- const input = await readInput(o, io);
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);
326
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
+ }
327
419
  const req = { ...input.request, options: o.options };
328
420
 
329
421
  if (o.loops) {
@@ -332,10 +424,7 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
332
424
  if (ls.error) return fail(CODES.REQUEST, ls.error);
333
425
  if (o.json) { out.write(JSON.stringify({ code: 0, loops: ls }) + '\n'); return 0; }
334
426
  if (!ls.length) { out.write('no loops\n'); return 0; }
335
- const lw = Math.max(5, ...ls.map((l) => l.label.length)), fw = Math.max(8, ...ls.map((l) => String(l.function ?? '-').length));
336
- out.write(`${'#'.padStart(3)} ${'label'.padEnd(lw)} ${'function'.padEnd(fw)} ${'lines'.padEnd(9)} instrs depth\n`);
337
- 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`);
338
- out.write('\n-loop N (0-based) or -loop LABEL analyzes one; "auto" is what runs without -loop.\n');
427
+ printLoops(ls, out);
339
428
  return 0;
340
429
  }
341
430
  const per = (tp) => (o.per ? tp / o.per : undefined);
@@ -428,3 +517,177 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
428
517
  return fail(1, `wuica: ${e?.message ?? e}`);
429
518
  }
430
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
+ }
@@ -0,0 +1,26 @@
1
+ // The built-in examples: the web page's set (web/js/examples.js, copied to lib/web with the other shared files, so the
2
+ // page and the package cannot drift): the basics, the classic loops and the SHA-256 showcase (machine code only: its
3
+ // assembly, about 60 KB, stays on the page). Not the mock engine's entries.
4
+
5
+ import { EXAMPLES, CLASSIC_EXAMPLES, SHOWCASE_EXAMPLES } from './web/examples.js';
6
+
7
+ const GROUPS = [['basics', EXAMPLES], ['classic', CLASSIC_EXAMPLES], ['showcase', SHOWCASE_EXAMPLES]];
8
+
9
+ // [{name, title, group, arch, instructions, hex, intel?, att?}]: arch is the CPU the page shows it on first; intel and
10
+ // att the assembly (absent for the showcase, which is machine code only).
11
+ const LIST = Object.freeze(GROUPS.flatMap(([group, list]) => list.map((e) => {
12
+ const asm = typeof e.text.intel === 'string';
13
+ // the instructions: the lines of the listing (32-byte lines for the showcase: its title says how many)
14
+ const instructions = asm ? e.text.hex.trim().split('\n').length : Number(/([\d,]+) instr/.exec(e.title)?.[1].replace(/,/g, '') ?? 0);
15
+ return Object.freeze({ name: e.id, title: e.title, group, arch: e.arch, instructions, hex: e.hex, ...(asm ? { intel: e.text.intel, att: e.text.att } : {}) });
16
+ })));
17
+
18
+ export function examples() {
19
+ return LIST;
20
+ }
21
+
22
+ // The example called `name` (case-insensitive), or null.
23
+ export function findExample(name) {
24
+ const n = String(name ?? '').toLowerCase();
25
+ return LIST.find((e) => e.name.toLowerCase() === n) ?? null;
26
+ }
package/lib/files.js CHANGED
@@ -1,18 +1,40 @@
1
1
  // Reading the package's files (shared by the library and its worker threads).
2
2
 
3
3
  import fs from 'node:fs/promises';
4
+ import { readFileSync, existsSync } from 'node:fs';
5
+ import path from 'node:path';
4
6
  import zlib from 'node:zlib';
5
7
  import { promisify } from 'node:util';
6
8
 
7
9
  const brotli = promisify(zlib.brotliDecompress);
10
+ // a Uint8Array view of a Buffer (new Uint8Array(buffer) would copy it)
11
+ const view = (b) => new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
8
12
 
9
13
  // Reads a file; `.br` files are decompressed. For a path without `.br`, `<path>.br` is tried first.
10
14
  export async function readMaybeCompressed(file) {
11
- if (file.endsWith('.br')) return new Uint8Array(await brotli(await fs.readFile(file)));
15
+ if (file.endsWith('.br')) return view(await brotli(await fs.readFile(file)));
12
16
  try {
13
- return new Uint8Array(await brotli(await fs.readFile(file + '.br')));
17
+ return view(await brotli(await fs.readFile(file + '.br')));
14
18
  } catch (e) {
15
19
  if (e.code !== 'ENOENT') throw e;
16
20
  }
17
- return new Uint8Array(await fs.readFile(file));
21
+ return view(await fs.readFile(file));
22
+ }
23
+
24
+ // The file of an instruction table in a data directory: the binary form (<name>.bin, the package's), else the JSON
25
+ // (<name>.json, as tools/export_data.py writes it), each plain or .br.
26
+ export function tableFile(dataDir, name) {
27
+ const bin = path.join(dataDir, 'arch', `${name}.bin`);
28
+ return existsSync(bin) || existsSync(bin + '.br') ? bin : path.join(dataDir, 'arch', `${name}.json`);
29
+ }
30
+
31
+ // The same, synchronously (an analyzer reloads its tables this way after a trap, instead of keeping their bytes).
32
+ export function readMaybeCompressedSync(file) {
33
+ if (file.endsWith('.br')) return view(zlib.brotliDecompressSync(readFileSync(file)));
34
+ try {
35
+ return view(zlib.brotliDecompressSync(readFileSync(file + '.br')));
36
+ } catch (e) {
37
+ if (e.code !== 'ENOENT') throw e;
38
+ }
39
+ return view(readFileSync(file));
18
40
  }