wuica-cli 0.1.7 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +233 -57
  2. package/dist/data/arch/ADL-P.bin.br +0 -0
  3. package/dist/data/arch/BDW.bin.br +0 -0
  4. package/dist/data/arch/CFL.bin.br +0 -0
  5. package/dist/data/arch/CLX.bin.br +0 -0
  6. package/dist/data/arch/HSW.bin.br +0 -0
  7. package/dist/data/arch/ICL.bin.br +0 -0
  8. package/dist/data/arch/ICX.bin.br +0 -0
  9. package/dist/data/arch/IVB.bin.br +0 -0
  10. package/dist/data/arch/KBL.bin.br +0 -0
  11. package/dist/data/arch/RKL.bin.br +0 -0
  12. package/dist/data/arch/SKL.bin.br +0 -0
  13. package/dist/data/arch/SKX.bin.br +0 -0
  14. package/dist/data/arch/SNB.bin.br +0 -0
  15. package/dist/data/arch/TGL.bin.br +0 -0
  16. package/dist/data/arch/ZEN3.bin.br +0 -0
  17. package/dist/data/uarch.json.br +0 -0
  18. package/dist/manifest.json +145 -66
  19. package/dist/wuica_wasm.wasm.br +0 -0
  20. package/index.d.ts +205 -13
  21. package/lib/cli.js +467 -49
  22. package/lib/core.js +9 -1
  23. package/lib/details.js +4 -23
  24. package/lib/examples.js +27 -0
  25. package/lib/files.js +26 -3
  26. package/lib/index.js +228 -42
  27. package/lib/mcp.js +107 -84
  28. package/lib/objfile.js +218 -0
  29. package/lib/thread-worker.js +15 -9
  30. package/lib/threads.js +40 -23
  31. package/lib/wasm.js +42 -11
  32. package/lib/web/ab-diff.js +217 -0
  33. package/lib/web/accum.js +10 -2
  34. package/lib/web/asm-regions.js +24 -17
  35. package/lib/web/asm-tokens.js +357 -0
  36. package/lib/web/assembler.js +36 -6
  37. package/lib/web/block-diff.js +165 -0
  38. package/lib/web/bound-core.js +211 -0
  39. package/lib/web/branch-label.js +155 -0
  40. package/lib/web/caveats.js +115 -3
  41. package/lib/web/details.js +91 -0
  42. package/lib/web/examples.js +103 -0
  43. package/lib/web/loop-find.js +139 -16
  44. package/lib/web/markdown.js +437 -0
  45. package/lib/web/showcase.js +368 -0
  46. package/lib/web/whatif-core.js +339 -0
  47. package/package.json +3 -1
  48. package/dist/data/arch/ADL-P.json.br +0 -0
  49. package/dist/data/arch/BDW.json.br +0 -0
  50. package/dist/data/arch/CFL.json.br +0 -0
  51. package/dist/data/arch/CLX.json.br +0 -0
  52. package/dist/data/arch/HSW.json.br +0 -0
  53. package/dist/data/arch/ICL.json.br +0 -0
  54. package/dist/data/arch/ICX.json.br +0 -0
  55. package/dist/data/arch/IVB.json.br +0 -0
  56. package/dist/data/arch/KBL.json.br +0 -0
  57. package/dist/data/arch/RKL.json.br +0 -0
  58. package/dist/data/arch/SKL.json.br +0 -0
  59. package/dist/data/arch/SKX.json.br +0 -0
  60. package/dist/data/arch/SNB.json.br +0 -0
  61. package/dist/data/arch/TGL.json.br +0 -0
  62. package/dist/data/arch/ZEN3.json.br +0 -0
  63. package/lib/insights.js +0 -100
  64. package/lib/whatif.js +0 -136
package/lib/cli.js CHANGED
@@ -2,27 +2,49 @@
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, WHAT_IF_OPT_IN_VARIANTS, CODES, examples, findExample, objectKind, markdown } from './index.js';
7
+ import { analyzedLines } from './web/branch-label.js';
8
+ import { whatIfPerElement, whatIfText } from './web/whatif-core.js';
9
+ import { diffAnalyses, diffMarkdown, diffText } from './web/block-diff.js';
6
10
 
7
11
  export const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
8
12
 
9
13
  export const USAGE = `Usage: wuica [options] [FILE | - | HEX]
14
+ wuica diff [options] A B two blocks (files, - or hex) on one CPU: throughput, bottlenecks, ports, instructions
15
+ changed; -per N or -per A,B (per element), -md, -json, -arch NAME, -loop, the options
16
+ wuica [options] FILE FILE... several inputs in one run: one table (-files LIST reads the names from a file)
10
17
  wuica mcp start the MCP server (stdio)
11
18
 
12
19
  Predicts the throughput of an x86-64 basic block with uiCA's pipeline model (this is wuica ${VERSION}, a WebAssembly
13
- port of uiCA). One input per run: assembly from FILE (gcc -S, clang -S, objdump -d output, or a hand-written loop),
14
- or from stdin if FILE is - or missing. A HEX argument that is not a file (e.g. 4801d84801c349ffcf75f5) is machine code.
20
+ port of uiCA). Input: assembly from FILE (gcc -S, clang -S, objdump -d or -dS, perf annotate --stdio, a hand-written
21
+ loop), or stdin if FILE is - or missing; several FILEs: one table. A HEX argument that is not a file is machine code.
22
+ Built-in examples (no file needed): -examples lists them, -example saxpy analyzes one (every option applies),
23
+ -example saxpy -show prints its assembly to save and edit.
15
24
 
16
25
  Input:
26
+ -examples list the built-in examples (name, title, instructions)
27
+ -example NAME analyze a built-in example as if its text were the input file (case-insensitive; with -att
28
+ its AT&T text)
29
+ -show with -example: print its assembly (machine code for sha256) instead of analyzing it
30
+ -files LIST also analyze the files named in LIST, one per line (- reads the names from stdin); with
31
+ several inputs the output is one table (a row per file, or per file and CPU), -TPonly gives
32
+ "file<TAB>[CPU<TAB>]cycles" lines, -json {code, files: [{file, ...as a single run}]}
33
+ -report with several inputs: also uiCA's report of each file
17
34
  -att, -intel the assembly's syntax (default: detected from the text: %registers mean AT&T)
18
35
  -hex the input is machine code as hex digits (spaces, commas, 0x prefixes allowed)
19
36
  -raw FILE read the machine code from a binary file that contains only the code (not an object
20
37
  file: for those, objdump -d FILE | wuica)
21
38
  -loops list the loops of the assembly (index, label, function, lines, instructions, depth, auto)
22
39
  -loop L what is analyzed: auto (default: the deepest loop, among equals the first; clang's
23
- "Inner Loop Header" notes count), whole (all the text), a loop's index (0-based, as
40
+ "Inner Loop Header" notes count; perf annotate: the loop with the most samples of its
41
+ own), whole (all the text), a loop's index (0-based, as
24
42
  -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)
43
+ -func NAME only the loops of function NAME (with -loop: its index or label among them); in an object
44
+ file its symbol, or a unique part of it
45
+ -funcs list the functions of an object file (name, section, address, size)
46
+ Object files: an ELF or Mach-O x86-64 object, executable or shared object is read directly (wuica dot.o -func dot):
47
+ its code as llvm-objdump -d prints it, the loop at its address.
26
48
 
27
49
  Output:
28
50
  -arch NAME microarchitecture (default: SKL; case-insensitive); "all" prints a table for every one,
@@ -33,6 +55,11 @@ Output:
33
55
  -per N the loop does N elements (bytes, floats, ...) per iteration: also print cycles per element
34
56
  (what-if values too)
35
57
  -whatif the what-if variants (unrolled, N accumulators, front end, fusion) per microarchitecture
58
+ -variants LIST with -whatif (implied): these variants only, comma-separated; also align (the 64 alignment
59
+ offsets: min, median, max, best and worst offset; 64 analyses, not in the default set)
60
+ -md print GitHub-flavoured Markdown instead of the text report (for an issue, a review, a
61
+ chat): the result with its uop table, the CPU table, the what-if and loop tables; not with
62
+ -json or -TPonly
36
63
  -json print the response as JSON
37
64
  -trace with -json: include the cycle-by-cycle events (large)
38
65
  -details with -json: include the details (allowed ports, latencies, port set, issue slots)
@@ -47,9 +74,10 @@ Simulation (as in uiCA):
47
74
  -minCycles N simulate at least N cycles (default: 500)
48
75
 
49
76
  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)
77
+ -threads N with several microarchitectures or files: up to N threads (default: the environment variable
78
+ WUICA_THREADS, else by the amount of work: none below about 0.3 s, else 2 to 8; 1 = one
79
+ after another)
80
+ -data DIR directory with uarch.json and arch/*.bin or *.json (default: the tables in the package)
53
81
  -h, --help this text
54
82
  -v, --version the version (with -json: also the uiCA commit of the data and model)
55
83
 
@@ -64,24 +92,40 @@ prototype models (from the fork jtl06/uiCA), less validated than the Intel model
64
92
 
65
93
  export const MCP_USAGE = `Usage: wuica-mcp (or: wuica mcp)
66
94
 
67
- The wuica MCP server on stdio (JSON-RPC): tools list_archs, analyze, what_if, compare_archs, assemble.
95
+ The wuica MCP server on stdio (JSON-RPC): tools list_archs, analyze, what_if, diff_blocks, compare_archs, list_loops,
96
+ assemble.
68
97
  Configure it in an MCP client as the command "wuica-mcp" (or "npx -y wuica-cli mcp"). Options: --help, --version.
69
98
  `;
70
99
 
71
100
  class UsageError extends Error {}
72
101
 
102
+ // What a bare run on a terminal prints (no input and stdin is a terminal: nothing to read), on stderr, exit 1.
103
+ export const SHORT_USAGE = `wuica: no input. Usage: wuica [options] FILE (assembly, objdump -d output; - or a pipe for stdin)
104
+ wuica loop.s -arch SKL,ZEN3 objdump -d f.o | wuica wuica -examples (built-in loops) wuica -h
105
+ Try: wuica -example saxpy -arch SKL,ZEN3,ADL-P
106
+ `;
107
+
108
+ // A bare run on a terminal: no input argument, no example or binary file, and stdin a terminal (piped stdin is read).
109
+ export function bareTerminalRun(o, stdinIsTTY) {
110
+ return o.input === null && o.files === undefined && o.example === undefined && o.raw === undefined && !o.examples && !!stdinIsTTY;
111
+ }
112
+
73
113
  // flag (lower case, without dashes) -> [canonical, takes a value]
74
114
  const FLAGS = {
75
115
  h: ['help'], help: ['help'], v: ['version'], version: ['version'],
116
+ examples: ['examples'], example: ['example', 1], show: ['show'], files: ['files', 1], report: ['report'], funcs: ['funcs'],
76
117
  arch: ['arch', 1], list: ['list'], hex: ['hex'], att: ['att'], intel: ['intel'], raw: ['raw', 1], data: ['data', 1],
77
118
  loop: ['loop', 1], loops: ['loops'], func: ['func', 1], per: ['per', 1], whatif: ['whatif'], threads: ['threads', 1],
78
- tponly: ['tpOnly'], json: ['json'], trace: ['trace'], details: ['details'],
119
+ tponly: ['tpOnly'], json: ['json'], md: ['md'], variants: ['variants', 1], trace: ['trace'], details: ['details'],
79
120
  alignmentoffset: ['alignmentOffset', 1], initpolicy: ['initPolicy', 1], simplefrontend: ['simpleFrontEnd'],
80
121
  nomicrofusion: ['noMicroFusion'], nomacrofusion: ['noMacroFusion'], miniterations: ['minIterations', 1], mincycles: ['minCycles', 1],
81
122
  };
82
123
 
124
+ /** @typedef {Record<string, any> & {arch: string, options: Record<string, any>, input: string | null, inputs: string[], syntax: string}} CliOptions */
125
+ /** @param {string[]} argv @returns {CliOptions} */
83
126
  export function parseArgs(argv) {
84
- const o = { arch: 'SKL', options: {}, input: null, syntax: 'auto' };
127
+ /** @type {CliOptions} */
128
+ const o = { arch: 'SKL', options: {}, input: null, inputs: [], syntax: 'auto' };
85
129
  const int = (s, name) => {
86
130
  if (!/^-?\d+$/.test(s)) throw new UsageError(`-${name}: not an integer: ${s}`);
87
131
  return Number(s);
@@ -89,11 +133,13 @@ export function parseArgs(argv) {
89
133
  for (let i = 0; i < argv.length; i++) {
90
134
  const a = argv[i];
91
135
  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;
136
+ // several inputs: a batch (batch(); o.input is the first)
137
+ o.inputs.push(a);
138
+ o.input ??= a;
94
139
  continue;
95
140
  }
96
141
  const m = /^--?([^=]+)(?:=(.*))?$/.exec(a);
142
+ if (!m) throw new UsageError(`unknown option ${a}`); // "-=x"
97
143
  const f = FLAGS[m[1].toLowerCase()];
98
144
  if (!f) throw new UsageError(`unknown option ${a}`);
99
145
  const [name, takes] = f;
@@ -103,6 +149,15 @@ export function parseArgs(argv) {
103
149
  switch (name) {
104
150
  case 'att': case 'intel': o.syntax = name; break;
105
151
  case 'loop': o.loop = /^\d+$/.test(v) ? Number(v) : v; break;
152
+ case 'variants': {
153
+ o.variants = v.split(',').map((x) => x.trim()).filter(Boolean);
154
+ const known = [...WHAT_IF_VARIANTS, ...WHAT_IF_OPT_IN_VARIANTS];
155
+ if (!o.variants.length) throw new UsageError(`-variants: no variant in "${v}" (known: ${known.join(', ')})`);
156
+ const unknown = o.variants.filter((x) => !known.includes(x));
157
+ if (unknown.length) throw new UsageError(`-variants: unknown variant(s): ${unknown.join(', ')} (known: ${known.join(', ')})`);
158
+ o.whatif = true;
159
+ break;
160
+ }
106
161
  case 'per': o.per = Number(v); if (!(o.per > 0)) throw new UsageError(`-per: a positive number of elements per iteration: ${v}`); break;
107
162
  case 'threads': o.threads = int(v, name); if (o.threads < 1) throw new UsageError('-threads: at least 1'); break;
108
163
  case 'trace': o.options.includeTrace = true; break;
@@ -113,6 +168,7 @@ export function parseArgs(argv) {
113
168
  default: o[name] = takes ? v : true;
114
169
  }
115
170
  }
171
+ if (o.md && (o.json || o.tpOnly)) throw new UsageError(`-md: Markdown instead of the text report; not with ${o.json ? '-json (JSON is its own format)' : '-TPonly (one number per line)'}`);
116
172
  o.arch = o.arch.trim();
117
173
  if (o.arch.toLowerCase() === 'list') o.list = true;
118
174
  // several microarchitectures: all, or a comma-separated list
@@ -153,13 +209,22 @@ function readFile(file) {
153
209
  }
154
210
 
155
211
  // {request: {hex} | {source, syntax}, name: what the diagnostics call it, notes: [stderr lines]}
156
- async function readInput(o, io) {
212
+ /** @param {CliOptions} o @param {any} io @param {any} [w] @returns {Promise<any>} */
213
+ async function readInput(o, io, w = null) {
157
214
  const notes = [];
215
+ if (o.example !== undefined) {
216
+ if (o.input !== null || o.raw !== undefined) throw new UsageError(`-example and an input (${o.input ?? `-raw ${o.raw}`}) cannot be combined`);
217
+ const e = exampleOf(o.example);
218
+ const syntax = o.syntax === 'att' ? 'att' : 'intel';
219
+ notes.push(`example ${e.name}: ${e.title}${e.intel ? `, ${syntax === 'att' ? 'AT&T' : 'Intel'} syntax` : ', machine code'} (-example ${e.name} -show prints it)`);
220
+ if (!e.intel) return { request: { hex: e.hex }, name: `example ${e.name}`, notes };
221
+ return { request: { source: e[syntax], syntax, ...(o.loop !== undefined ? { loop: o.loop } : {}), ...(o.func ? { func: o.func } : {}) }, name: `example ${e.name}`, notes };
222
+ }
158
223
  if (o.raw !== undefined) {
159
224
  if (o.input !== null) throw new UsageError(`-raw and an input (${o.input}) cannot be combined`);
160
225
  const b = readFile(o.raw);
161
226
  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)`);
227
+ 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
228
  if (looksText(b)) notes.push(`warning: ${o.raw} looks like text, not machine code (without -raw it is read as assembly)`);
164
229
  return { request: { hex: b.toString('hex') }, name: o.raw, notes };
165
230
  }
@@ -169,10 +234,17 @@ async function readInput(o, io) {
169
234
  text = await readStdin(io.stdin);
170
235
  name = '<stdin>';
171
236
  } else if (fs.existsSync(o.input)) {
172
- text = readFile(o.input).toString('utf8');
237
+ const b = readFile(o.input);
173
238
  name = o.input;
239
+ // an object file or executable: llvm-objdump -d's text of its code (Wuica.disassemble), read as objdump output
240
+ if (objectKind(b) && !o.hex) {
241
+ const d = w.disassemble(new Uint8Array(b.buffer, b.byteOffset, b.byteLength), { name: path.basename(name), func: o.func ?? null });
242
+ if (d.code) throw new UsageError(/^func: /.test(d.error) ? d.error : `${name}: ${d.error}`);
243
+ return { request: { source: d.text, syntax: 'intel', ...(o.loop !== undefined ? { loop: o.loop } : {}), ...(d.func ? { func: d.func } : {}) }, name, notes, object: d };
244
+ }
245
+ text = b.toString('utf8');
174
246
  } else if (normalizeHex(o.input) !== null) {
175
- const n = normalizeHex(o.input).length / 2;
247
+ const n = String(normalizeHex(o.input)).length / 2;
176
248
  notes.push(`analyzed: ${n} byte${n === 1 ? '' : 's'} of machine code from the argument "${o.input}" (not a file)`);
177
249
  return { request: { hex: o.input }, name: 'the argument', notes };
178
250
  } else {
@@ -182,6 +254,29 @@ async function readInput(o, io) {
182
254
  return { request: { source: text, syntax: o.syntax, ...(o.loop !== undefined ? { loop: o.loop } : {}), ...(o.func ? { func: o.func } : {}) }, name, notes };
183
255
  }
184
256
 
257
+ // The -loops table
258
+ function printLoops(ls, out) {
259
+ const lw = Math.max(5, ...ls.map((l) => l.label.length)), fw = Math.max(8, ...ls.map((l) => String(l.function ?? '-').length));
260
+ out.write(`${'#'.padStart(3)} ${'label'.padEnd(lw)} ${'function'.padEnd(fw)} ${'lines'.padEnd(9)} instrs depth\n`);
261
+ 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`);
262
+ out.write('\n-loop N (0-based) or -loop LABEL analyzes one; "auto" is what runs without -loop.\n');
263
+ }
264
+
265
+ // The built-in example called name, or a UsageError that lists the names.
266
+ function exampleOf(name) {
267
+ const e = findExample(name);
268
+ if (!e) throw new UsageError(`unknown example: ${name} (known: ${examples().map((x) => x.name).join(', ')})`);
269
+ return e;
270
+ }
271
+
272
+ function printExamples(o, out) {
273
+ const list = examples();
274
+ if (o.json) { out.write(JSON.stringify(list.map(({ name, title, group, arch, instructions }) => ({ name, title, group, arch, instructions }))) + '\n'); return; }
275
+ const nw = Math.max(...list.map((e) => e.name.length)), tw = Math.max(...list.map((e) => e.title.length));
276
+ for (const e of list) out.write(`${e.name.padEnd(nw)} ${e.title.padEnd(tw)} ${String(e.instructions).padStart(4)} instructions\n`);
277
+ out.write('\nwuica -example NAME [options] analyzes one; -example NAME -show prints its assembly.\n');
278
+ }
279
+
185
280
  const fmt = (x) => Number(x).toFixed(2);
186
281
  // cycles per element: 3 significant digits under 0.1 (0.0625, 0.0313), else as fmt
187
282
  const fmtEl = (x) => (x !== 0 && Math.abs(x) < 0.1 ? Number(x).toPrecision(3) : fmt(x));
@@ -215,7 +310,7 @@ function printAnalyzed(r, err, o) {
215
310
  const syn = r.syntax ? `${r.syntax === 'att' ? 'AT&T' : 'Intel'} syntax${o.syntax === 'auto' ? ' (detected)' : ''}` : null;
216
311
  if (p && p.line) {
217
312
  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}` : ''}`
313
+ 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
314
  + `${others > 0 ? `; ${others} other loop${others === 1 ? '' : 's'}: -loops lists them, -loop picks one` : ''}; -loop whole for the whole text\n`);
220
315
  } else if (syn && r.syntax === 'att' && o.syntax === 'auto') {
221
316
  err.write(`analyzed: the whole text, ${syn}; -intel forces Intel\n`);
@@ -269,39 +364,47 @@ function diagnosis(ins, r) {
269
364
  return lines;
270
365
  }
271
366
 
272
- // A what-if result with cycles per element (-per N): elementsPerIteration and perElement on it, perElement on each
273
- // variant with a tp.
274
- function whatIfPer(x, per) {
275
- if (!per || x.code) return x;
276
- return { ...x, elementsPerIteration: per, perElement: x.tp / per, variants: x.variants.map((v) => (v.tp !== undefined ? { ...v, perElement: v.tp / per } : v)) };
277
- }
278
-
279
- const VARIANT_W = 18;
280
- function whatIfTable(x) {
281
- const per = x.elementsPerIteration;
282
- const f = per ? (v) => fmtEl(v / per) : fmt;
283
- const rows = x.variants.map((v) => (v.error ? ` ${v.label.padEnd(VARIANT_W)} ${'-'.padStart(8)} ${v.error}`
284
- : ` ${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)}`));
285
- 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)}):`,
286
- ` ${'variant'.padEnd(VARIANT_W)} ${'cycles'.padStart(8)} ${'delta'.padStart(8)} ${'speedup'.padStart(7)}`, ...rows,
287
- ...(x.accumulators ? [` best number of accumulators: ${x.accumulators.best}${x.accumulators.best === 1 ? ' (as it is)' : ''}`] : [])].join('\n') + '\n';
288
- }
367
+ // what-if results per element and as text: web/js/whatif-core.js (shared with the REST API)
368
+ const whatIfPer = whatIfPerElement;
369
+ const whatIfTable = whatIfText;
289
370
  // -TPonly -whatif: one "variant cycles [per element]" line per variant (prefix: the CPU, with several)
290
371
  function whatIfTerse(x, prefix = '') {
291
372
  if (x.code) return `${prefix}what-if error: ${x.error}\n`;
373
+ if (x.unsupported) return `${prefix}what-if: not a result: ${x.unsupported}\n`; // (no variants)
292
374
  return x.variants.map((v) => `${prefix}${v.id} ${v.error ? 'error' : `${fmt(v.tp)}${v.perElement !== undefined ? ` ${fmtEl(v.perElement)}` : ''}`}\n`).join('');
293
375
  }
294
376
 
377
+ // -md: "SKL · Skylake (2015)"
378
+ function archTitle(w, id) {
379
+ const a = w.archs().find((x) => x.id === id);
380
+ return a ? `${id} · ${a.name}${a.year ? ` (${a.year})` : ''}` : id;
381
+ }
382
+ // -md: the analyzed lines of an assembly input, for the branch targets as labels (branch-label.js); null for machine code
383
+ const srcOf = (req, r) => (req.source ? analyzedLines(String(req.source).replace(/\r\n?/g, '\n'), r) : null);
384
+ // -md: the assembly that was analyzed (the loop's lines, or all of the text), for the report's code block; none for
385
+ // machine code or a text longer than MD_CODE_LINES lines
386
+ const MD_CODE_LINES = 200;
387
+ function analyzedCode(req, r) {
388
+ if (!req.source) return null;
389
+ const lines = String(req.source).replace(/\r\n?/g, '\n').split('\n');
390
+ const p = r.loop;
391
+ const part = p && p.line && p.endLine ? lines.slice(p.line - 1, p.endLine) : lines;
392
+ const text = part.join('\n').replace(/^\n+|\s+$/g, '');
393
+ return text && part.length <= MD_CODE_LINES ? text : null;
394
+ }
395
+
295
396
  // argv: the arguments after the program name. io: {stdin, stdout, stderr}. Returns the exit code: the result's
296
397
  // `code` (0 ok, 1 bad request or usage, 2 assembler error, 3 analysis error).
297
398
  export async function main(argv, io = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr }) {
298
399
  const { stdout: out, stderr: err } = io;
299
- let o = null;
400
+ /** @type {CliOptions} */
401
+ let o = /** @type {any} */ (null); // set by parseArgs, first thing (fail() before that: o?.json)
300
402
  const fail = (code, msg) => {
301
403
  if (o?.json) out.write(JSON.stringify({ code, error: msg, stderr: [{ text: msg }] }) + '\n');
302
404
  else err.write(`${msg}\n`);
303
405
  return code;
304
406
  };
407
+ if (argv[0] === 'diff') return diffMain(argv.slice(1), io);
305
408
  try {
306
409
  o = parseArgs(argv);
307
410
  if (o.help) { out.write(USAGE + '\n'); return 0; }
@@ -314,6 +417,15 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
314
417
  } else out.write(`wuica ${VERSION}\n`);
315
418
  return 0;
316
419
  }
420
+ if (o.examples) { printExamples(o, out); return 0; }
421
+ if (o.show) {
422
+ if (o.example === undefined) throw new UsageError('-show: with -example NAME (prints that example\'s assembly)');
423
+ const e = exampleOf(o.example);
424
+ out.write(e.intel ? e[o.syntax === 'att' ? 'att' : 'intel'] : e.hex.replace(/(.{64})/g, '$1\n').replace(/\n?$/, '\n'));
425
+ if (!e.intel) err.write(`example ${e.name} is machine code: wuica -hex FILE reads it\n`);
426
+ return 0;
427
+ }
428
+ if (bareTerminalRun(o, io.stdin?.isTTY)) { err.write(SHORT_USAGE); return 1; }
317
429
  const w = await createWuica({ ...(o.data ? { dataDir: o.data } : {}), ...(o.threads ? { threads: o.threads } : {}) });
318
430
  if (o.list) { printList(w, o, out); return 0; }
319
431
  // the microarchitectures before the input (stdin is not read for a mistyped name)
@@ -322,8 +434,23 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
322
434
  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
435
  if (o.options.details && (!o.json || o.archs)) err.write('-details: shown only with -json and one microarchitecture; ignored\n');
324
436
  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);
437
+ if (o.inputs.length > 1 || o.files !== undefined) {
438
+ if (o.raw !== undefined) throw new UsageError('-raw: one input per run (not with several inputs)');
439
+ return await batch(w, o, io);
440
+ }
441
+ if (o.report) err.write('-report: with several inputs (one input prints its report anyway); ignored\n');
442
+ const input = await readInput(o, io, w);
326
443
  for (const n of input.notes) err.write(`${n}\n`);
444
+ if (input.object) o.objectInput = true;
445
+ if (o.funcs) {
446
+ if (!input.object) return fail(CODES.REQUEST, '-funcs: lists the functions of an object file (for assembly, -loops lists the loops with their functions)');
447
+ const fs_ = input.object.functions;
448
+ if (o.json) { out.write(JSON.stringify({ code: 0, format: input.object.format, functions: fs_ }) + '\n'); return 0; }
449
+ const nw = Math.max(4, ...fs_.map((f) => f.name.length)), sw = Math.max(7, ...fs_.map((f) => f.section.length));
450
+ out.write(`${'name'.padEnd(nw)} ${'section'.padEnd(sw)} ${'address'.padStart(10)} ${'size'.padStart(6)}\n`);
451
+ 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`);
452
+ return 0;
453
+ }
327
454
  const req = { ...input.request, options: o.options };
328
455
 
329
456
  if (o.loops) {
@@ -331,23 +458,21 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
331
458
  const ls = listLoops(req.source, { func: o.func ?? null });
332
459
  if (ls.error) return fail(CODES.REQUEST, ls.error);
333
460
  if (o.json) { out.write(JSON.stringify({ code: 0, loops: ls }) + '\n'); return 0; }
461
+ if (o.md) { out.write(markdown.loops(ls)); return 0; }
334
462
  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');
463
+ printLoops(ls, out);
339
464
  return 0;
340
465
  }
341
466
  const per = (tp) => (o.per ? tp / o.per : undefined);
342
467
  const bound = { analyze: (a, r) => w.analyze(a, r), assemble: (t) => w.assemble(t, 'intel') };
343
468
  const whatIfs = async (archs) => {
344
469
  const res = {};
345
- for (const a of archs) res[w.resolveArch(a)] = whatIfPer(await whatIf(bound.analyze, a, req, WHAT_IF_VARIANTS, { assemble: bound.assemble }), o.per);
470
+ for (const a of archs) res[w.resolveArch(a)] = whatIfPer(await whatIf(bound.analyze, a, req, o.variants ?? WHAT_IF_VARIANTS, { assemble: bound.assemble }), o.per);
346
471
  return res;
347
472
  };
348
473
 
349
474
  if (o.archs) {
350
- const c = await w.compare({ ...req, ...(o.archs.length ? { archs: o.archs } : {}) });
475
+ const c = await w.compare({ ...req, ...(o.archs.length ? { archs: o.archs } : {}), ...(o.per ? { per: o.per } : {}) });
351
476
  const status = c.code || Math.max(0, ...(c.results ?? []).map((r) => r.code));
352
477
  if (c.code) {
353
478
  if (o.json) { out.write(JSON.stringify(c) + '\n'); return status; }
@@ -357,7 +482,7 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
357
482
  // the caveats per CPU: one analysis for the instructions, each CPU's configuration (the split-load cost)
358
483
  const first = c.results.find((r) => r.code === 0);
359
484
  const base = !o.tpOnly && first ? await w.analyze(first.arch, req) : null;
360
- 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);
485
+ const insOf = (r) => (base?.code === 0 && r.code === 0 && !r.unsupported ? w.insights({ ...base, arch: r.arch, tp: r.tp, limits: r.limits, bottlenecks: r.bottlenecks }) : null);
361
486
  const extra = c.results.map((r) => ({ ins: insOf(r), per: r.code === 0 ? per(r.tp) : undefined }));
362
487
  const wi = o.whatif ? await whatIfs(c.results.filter((r) => r.code === 0).map((r) => r.arch)) : null;
363
488
  if (o.json) {
@@ -367,9 +492,16 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
367
492
  }
368
493
  printStderr(c, err, input.name);
369
494
  printAnalyzed(c, err, o);
495
+ if (o.md) {
496
+ const results = c.results.map((r, k) => ({ ...r, ...(extra[k].ins?.caveats ? { caveats: extra[k].ins.caveats } : {}) }));
497
+ out.write(markdown.cpuTable({ ...c, results }, { per: o.per }));
498
+ for (const x of Object.values(wi ?? {})) out.write('\n' + markdown.whatIfAlignment(x));
499
+ if (base?.code === 0 && !o.per) { const s = inductionSteps(base); if (s.length) err.write(stepLine(s)); }
500
+ return status;
501
+ }
370
502
  const kw = Math.max(4, ...c.results.map((r) => r.arch.length));
371
503
  const nw = Math.max(5, ...c.results.map((r) => r.name.length));
372
- 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(', ')})` : '-')));
504
+ const bns = c.results.map((r, k) => (r.code ? `error: ${r.error.split('\n')[0]}` : r.unsupported ? '-' : r.bottlenecks.join(', ') || (extra[k].ins?.largest ? `- (nearest ${extra[k].ins.largest.join(', ')})` : '-')));
373
505
  // the Bottlenecks column as wide as its widest entry (an error's message, the last thing on its row, not counted)
374
506
  const bw = Math.max(11, ...bns.filter((b, k) => !c.results[k].code).map((b) => b.length));
375
507
  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`);
@@ -381,12 +513,12 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
381
513
  return;
382
514
  }
383
515
  const year = String(r.year ?? '').padEnd(4);
384
- const tp = (r.code ? '-' : `${fmt(r.tp)}${r.decodeErrors ? '*' : ''}`).padStart(6);
385
- const notes = [r.decodeErrors ? `${r.decodeErrors} undecodable (left out)` : null, ...(ins?.caveats ?? []).map((x) => x.text), r.prototype ? '[prototype]' : null].filter(Boolean).join('; ');
516
+ const tp = (r.code ? '-' : `${fmt(r.tp)}${r.decodeErrors || r.unsupported ? '*' : ''}`).padStart(6);
517
+ const notes = [r.unsupported ? `not a result: ${r.unsupported}` : null, r.decodeErrors ? `${r.decodeErrors} undecodable (left out)` : null, r.noData ? `${r.noData} without data (cost left out)` : null, ...(ins?.caveats ?? []).map((x) => x.text), r.prototype ? '[prototype]' : null].filter(Boolean).join('; ');
386
518
  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');
387
519
  });
388
520
  if (!o.tpOnly) {
389
- 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`);
521
+ out.write(`\nTP: cycles per iteration${o.per ? `; per el: per element (${o.per} per iteration)` : ''}. "-": unknown. *: not a result: that CPU cannot run some of the code, which its number leaves out.\n`);
390
522
  if (c.results.some((r) => r.prototype)) out.write('[prototype]: experimental model of the fork jtl06/uiCA.\n');
391
523
  if (base?.code === 0 && !o.per) { const s = inductionSteps(base); if (s.length) err.write(stepLine(s)); }
392
524
  for (const x of Object.values(wi ?? {})) out.write('\n' + (x.code ? `What if (${x.arch}): ${x.error}\n` : whatIfTable(x)));
@@ -395,7 +527,7 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
395
527
  }
396
528
 
397
529
  const r = await w.analyze(o.arch, req);
398
- const ins = r.code === 0 ? w.insights(r) : null;
530
+ const ins = r.code === 0 && !r.unsupported ? w.insights(r) : null; // (none for a result its CPU cannot run)
399
531
  const wi = o.whatif && r.code === 0 ? await whatIfs([o.arch]) : null;
400
532
  if (o.json) {
401
533
  out.write(JSON.stringify(r.code ? r : { ...r, ...(o.per ? { perElement: per(r.tp) } : {}), ...(ins ? { insights: ins } : {}), ...(wi ? { whatIf: wi } : {}) }) + '\n');
@@ -404,6 +536,13 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
404
536
  printStderr(r, err, input.name);
405
537
  if (r.code) return r.code;
406
538
  printAnalyzed(r, err, o);
539
+ if (o.md) {
540
+ out.write(markdown.report(r, { arch: archTitle(w, r.arch), per: o.per, insights: ins, src: srcOf(req, r), code: analyzedCode(req, r) }));
541
+ for (const x of Object.values(wi ?? {})) out.write('\n' + markdown.whatIfAlignment(x));
542
+ const steps = !o.per ? inductionSteps(r) : [];
543
+ if (steps.length) err.write(stepLine(steps));
544
+ return 0;
545
+ }
407
546
  if (o.tpOnly) {
408
547
  out.write(`${fmt(r.tp)}${o.per ? ` ${fmtEl(per(r.tp))}` : ''}\n`);
409
548
  for (const x of Object.values(wi ?? {})) out.write(whatIfTerse(x));
@@ -414,6 +553,8 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
414
553
  let text = r.text;
415
554
  if (ins?.largest && /^Bottleneck: unknown$/m.test(text)) text = text.replace(/^Bottleneck: unknown$/m, d.shift());
416
555
  out.write(text);
556
+ if (r.unsupported) d.unshift(`Not a result for ${r.arch}: ${r.unsupported} (the throughput leaves out what it cannot run)`);
557
+ else if (r.noData) d.push(`${r.noData} instruction${r.noData === 1 ? '' : 's'} without data (not in the instruction tables): the throughput leaves their cost out`);
417
558
  if (o.per) d.push(`Per element: ${fmtEl(per(r.tp))} cycles (${fmt(r.tp)} cycles/iteration, ${o.per} elements per iteration)`);
418
559
  if (d.length) out.write(`\n${d.join('\n')}\n`);
419
560
  const steps = !o.per ? inductionSteps(r) : [];
@@ -428,3 +569,280 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
428
569
  return fail(1, `wuica: ${e?.message ?? e}`);
429
570
  }
430
571
  }
572
+
573
+ // ---- wuica diff A B ---------------------------------------------------------------------------------------------------
574
+ // Two blocks (each a file, - for stdin, or hex; object files as for one input) on one microarchitecture (-arch, default
575
+ // SKL): web/js/block-diff.js. -per N (both) or -per A,B: also per element. -md: the Markdown of the page's A–B view;
576
+ // -json: the result object. The other options as for one input (applied to both). Exit status: 0, or the failing side's.
577
+ async function diffMain(argv, io) {
578
+ const { stdout: out, stderr: err } = io;
579
+ /** @type {CliOptions} */
580
+ let o = /** @type {any} */ (null);
581
+ try {
582
+ // -per N or -per A,B (parseArgs takes one number)
583
+ /** @type {number[] | null} */
584
+ let per = null;
585
+ const rest = [];
586
+ for (let i = 0; i < argv.length; i++) {
587
+ const m = /^--?per(?:=(.*))?$/i.exec(argv[i]);
588
+ if (!m) { rest.push(argv[i]); continue; }
589
+ const v = m[1] ?? argv[++i];
590
+ if (v === undefined) throw new UsageError('-per needs a value');
591
+ per = String(v).split(',').map(Number);
592
+ if (per.length === 1) per = [per[0], per[0]];
593
+ if (per.length !== 2 || !per.every((n) => Number.isFinite(n) && n > 0)) throw new UsageError(`-per: elements per iteration, N or A,B: ${v}`);
594
+ }
595
+ o = parseArgs(rest);
596
+ if (o.help) { out.write(USAGE + '\n'); return 0; }
597
+ if (o.md && (o.json || o.tpOnly)) throw new UsageError(`-md: Markdown instead of the text report; not with ${o.json ? '-json (JSON is its own format)' : '-TPonly (one number per line)'}`);
598
+ if (o.inputs.length !== 2) throw new UsageError(`two inputs, A and B (got ${o.inputs.length})`);
599
+ if (o.archs) throw new UsageError('one microarchitecture (-arch NAME)');
600
+ const NOT = { whatif: '-whatif', variants: '-variants', loops: '-loops', funcs: '-funcs', example: '-example', files: '-files', raw: '-raw', tpOnly: '-TPonly', report: '-report' };
601
+ for (const [f, flag] of Object.entries(NOT)) if (o[f] !== undefined && o[f] !== false) throw new UsageError(`${flag} is not available here`);
602
+ if (o.inputs.filter((n) => n === '-').length > 1) throw new UsageError('stdin (-) can be read only once');
603
+ const w = await createWuica({ ...(o.data ? { dataDir: o.data } : {}) });
604
+ if (!w.resolveArch(o.arch)) return failWith(CODES.REQUEST, `unknown microarchitecture: ${o.arch} (known: ${w.archs('id').map((a) => a.id).join(', ')})`);
605
+ const sides = [];
606
+ for (const name of o.inputs) {
607
+ const input = await readInput({ ...o, input: name }, io, w);
608
+ for (const n of input.notes) err.write(`${name}: ${n}\n`);
609
+ sides.push(input);
610
+ }
611
+ const x = await diffAnalyses(w, o.arch, { a: sides[0].request, b: sides[1].request, options: o.options, ...(per ? { per } : {}) });
612
+ if (x.failure) {
613
+ if (o.json) { out.write(JSON.stringify(x.failure) + '\n'); return x.failure.code; }
614
+ // one message: the assembler's positioned lines with the side's file name, else the error (with the side's name
615
+ // when it is one side's)
616
+ const k = /^A: /.test(x.failure.error) ? 0 : /^B: /.test(x.failure.error) ? 1 : -1;
617
+ const tagged = (x.failure.stderr ?? []).some((l) => l.tag);
618
+ if (k >= 0 && tagged) printStderr(x.failure, err, o.inputs[k]);
619
+ else err.write(`${k >= 0 ? o.inputs[k] : 'wuica diff'}: ${String(x.failure.error).replace(/^[AB]: /, '')}\n`);
620
+ return x.failure.code;
621
+ }
622
+ for (const [k, r] of [x.a, x.b].entries()) printStderr(prefixed(r, o.inputs[k]), err, o.inputs[k]);
623
+ if (o.json) { out.write(JSON.stringify(x.result) + '\n'); return 0; }
624
+ out.write(o.md ? diffMarkdown(x, { archTitle: archTitle(w, x.result.arch) }) : `A: ${o.inputs[0]}\nB: ${o.inputs[1]}\n${diffText(x.result)}`);
625
+ return 0;
626
+ } catch (e) {
627
+ if (e instanceof UsageError) return failWith(1, `wuica diff: ${e.message}`);
628
+ return failWith(1, `wuica diff: ${e?.message ?? e}`);
629
+ }
630
+ function failWith(code, msg) {
631
+ if (o?.json) out.write(JSON.stringify({ code, error: msg, stderr: [{ text: msg }] }) + '\n');
632
+ else err.write(`${msg}\n`);
633
+ return code;
634
+ }
635
+ }
636
+
637
+ // ---- several inputs in one run ---------------------------------------------------------------------------------------
638
+ // wuica a.s b.s ... / -files LIST (one path per line; - for stdin): each input as a single run would read it, the
639
+ // analyses of all of them (x the CPUs) as one set of jobs for the threads, the output in input order:
640
+ // text one table: a row per file (one CPU), or a row per file and CPU (several: grouped by file, a CPU column,
641
+ // so that any number of CPUs fits in 80 columns); -report adds uiCA's report per file, -whatif the what-if
642
+ // table per file, each after a "==> FILE <==" line
643
+ // -TPonly tab-separated lines: file, [CPU,] [variant,] cycles [, cycles per element]
644
+ // -json {code, files: [{file, ...}]}: each entry is what a single run prints for that file, with its name
645
+ // The exit status (and the JSON's code) is the largest of the files' statuses.
646
+
647
+ // The input names of a run: the arguments, then those of -files (blank lines and # comments left out).
648
+ async function inputNames(o, io) {
649
+ const names = [...o.inputs];
650
+ if (o.files !== undefined) {
651
+ const text = o.files === '-' ? await readStdin(io.stdin) : readFile(o.files).toString('utf8');
652
+ const listed = text.split(/\r?\n/).map((s) => s.trim()).filter((s) => s && !s.startsWith('#'));
653
+ if (!listed.length) throw new UsageError(`-files ${o.files}: no file names in it`);
654
+ names.push(...listed);
655
+ }
656
+ if (names.filter((n) => n === '-').length + (o.files === '-' ? 1 : 0) > 1) throw new UsageError('stdin (-) can be read only once');
657
+ return names;
658
+ }
659
+
660
+ const STATUS = (r) => r.code || Math.max(0, ...(r.results ?? []).map((x) => x.code));
661
+
662
+ async function batch(w, o, io) {
663
+ const { stdout: out, stderr: err } = io;
664
+ if (o.example !== undefined) throw new UsageError('-example: one input per run (not with several inputs)');
665
+ const names = await inputNames(o, io);
666
+ const items = [];
667
+ for (const name of names) {
668
+ try {
669
+ const input = await readInput({ ...o, input: name }, io, w);
670
+ for (const n of input.notes) err.write(`${name}: ${n}\n`);
671
+ items.push({ name, req: { ...input.request, options: o.options } });
672
+ } catch (e) {
673
+ if (!(e instanceof UsageError)) throw e;
674
+ items.push({ name, failure: { code: CODES.REQUEST, error: e.message, stderr: [{ text: e.message }] } });
675
+ }
676
+ }
677
+ const good = items.filter((x) => x.req);
678
+
679
+ if (o.loops) {
680
+ let worst = 0;
681
+ const docs = [];
682
+ for (const it of items) {
683
+ const ls = it.failure ? it.failure : !it.req.source ? { error: '-loops: needs assembly (not machine code)' } : listLoops(it.req.source, { func: o.func ?? null });
684
+ const code = ls.error ? CODES.REQUEST : 0;
685
+ worst = Math.max(worst, code);
686
+ if (o.json) { docs.push({ file: it.name, ...(ls.error ? { code, error: ls.error, stderr: [{ text: ls.error }] } : { code: 0, loops: ls }) }); continue; }
687
+ if (o.md) {
688
+ out.write(`${it === items[0] ? '' : '\n'}### ${markdown.text(it.name)}\n\n`);
689
+ if (ls.error) err.write(`${it.name}: ${ls.error}\n`);
690
+ out.write(ls.error ? `error: ${markdown.text(ls.error)}\n` : markdown.loops(ls));
691
+ continue;
692
+ }
693
+ out.write(`==> ${it.name} <==\n`);
694
+ if (ls.error) err.write(`${it.name}: ${ls.error}\n`);
695
+ else if (!ls.length) out.write('no loops\n');
696
+ else printLoops(ls, out);
697
+ }
698
+ if (o.json) out.write(JSON.stringify({ code: worst, files: docs }) + '\n');
699
+ return worst;
700
+ }
701
+
702
+ const per = (tp) => (o.per ? tp / o.per : undefined);
703
+ const bound = { analyze: (a, r) => w.analyze(a, r), assemble: (t) => w.assemble(t, 'intel') };
704
+ const whatIfs = async (req, archs) => {
705
+ const res = {};
706
+ for (const a of archs) res[w.resolveArch(a)] = whatIfPer(await whatIf(bound.analyze, a, req, o.variants ?? WHAT_IF_VARIANTS, { assemble: bound.assemble }), o.per);
707
+ return res;
708
+ };
709
+ const docs = new Map(); // item -> {doc (as a single run's JSON), status, rows: [{cpu, tp, pe, bn, notes, code}], report, wi}
710
+
711
+ if (!o.archs) {
712
+ const rs = await w.analyzeMany(o.arch, good.map((x) => x.req));
713
+ for (const [k, it] of good.entries()) {
714
+ const r = rs[k];
715
+ const ins = r.code === 0 ? w.insights(r) : null;
716
+ const wi = o.whatif && r.code === 0 ? await whatIfs(it.req, [o.arch]) : null;
717
+ const doc = r.code ? r : { ...r, ...(o.per ? { perElement: per(r.tp) } : {}), ...(ins ? { insights: ins } : {}), ...(wi ? { whatIf: wi } : {}) };
718
+ docs.set(it, { doc, status: r.code, r, ins, wi, rows: [rowOf(r, ins, per)] });
719
+ }
720
+ } else {
721
+ const cs = await w.compareMany(good.map((x) => x.req), o.archs.length ? { archs: o.archs } : {});
722
+ // the caveats per CPU: one analysis per file on its first CPU that worked (as a single run does), grouped by that CPU
723
+ const bases = new Array(good.length).fill(null);
724
+ if (!o.tpOnly) {
725
+ const byArch = new Map();
726
+ 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); });
727
+ for (const [arch, ks] of byArch) (await w.analyzeMany(arch, ks.map((k) => good[k].req))).forEach((b, j) => { bases[ks[j]] = b; });
728
+ }
729
+ for (const [k, it] of good.entries()) {
730
+ const c = cs[k];
731
+ const status = STATUS(c);
732
+ if (c.code) { docs.set(it, { doc: c, status, rows: [rowOf(c, null, per)] }); continue; }
733
+ const base = bases[k];
734
+ 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);
735
+ const extra = c.results.map((r) => ({ ins: insOf(r), per: r.code === 0 ? per(r.tp) : undefined }));
736
+ const wi = o.whatif ? await whatIfs(it.req, c.results.filter((r) => r.code === 0).map((r) => r.arch)) : null;
737
+ 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 } : {}) }));
738
+ const doc = { ...c, code: status, ...(o.per ? { elementsPerIteration: o.per } : {}), results, ...(wi ? { whatIf: wi } : {}) };
739
+ 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 })) });
740
+ }
741
+ }
742
+ for (const it of items) if (it.failure) docs.set(it, { doc: it.failure, status: it.failure.code, rows: [rowOf(it.failure, null, per)] });
743
+ const worst = Math.max(0, ...items.map((it) => docs.get(it).status));
744
+
745
+ if (o.json) {
746
+ out.write(JSON.stringify({ code: worst, files: items.map((it) => ({ file: it.name, ...docs.get(it).doc })) }) + '\n');
747
+ return worst;
748
+ }
749
+ // diagnostics: each file's stderr lines, with its name
750
+ for (const it of items) printStderr(prefixed(docs.get(it).doc, it.name), err, it.name);
751
+
752
+ if (o.tpOnly) {
753
+ for (const it of items) {
754
+ const d = docs.get(it);
755
+ 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`);
756
+ for (const [cpu, x] of Object.entries(d.wi ?? {})) {
757
+ if (x.code) { out.write(`${[it.name, ...(o.archs ? [cpu] : []), 'what-if error'].join('\t')}\n`); continue; }
758
+ 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`);
759
+ }
760
+ }
761
+ return worst;
762
+ }
763
+
764
+ if (o.md) return batchMarkdown(w, o, out, items, docs, worst);
765
+
766
+ // the table
767
+ 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'; };
768
+ const fw = Math.max(4, ...items.map((it) => it.name.length)), lw = Math.max(4, ...items.map((it) => loopOf(it).length));
769
+ const all = items.flatMap((it) => docs.get(it).rows);
770
+ const cw = o.archs ? Math.max(3, ...all.map((r) => String(r.cpu ?? '-').length)) : 0;
771
+ const bw = Math.max(11, ...all.filter((r) => !r.code).map((r) => r.bn.length));
772
+ 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');
773
+ for (const it of items) {
774
+ docs.get(it).rows.forEach((row, j) => {
775
+ const tp = (row.code ? '-' : `${fmt(row.tp)}${row.decodeErrors || row.unsupported ? '*' : ''}`).padStart(6);
776
+ const notes = [...row.notes, row.prototype ? '[prototype]' : null].filter(Boolean).join('; ');
777
+ 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');
778
+ });
779
+ }
780
+ 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`
781
+ + 'Loop: what was analyzed ("as is": all of it). *: not a result (code left out).\n');
782
+ if (all.some((r) => r.prototype)) out.write('[prototype]: experimental model of the fork jtl06/uiCA.\n');
783
+ if (o.report) {
784
+ for (const it of items) {
785
+ const d = docs.get(it);
786
+ if (d.r?.code === 0) { out.write(`\n==> ${it.name} <==\n${d.r.text}`); continue; }
787
+ if (d.c) for (const r of d.c.results.filter((x) => x.code === 0)) {
788
+ const full = await w.analyze(r.arch, it.req);
789
+ if (full.code === 0) out.write(`\n==> ${it.name} (${r.arch}) <==\n${full.text}`);
790
+ }
791
+ }
792
+ }
793
+ for (const it of items) {
794
+ const wi = docs.get(it).wi;
795
+ if (!wi) continue;
796
+ out.write(`\n==> ${it.name} <==\n`);
797
+ Object.values(wi).forEach((x, k) => out.write((k ? '\n' : '') + (x.code ? `What if (${x.arch}): ${x.error}\n` : whatIfTable(x))));
798
+ }
799
+ return worst;
800
+ }
801
+
802
+ // -md with several inputs: the files x CPUs table (a CPU column also with one CPU), then with -report each file's
803
+ // report, then each file's what-if tables, under a heading per file
804
+ async function batchMarkdown(w, o, out, items, docs, worst) {
805
+ const info = new Map(w.archs().map((a) => [a.id, a]));
806
+ const named = (r) => (r.code || r.name ? r : { ...r, name: info.get(r.arch)?.name ?? '', year: info.get(r.arch)?.year ?? null, prototype: !!info.get(r.arch)?.prototype });
807
+ const rows = items.map((it) => {
808
+ const d = docs.get(it).doc;
809
+ if (d.results) return { file: it.name, result: { ...d, results: d.results.map(named) } };
810
+ if (d.code) return { file: it.name, result: d };
811
+ return { file: it.name, result: { ...named(d), caveats: d.insights?.caveats ?? [] } };
812
+ });
813
+ out.write(markdown.cpuTable(rows, { per: o.per }));
814
+ if (o.report) {
815
+ for (const it of items) {
816
+ const d = docs.get(it);
817
+ if (d.r?.code === 0) { out.write('\n' + markdown.report(d.r, { title: it.name, arch: archTitle(w, d.r.arch), per: o.per, insights: d.ins, src: srcOf(it.req, d.r) })); continue; }
818
+ if (d.c) for (const r of d.c.results.filter((x) => x.code === 0)) {
819
+ const full = await w.analyze(r.arch, it.req);
820
+ if (full.code === 0) out.write('\n' + markdown.report(full, { title: `${it.name} (${r.arch})`, arch: archTitle(w, r.arch), per: o.per, insights: w.insights(full), src: srcOf(it.req, full) }));
821
+ }
822
+ }
823
+ }
824
+ for (const it of items) {
825
+ const wi = docs.get(it).wi;
826
+ if (!wi) continue;
827
+ out.write(`\n### ${markdown.text(it.name)}\n`);
828
+ for (const x of Object.values(wi)) out.write('\n' + markdown.whatIfAlignment(x));
829
+ }
830
+ return worst;
831
+ }
832
+
833
+ // A table row of a result (analyze, a compare() row, or a failure): tp, per element, bottlenecks, notes
834
+ function rowOf(r, ins, per) {
835
+ if (r.code) return { code: r.code, bn: `error: ${String(r.error).split('\n')[0]}`, notes: [] };
836
+ return {
837
+ code: 0, tp: r.tp, pe: per(r.tp), decodeErrors: r.decodeErrors, unsupported: r.unsupported ?? null,
838
+ bn: r.bottlenecks.join(', ') || (ins?.largest ? `- (nearest ${ins.largest.join(', ')})` : '-'),
839
+ notes: [r.unsupported ? `not a result: ${r.unsupported}` : null, r.decodeErrors ? `${r.decodeErrors} undecodable (left out)` : null, r.noData ? `${r.noData} without data (cost left out)` : null, ...(ins?.caveats ?? []).map((x) => x.text)].filter(Boolean),
840
+ };
841
+ }
842
+
843
+ // a result's stderr lines, those without the input's name (warnings of the whole input) with it in front
844
+ function prefixed(doc, name) {
845
+ const lines = doc.stderr ?? [];
846
+ const alone = lines.length === 1 && !lines[0].tag; // a failure's one line (no such file, ...)
847
+ return { stderr: lines.map((l) => ((alone || /^Warning\b/.test(l.text)) && !l.text.startsWith(`${name}:`) ? { ...l, text: `${name}: ${l.text}` } : l)) };
848
+ }