wuica-cli 0.1.10 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,6 +8,9 @@ port's test corpus. The package contains:
8
8
  - a **command-line tool**: `npx wuica-cli loop.s -arch SKL`
9
9
  - a local **MCP server** (stdio) for AI agents: `npx wuica-cli mcp`
10
10
 
11
+ In the browser: [wuica.jacen.li](https://wuica.jacen.li) · source and issues: [github.com/jtl06/wuica](https://github.com/jtl06/wuica) ·
12
+ hosted API: [api.wuica.jacen.li](https://api.wuica.jacen.li)
13
+
11
14
  This is **not the official uiCA** (that is [uiCA.uops.info](https://uiCA.uops.info) and the
12
15
  [uiCA repository](https://github.com/andreas-abel/uiCA)). The instruction data (latencies, throughputs, port usage) comes
13
16
  from [uops.info](https://www.uops.info). Besides uiCA's Intel models (Sandy Bridge to Rocket Lake), wuica includes the
@@ -52,10 +55,35 @@ On an Arm Mac, give clang `--target=x86_64-linux-gnu` (wuica analyzes x86-64 cod
52
55
  in the register's units: `rcx += 8 per iteration (index; ×4 bytes in [rdi+rcx*4])` is 8 elements of 4 bytes,
53
56
  `r13 += 64 per iteration (bytes; the base of [r13+0x20])` is 64 bytes (16 floats: `-per 16`), `(register step)` a
54
57
  counter no address uses.
55
- - **Which loop.** A whole function or file is analyzed at one loop: the deepest one (clang's
56
- `# =>This Inner Loop Header` notes count), among equals the first in the code. That can be a remainder loop: clang
57
- often emits it before the main loop, gcc after it. Stderr says what was picked and how many others there are;
58
- `-loops` lists them (index, label, function, lines, instructions, depth, auto), `-loop N` (0-based) or
58
+ - **Which loop.** A whole function or file is analyzed at one loop, by default (`auto`):
59
+ 1. only the innermost loops at the greatest depth (clang's `# =>This Inner Loop Header` notes count), and of those
60
+ only the ones in the function of the first of them: in a file with several functions the default stays in that
61
+ function (`-func` picks another); and not a remainder of another of them: a loop that continues the counter of an
62
+ earlier loop toward the same bound register after that loop stopped (the earlier loop's only exit is that compare,
63
+ and the counter comes from the register it compares), so it runs less than one of its steps: clang's scalar tail
64
+ of an unrolled loop, even when it has more instructions;
65
+ 2. among those, the one whose vector instructions use the widest registers (zmm, then ymm, then xmm, then none), then
66
+ the one with more vector instructions;
67
+ 3. then the one with more instructions, then the first in the text.
68
+
69
+ A vector instruction is an SSE/AVX/AVX-512 instruction that names an xmm, ymm or zmm register and works on several
70
+ elements. Scalar code uses xmm registers too, so these do not count: scalar floating point (a mnemonic, without its
71
+ `v`, that does not start with `p` and ends in `ss`, `sd` or `sh`: `addss`, `vfmadd231sd`, `movsd`, `cvtsi2sd`, and
72
+ `cvttsd2si`, but not the broadcasts), one element moved to or from a general-purpose register or memory (`movd`,
73
+ `movq`, `pinsr*`, `pextr*`, `insertps`, `extractps`, `movlpd`, `movhpd`), zero idioms (`vxorps xmm0, xmm0, xmm0`),
74
+ register-to-register copies (`movaps xmm1, xmm0`), and `andps`/`andnps`/`orps`/`xorps` (and `pd`) on xmm registers,
75
+ which compilers use for `fabs`, negation and `copysign` of scalars. So a vectorized loop is picked over its scalar
76
+ remainder or peel loop wherever the compiler put them, and a scalar float loop does not beat a larger integer loop for
77
+ touching xmm. The rule can still miss: a vectorized loop with a fixed, small trip count (merging sub-histograms)
78
+ beats the scalar main loop (a small constant trip count is not used against it: in an 8x8 transform the 8-iteration
79
+ loops are the work), a cleanup loop the compiler vectorized and unrolled with a counter of its own can beat a
80
+ hand-written intrinsics loop or a loop unrolled by hand, gcc's vectorized peel loop (`-O3`) can
81
+ beat the main loop, and clang's conversion of a `uint64_t` to `double` without AVX-512 (`vunpcklps`, `vsubpd`, `vshufpd` around a
82
+ `vaddsd`) makes a scalar loop look like a 128-bit vector loop. Without clang's notes (objdump output) a loop with
83
+ several back edges can be found as overlapping loops, so `-S` and objdump of it may differ. Stderr says what was
84
+ picked and how many others there are;
85
+ `-loops` lists them (index, label, function, lines, instructions, depth, auto; for a loop three or more deep in
86
+ clang's notes the list keeps the place it had when only the notes' first two lines were read), `-loop N` (0-based) or
59
87
  `-loop LABEL` picks one, `-func NAME` keeps one function's loops, `-loop whole` analyzes the whole text. A label
60
88
  that names loops in several functions (`1:` … `jnz 1b`) is an error that lists them; `-func` or the index picks one.
61
89
  - **Branches inside the loop.** uiCA runs the analyzed code straight through: in a loop with an if/else (or two back
@@ -66,9 +94,13 @@ On an Arm Mac, give clang `--target=x86_64-linux-gnu` (wuica analyzes x86-64 cod
66
94
  `-raw FILE` (bare machine code).
67
95
  - **Object files.** An ELF or Mach-O x86-64 object, executable or shared object is read directly: its code as
68
96
  `llvm-objdump -d` prints it (decoded by the analyzer), so `wuica dot.o` and `objdump -d dot.o | wuica` pick the same
69
- loop and give the same numbers. `-func NAME` takes the symbol, without Mach-O's `_`, or a unique part of it; `-funcs`
70
- lists the functions; `-loops` gives the loops' addresses; `-ffunction-sections` objects work. An arm64 object (what a
71
- Mac compiles by default) says so and how to compile for x86-64 (`clang -arch x86_64 -c`, or
97
+ loop and give the same numbers. `-func NAME` takes the symbol, without Mach-O's `_`, or a unique part of it, and
98
+ analyzes that function alone (its loop, or its body if it has none); `-funcs` lists the functions; `-loops` gives the
99
+ loops' addresses; `-ffunction-sections` objects work. A name the file gives several functions (static functions of
100
+ different source files, gcc's `.cold` parts: any static executable has them) is listed as `NAME.0xADDR`, with its
101
+ address; `-func NAME` then lists them, and `-func NAME.0xADDR` picks one. Give a large executable a `-func`: with it
102
+ a 2.6 MB static executable takes 0.2 s, without it the whole file is read, which takes minutes and can fail. An
103
+ arm64 object (what a Mac compiles by default) says so and how to compile for x86-64 (`clang -arch x86_64 -c`, or
72
104
  `--target=x86_64-linux-gnu`); COFF is not supported yet (`llvm-objdump -d f.obj | wuica`).
73
105
  - **Several inputs** (`wuica a.s b.s c.o`, a glob, or `-files LIST` with one name per line, `-files -` from stdin):
74
106
  one process for all of them, the analyses spread over the threads. One CPU: a row per file (file, loop, TP,
@@ -144,7 +176,7 @@ markdown.report(r, { insights: w.insights(r) }); // Markdown, as wuica
144
176
  Methods never throw for bad input: they resolve to a failure `{code, error, stderr}` (see the contract below).
145
177
  `createWuica({ dataDir })` reads the tables from another directory (`uarch.json` and the binary `arch/<NAME>.bin`,
146
178
  plain or `.br`; a uiCA export's `arch/<NAME>.json` is converted by `tools/encode-tables.sh IN_DIR OUT_DIR` of the
147
- repository: the analyzer that ships reads no JSON tables). `w.disassemble(bytes)` turns an object file into the text `analyze` reads. TypeScript declarations are included (`index.d.ts`).
179
+ repository: the analyzer that ships reads no JSON tables). `w.disassemble(bytes)` turns an object file into the text `analyze` reads (`{func}`: of that function alone). TypeScript declarations are included (`index.d.ts`).
148
180
 
149
181
  `compare`, `analyzeMany(arch, requests)` and `compareMany(requests, {archs})` analyze on worker threads when the work
150
182
  is worth it: by default the number of threads comes from the work (the tables to load, the analyses and their
@@ -369,13 +401,15 @@ Request:
369
401
  spaces, commas and `0x` are allowed).
370
402
  - `source` is read as the web page reads pasted assembly. `loop` (optional) says what of it is analyzed:
371
403
  - `"auto"` (the default): a whole function (`gcc -S`, `clang -S`, `objdump -d` lines with addresses, with or
372
- without the bytes, Intel or AT&T) is analyzed at its deepest loop (clang's `Inner Loop Header` notes count;
373
- among equals the first in the code, which may be a remainder loop: clang often emits it first). A span that holds a `ret` or another function's label is not a loop (a tail
404
+ without the bytes, Intel or AT&T) is analyzed at its default loop ("Which loop" above: among the deepest innermost
405
+ loops, in the function of the first of them, the widest vector loop, then the one with the most vector instructions,
406
+ then the largest, then the first). A span that holds a `ret` or another function's label is not a loop (a tail
374
407
  call jumping back). A compiler's function without a loop (it has a function label, directives or a
375
408
  prologue/epilogue, and ends in `ret`) is analyzed at its body, without prologue, epilogue and `ret`; a bare snippet
376
409
  such as `add rax, 1` / `ret` is analyzed as typed. A text that is one loop already, or has region markers, is
377
410
  analyzed as it is.
378
- - `"whole"`: the whole text, never a pick; a number: that loop (0-based: deepest first, then in code order); any
411
+ - `"whole"`: the whole text, never a pick; a number: that loop (0-based, in the order `listLoops` and `-loops` list
412
+ them: the deepest innermost first, then in code order; the default need not be 0); any
379
413
  other string: the loop with that label (`".LBB0_12"`, `"0x10"`). `func` (optional) keeps one function's loops.
380
414
  - `syntax` is `"auto"` (the default: detected from the text), `"intel"` or `"att"`; the response's `syntax` says
381
415
  which was used.
Binary file
Binary file
Binary file
Binary file
@@ -1,33 +1,33 @@
1
1
  {
2
2
  "uiCA": {
3
3
  "repository": "https://github.com/jtl06/uiCA",
4
- "commit": "7301b04",
5
- "branch": "improve-r10"
4
+ "commit": "5429430",
5
+ "branch": "improve-r11"
6
6
  },
7
7
  "tables": {
8
8
  "format": "WUICATBL 1",
9
- "sha256": "d1dce7edf3a6e0af263c94ed8712fb11ee8f4572c8685057201d2309e5e24631"
9
+ "sha256": "75f55cc6e568603e1c1f73cff43b1b5ce9d1e4e2af42a18d6b60edc07fa72ce3"
10
10
  },
11
11
  "files": {
12
12
  "wuica_wasm.wasm": {
13
- "size": 3064326,
14
- "sha256": "fe34e612cb5ec9ed7e8c409a63310e8fd4601b8fe95bc8bf23ff17ee3a377559"
13
+ "size": 3104338,
14
+ "sha256": "288d6ff11eb6c80372964644596b6e92c1cffe3cfd064face5184ac50b8de729"
15
15
  },
16
16
  "wuica_asm.wasm": {
17
17
  "size": 3802001,
18
18
  "sha256": "ee66811d0671cdea73176a3670f82816dcbb3cbb1fed13cd7dc2acbb69cb627d"
19
19
  },
20
20
  "data/uarch.json": {
21
- "size": 51885,
22
- "sha256": "cce92ecddac13e6fa90902142a9e6cb03c4ef93d259039998488a31839426fd0"
21
+ "size": 60681,
22
+ "sha256": "71e003392f4ca0cffeb884f6631e13727cfef764c9aa9e3c1c65965990341b8b"
23
23
  },
24
24
  "data/arch/ADL-P.bin": {
25
- "size": 819776,
26
- "sha256": "3a6623b7086ada2689d068745929537046655b444641885e09154221b5edac87",
25
+ "size": 819806,
26
+ "sha256": "47f6c9e689e0635bf802b1e0d8cf9beedf3387b32e803d9d3c139ba9390f014f",
27
27
  "source": {
28
28
  "file": "data/arch/ADL-P.json",
29
- "size": 1771348,
30
- "sha256": "1632dd7f57d26efa6e465c25c72e38523302c906f8db403af6ba1c432b1e1ccb"
29
+ "size": 1771497,
30
+ "sha256": "749e4a3e3453375083f35d90f2a772f36e7fb86709dbf11338c09fab1c537285"
31
31
  }
32
32
  },
33
33
  "data/arch/BDW.bin": {
@@ -76,12 +76,12 @@
76
76
  }
77
77
  },
78
78
  "data/arch/ICX.bin": {
79
- "size": 698165,
80
- "sha256": "b01057f584a837604ad9c08c4eeae45e09161dce826234d5f010e807a0a18b21",
79
+ "size": 710771,
80
+ "sha256": "10f3524a3e2cc00340fcbe2c6191e3931bf5e8e51612b5032ec65761c46ba167",
81
81
  "source": {
82
82
  "file": "data/arch/ICX.json",
83
- "size": 1495406,
84
- "sha256": "dd45538e22584305d5186d78673b3d4f8bc83fd2d0c0e600ec98540a6d0f2eff"
83
+ "size": 1565345,
84
+ "sha256": "69a5145d629da84f4319eb3eafe9e82827e618e6647b4b751439d02f20f4db41"
85
85
  }
86
86
  },
87
87
  "data/arch/IVB.bin": {
@@ -148,12 +148,12 @@
148
148
  }
149
149
  },
150
150
  "data/arch/ZEN3.bin": {
151
- "size": 198979,
152
- "sha256": "525e66430a3ddc9f0c88d914f32083fbdc0c32f17233dd972548286b4d43b7c7",
151
+ "size": 202810,
152
+ "sha256": "a1fd9019fc464af020e04892d8d782f92ad0688a061d62a5d62899c62d05aecd",
153
153
  "source": {
154
154
  "file": "data/arch/ZEN3.json",
155
- "size": 527963,
156
- "sha256": "72097d0e154b17ef71c12547946c2750f388cdae479b9af99ed5633959c9059a"
155
+ "size": 553459,
156
+ "sha256": "41a147bba4a7419cb5552d457cde022b0130bbf89f4c78e9b9a2725857dabcff"
157
157
  }
158
158
  }
159
159
  }
Binary file
package/index.d.ts CHANGED
@@ -24,8 +24,9 @@ export interface AnalysisOptions {
24
24
  /** "auto" (the default): detected from the text (%registers, $immediates: AT&T; else Intel noprefix). */
25
25
  export type Syntax = 'auto' | 'intel' | 'att';
26
26
 
27
- /** What of `source` is analyzed: "auto" (default: the innermost loop of a whole function, or its body if it has no
28
- * loop; else the text as it is), "whole", or the index of a loop (innermost first, in code order). */
27
+ /** What of `source` is analyzed: "auto" (default: of the deepest innermost loops in the function of the first of them, the one with the
28
+ * widest vector registers, then the most vector instructions, then the most instructions, then the first; its body if
29
+ * it has no loop; else the text as it is), "whole", the index of a loop (as listLoops lists them), or its label. */
29
30
  export type LoopChoice = 'auto' | 'whole' | number | string;
30
31
  /** The named loop choices ('auto', 'whole'); a number is a loop's index (0-based), any other string its label. */
31
32
  export declare const LOOP_CHOICES: readonly ['auto', 'whole'];
@@ -33,7 +34,9 @@ export declare const LOOP_CHOICES: readonly ['auto', 'whole'];
33
34
  export type OtherLoop = Omit<LoopListing, 'auto'>;
34
35
  /** A loop of assembly text (listLoops; the CLI's -loops; the MCP tool list_loops). */
35
36
  export interface LoopListing {
36
- /** Its index for `loop` (0-based): the deepest loops first, then in code order. */
37
+ /** Its index for `loop` (0-based): the deepest innermost loops first, then in code order (the default, `auto`, need
38
+ * not be the first; a loop three or more deep in clang's notes keeps the place it had when only the notes' first two
39
+ * lines were read). */
37
40
  index: number;
38
41
  label: string;
39
42
  /** The function it is in (the last non-local label before it), or null. */
@@ -332,8 +335,11 @@ export interface Wuica {
332
335
  /** An object file or executable (ELF or Mach-O, x86-64; a universal file's x86-64 slice) as llvm-objdump -d's text
333
336
  * of its code sections, which analyze() and compare() read as `source` (the loop at its address, the alignment from
334
337
  * it). Another architecture or format is a Failure that says what it is and how to get x86-64. `func` is resolved
335
- * (exact, without Mach-O's "_", or a unique part of a name) and returned as `func`. */
336
- disassemble(bytes: Uint8Array, options?: { name?: string; func?: string | null }): { code: 0; text: string; format: string; functions: { name: string; section: string; address: number; size: number }[]; func?: string } | Failure;
338
+ * (exact, without Mach-O's "_", or a unique part of a name) and returned as `func`. A name the file gives several
339
+ * functions (static functions of different source files, .cold parts) is NAME.0xADDR, `symbol` the name in the file;
340
+ * `func` set to that name alone is a Failure that lists them. With `func`, `text` is that function's alone (a
341
+ * function of one instruction: with its neighbor), whose loops are the whole text's loops that lie in it. */
342
+ disassemble(bytes: Uint8Array, options?: { name?: string; func?: string | null }): { code: 0; text: string; format: string; functions: { name: string; section: string; address: number; size: number; symbol?: string }[]; func?: string } | Failure;
337
343
  /** GET /api/archs: in order of release (uiCA's ablation variants, ids with "_", are left out). */
338
344
  archs(): ArchInfo[];
339
345
  archs(fields: ArchField[] | string): Partial<ArchInfo>[];
package/lib/cli.js CHANGED
@@ -36,10 +36,12 @@ Input:
36
36
  -raw FILE read the machine code from a binary file that contains only the code (not an object
37
37
  file: for those, objdump -d FILE | wuica)
38
38
  -loops list the loops of the assembly (index, label, function, lines, instructions, depth, auto)
39
- -loop L what is analyzed: auto (default: the deepest loop, among equals the first; clang's
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
42
- -loops lists them) or its label (-loop .LBB0_12)
39
+ -loop L what is analyzed: auto (default: of the deepest innermost loops in the function of
40
+ the first of them, the one with the widest vector registers, then the most vector
41
+ instructions, then the most instructions, then the first; clang's "Inner Loop
42
+ Header" notes count; perf annotate: the loop with the most samples of its own),
43
+ whole (all the text), a loop's index (0-based, as -loops lists them) or its label
44
+ (-loop .LBB0_12)
43
45
  -func NAME only the loops of function NAME (with -loop: its index or label among them); in an object
44
46
  file its symbol, or a unique part of it
45
47
  -funcs list the functions of an object file (name, section, address, size)
@@ -310,7 +312,10 @@ function printAnalyzed(r, err, o) {
310
312
  const syn = r.syntax ? `${r.syntax === 'att' ? 'AT&T' : 'Intel'} syntax${o.syntax === 'auto' ? ' (detected)' : ''}` : null;
311
313
  if (p && p.line) {
312
314
  const others = (p.count ?? 1) - (Number.isInteger(p.index) ? 1 : 0);
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}` : ''}`
315
+ // (an object file's function: the loop's, or for a body the -func it was given)
316
+ const fn = p.function ?? (o.objectInput ? o.objectFunc : null);
317
+ const where = [o.objectInput ? null : `lines ${p.line}-${p.endLine}`, fn ? `in ${fn}` : null, p.address !== undefined ? `address 0x${p.address.toString(16)}` : null].filter(Boolean);
318
+ err.write(`analyzed: ${p.name} (${where.join(', ')})${syn ? `, ${syn}` : ''}`
314
319
  + `${others > 0 ? `; ${others} other loop${others === 1 ? '' : 's'}: -loops lists them, -loop picks one` : ''}; -loop whole for the whole text\n`);
315
320
  } else if (syn && r.syntax === 'att' && o.syntax === 'auto') {
316
321
  err.write(`analyzed: the whole text, ${syn}; -intel forces Intel\n`);
@@ -441,7 +446,7 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
441
446
  if (o.report) err.write('-report: with several inputs (one input prints its report anyway); ignored\n');
442
447
  const input = await readInput(o, io, w);
443
448
  for (const n of input.notes) err.write(`${n}\n`);
444
- if (input.object) o.objectInput = true;
449
+ if (input.object) { o.objectInput = true; o.objectFunc = input.request.func ?? null; }
445
450
  if (o.funcs) {
446
451
  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
452
  const fs_ = input.object.functions;
@@ -455,7 +460,8 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st
455
460
 
456
461
  if (o.loops) {
457
462
  if (!req.source) return fail(CODES.REQUEST, '-loops: needs assembly (not machine code)');
458
- const ls = listLoops(req.source, { func: o.func ?? null });
463
+ // (an object file's -func as disassemble() resolved it: a part of a name, Mach-O's "_", NAME.0xADDR)
464
+ const ls = listLoops(req.source, { func: req.func ?? o.func ?? null });
459
465
  if (ls.error) return fail(CODES.REQUEST, ls.error);
460
466
  if (o.json) { out.write(JSON.stringify({ code: 0, loops: ls }) + '\n'); return 0; }
461
467
  if (o.md) { out.write(markdown.loops(ls)); return 0; }
package/lib/index.js CHANGED
@@ -615,8 +615,10 @@ class Wuica {
615
615
 
616
616
  // An object file (ELF or Mach-O, x86-64; objfile.js) as llvm-objdump -d's text of its code, which analyze() and
617
617
  // compare() read as `source` (the objdump path: the loop at its address, exits stubbed, the alignment from it).
618
- // -> {code: 0, text, format, functions: [{name, section, address, size}]} or a failure (another architecture says how
619
- // to compile for x86-64). `func`: also resolves a -func name (exact, without Mach-O's "_", or a unique part): `func`.
618
+ // -> {code: 0, text, format, functions: [{name, section, address, size[, symbol]}]} or a failure (another architecture
619
+ // says how to compile for x86-64). A name the file gives several functions is NAME.0xADDR, with `symbol` the name in
620
+ // the file (objfile.js uniqueNames). `func`: also resolves a -func name (exact, without Mach-O's "_", or a unique
621
+ // part; a repeated name is an error that lists the functions): `func`, and `text` is that function's alone.
620
622
  /** @param {Uint8Array} bytes @param {{name?: string, func?: string | null}} [opts] @returns {any} */
621
623
  disassemble(bytes, { name = 'input', func = null } = {}) {
622
624
  const obj = readObject(bytes);
@@ -628,13 +630,27 @@ class Wuica {
628
630
  if (r.error) return failure(CODES.REQUEST, r.error);
629
631
  resolved = r.name;
630
632
  }
633
+ // with a function: the text of that function alone. Its loops are those of the whole text's that lie in it (not a
634
+ // span from it into another function, which the whole text took for a loop: a branch to a .cold part placed before
635
+ // it), and it stays valid and small whatever else the file has (a static executable: thousands of functions,
636
+ // megabytes of text).
637
+ // A function of one instruction comes with the function after it (or before it, the last one): text with a single
638
+ // instruction line is not read as objdump output (loop-find.js fromObjdump)
639
+ const decode = (b) => this.#analyzer.decode(b, 'ALL');
631
640
  let text;
632
641
  try {
633
- text = objdumpText(obj, (b) => this.#analyzer.decode(b, 'ALL'), name);
642
+ if (resolved === null) text = objdumpText(obj, decode, name);
643
+ else {
644
+ const k = obj.functions.findIndex((f) => f.name === resolved);
645
+ text = objdumpText({ ...obj, functions: [obj.functions[k]] }, decode, name);
646
+ const lines = (s) => s.split('\n').filter((l) => /^ *[0-9a-f]+: /.test(l)).length;
647
+ const other = obj.functions[k + 1] ?? obj.functions[k - 1];
648
+ if (lines(text) < 2 && other) text = objdumpText({ ...obj, functions: obj.functions.filter((f) => f === other || f.name === resolved) }, decode, name);
649
+ }
634
650
  } catch (e) {
635
651
  return failure(CODES.ANALYSIS, `the decoder failed (${e.message})`);
636
652
  }
637
- return { code: CODES.OK, text, format: obj.format, functions: obj.functions.map(({ name: n, section, address, size }) => ({ name: n, section, address, size })), ...(resolved !== null ? { func: resolved } : {}) };
653
+ return { code: CODES.OK, text, format: obj.format, functions: obj.functions.map(({ name: n, section, address, size, symbol }) => ({ name: n, section, address, size, ...(symbol !== undefined ? { symbol } : {}) })), ...(resolved !== null ? { func: resolved } : {}) };
638
654
  }
639
655
 
640
656
  get restarts() { return this.#analyzer.restarts; }
package/lib/mcp.js CHANGED
@@ -27,7 +27,7 @@ const ASSUMPTIONS =
27
27
 
28
28
  const INPUT_NOTE =
29
29
  'The block: `source` (x86-64 assembly, Intel or AT&T, detected; a whole function, gcc/clang -S or objdump -d output ' +
30
- 'is fine: its innermost loop is analyzed; `loop` picks another: "whole", an index or a label; `func` one ' +
30
+ 'is fine: its innermost loop is analyzed (the widest vector loop, else the largest); `loop` picks another: "whole", an index or a label; `func` one ' +
31
31
  "function's) or `hex` (machine code).";
32
32
 
33
33
  const ERRORS_NOTE = 'A failure is a tool error {code, error, stderr}: 1 bad request, 2 assembler error (positioned stderr), 3 analysis failed.';
@@ -43,7 +43,7 @@ const codeShape = {
43
43
  hex: str('machine code as hex bytes, e.g. "4801d84801c349ffcf75f5" (spaces allowed)'),
44
44
  syntax: str('syntax of `source`: "auto" (default: detected from the text), "intel" (noprefix) or "att"', { enum: ['auto', 'intel', 'att'] }),
45
45
  loop: {
46
- description: 'what of `source` is analyzed: "auto" (default: the deepest loop of a whole function, else the text), "whole", the index of a loop (0-based), or its label',
46
+ description: 'what of `source` is analyzed: "auto" (default: of the deepest innermost loops, in the function of the first of them, the widest vector loop, then the most vector instructions, then the largest; else the text), "whole", the index of a loop (0-based), or its label',
47
47
  anyOf: [{ type: 'string', enum: ['auto', 'whole'] }, { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER }, { type: 'string', minLength: 1 }],
48
48
  },
49
49
  func: str('only the loops of this function (a label of `source`)', { minLength: 1 }),
package/lib/objfile.js CHANGED
@@ -23,24 +23,52 @@ export function objectKind(b) {
23
23
 
24
24
  const ARCH_HELP = 'compile for x86-64: clang --target=x86_64-linux-gnu -c (Linux objects) or clang -arch x86_64 -c (macOS)';
25
25
 
26
- // The code of an object file: {format, functions: [{name, section, address, size, bytes}]} or {error}.
26
+ // The code of an object file: {format, functions: [{name, section, address, size, bytes[, symbol]}]} or {error}.
27
+ // Names are unique (uniqueNames): a function whose symbol name occurs more than once has its address in its name, and
28
+ // `symbol` is the name in the file.
27
29
  /** @returns {any} */
28
30
  export function readObject(bytes) {
29
31
  const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
30
32
  const k = objectKind(b);
31
33
  if (!k) return { error: 'not an object file' };
32
34
  try {
33
- if (k.kind === 'elf') return readElf(b);
34
- if (k.kind === 'macho') return readMachO(b);
35
- if (k.kind === 'fat') return readFat(b);
36
- if (k.kind === 'macho32') return { error: `a 32-bit Mach-O file: wuica analyzes x86-64 code; ${ARCH_HELP}` };
37
- if (k.kind === 'archive') return { error: 'an archive (.a): extract an object from it (ar x lib.a foo.o) and give that' };
38
- return { error: `${k.kind === 'pe' ? 'a PE (Windows) executable' : 'a COFF object file'}: not supported yet; disassemble it and pipe the listing (llvm-objdump -d FILE | wuica)` };
35
+ const r = readContainer(b, k);
36
+ if (r.functions) uniqueNames(r.functions);
37
+ return r;
39
38
  } catch (e) {
40
39
  return { error: `a damaged or truncated object file (${e.message})` };
41
40
  }
42
41
  }
43
42
 
43
+ // A static executable (or a relocatable object made by ld -r) has local symbols with the same name: static functions of
44
+ // different translation units, their .cold parts, glibc's helpers. In llvm-objdump -d's text each function's header
45
+ // ("0000000000401000 <step>:") becomes a label, and a label defined twice fails to assemble. So every function whose
46
+ // name occurs more than once is named NAME.0xADDR (its address; a plain label as loop-find.js reads one), all of them:
47
+ // none is the NAME of a -func, which says that NAME is ambiguous (resolveFunction). A file without repeated names keeps
48
+ // its names: its text is llvm-objdump's, as before.
49
+ function uniqueNames(functions) {
50
+ const count = new Map();
51
+ for (const f of functions) count.set(f.name, (count.get(f.name) ?? 0) + 1);
52
+ const taken = new Set(functions.map((f) => f.name));
53
+ for (const f of functions) {
54
+ if (count.get(f.name) === 1) continue;
55
+ let name = `${f.name}.0x${f.address.toString(16)}`;
56
+ for (let k = 2; taken.has(name); k++) name = `${f.name}.0x${f.address.toString(16)}.${k}`; // (a symbol of that name too)
57
+ taken.add(name);
58
+ f.symbol = f.name;
59
+ f.name = name;
60
+ }
61
+ }
62
+
63
+ function readContainer(b, k) {
64
+ if (k.kind === 'elf') return readElf(b);
65
+ if (k.kind === 'macho') return readMachO(b);
66
+ if (k.kind === 'fat') return readFat(b);
67
+ if (k.kind === 'macho32') return { error: `a 32-bit Mach-O file: wuica analyzes x86-64 code; ${ARCH_HELP}` };
68
+ if (k.kind === 'archive') return { error: 'an archive (.a): extract an object from it (ar x lib.a foo.o) and give that' };
69
+ return { error: `${k.kind === 'pe' ? 'a PE (Windows) executable' : 'a COFF object file'}: not supported yet; disassemble it and pipe the listing (llvm-objdump -d FILE | wuica)` };
70
+ }
71
+
44
72
  function view(b) { return new DataView(b.buffer, b.byteOffset, b.byteLength); }
45
73
  const u64 = (dv, o) => Number(dv.getBigUint64(o, true));
46
74
  const cstr = (b, o) => { let e = o; while (e < b.length && b[e] !== 0) e++; return td.decode(b.subarray(o, e)); };
@@ -205,14 +233,24 @@ export function objdumpText(obj, decode, name = 'input') {
205
233
  }
206
234
 
207
235
  // The function a -func name means among an object's functions: exact, else without Mach-O's leading underscore, else a
208
- // unique part of a name. {name} or {error} (the candidates when ambiguous, the functions when none matches).
236
+ // unique part of a name. {name} or {error} (the candidates when ambiguous, the functions when none matches). A name the
237
+ // file gives to several functions (uniqueNames: NAME.0xADDR) is ambiguous: the error lists them with their addresses.
209
238
  export function resolveFunction(functions, func) {
210
239
  const names = [...new Set(functions.map((f) => f.name))];
211
240
  if (names.includes(func)) return { name: func };
241
+ for (const symbol of [func, `_${func}`]) {
242
+ const same = functions.filter((f) => f.symbol === symbol);
243
+ if (!same.length) continue;
244
+ const shown = same.slice(0, 10).map((f) => `0x${f.address.toString(16)}`);
245
+ const at = `${shown.slice(0, -1).join(', ')}${same.length > 2 ? ',' : ''} and ${shown[shown.length - 1]}${same.length > 10 ? ` (and ${same.length - 10} more: -funcs lists them)` : ''}`;
246
+ return { error: `func: ${JSON.stringify(func)} names ${same.length} functions of the file, at ${at} (static functions of different source files, or parts of one): give it with its address, -func ${same[0].name}${same.length === 2 ? ` or -func ${same[1].name}` : ''}` };
247
+ }
212
248
  const under = names.filter((n) => n === `_${func}`);
213
249
  if (under.length === 1) return { name: under[0] };
214
250
  const part = names.filter((n) => n.includes(func));
215
251
  if (part.length === 1) return { name: part[0] };
216
- if (part.length > 1) return { error: `func: ${JSON.stringify(func)} is part of ${part.length} function names (${part.join(', ')}): give one of them` };
217
- return { error: `func: ${JSON.stringify(func)} is not a function of the file (functions: ${names.join(', ') || 'none'})` };
252
+ // (a static executable has thousands of functions: a long list is left to -funcs)
253
+ const list = (xs) => (xs.length <= 20 ? xs.join(', ') : `${xs.slice(0, 20).join(', ')}, and ${xs.length - 20} more: -funcs lists them`);
254
+ if (part.length > 1) return { error: `func: ${JSON.stringify(func)} is part of ${part.length} function names (${list(part)}): give one of them` };
255
+ return { error: `func: ${JSON.stringify(func)} is not a function of the file (functions: ${list(names) || 'none'})` };
218
256
  }
@@ -348,8 +348,8 @@ export function separatorNotes(text) {
348
348
  // count} | null) and source ({text: null, file, spans: [{off, line}]} | null). assemble(text) -> promise of that result.
349
349
  // A ';' comment after a statement is retried as '#' (above).
350
350
  // opts.loop ('auto', 'whole' or a loop's index): the text is assembled for an analysis (loop-find.js): objdump lines,
351
- // the loop or the body of a function, the exits as not taken. The result then also has loop ({index, count, name, line,
352
- // endLine, address, alignment} | null: what was picked), loops ([{begin, end, label}]: the choices), body ({begin, end}
351
+ // the loop or the body of a function, the exits as not taken. The result then also has loop ({index, count, name, auto,
352
+ // line, endLine, address, alignment} | null: what was picked; auto: the default picked it), loops ([{begin, end, label}]: the choices), body ({begin, end}
353
353
  // | null), choosable (a choice matters: code around the loop or the body) and alignment (from
354
354
  // the text's addresses, or null), and the notes (exits, undefined jump targets) among its diagnostics.
355
355
  export async function assembleMarked(assemble, text, opts = {}) {
@@ -380,7 +380,7 @@ export async function assembleMarked(assemble, text, opts = {}) {
380
380
  }
381
381
  if (!prep) return r;
382
382
  const loop = prep.choice === null ? null : {
383
- index: prep.choice === 'body' ? null : prep.choice, count: prep.loops.length, name: loopName(prep),
383
+ index: prep.choice === 'body' ? null : prep.choice, count: prep.loops.length, name: loopName(prep), auto: !!prep.auto,
384
384
  line: prep.pick.begin, endLine: prep.pick.end, lines: prep.pick.lines, address: prep.address, alignment: prep.alignment,
385
385
  };
386
386
  // the source line of each analyzed instruction: of the pick, or of the whole text (not with a marked region)
@@ -16,8 +16,10 @@
16
16
  // - a ';' that starts a line is a comment (as '#'); one after a statement stays a separator unless the assembler
17
17
  // rejects what follows it (asm-regions.js: commentFixes, separatorNotes).
18
18
  // - the loops: backward branches to a label (or to an address); innermost first, in the order of the code. A span
19
- // that holds a ret or a function's label is not a loop (a tail call to an earlier function). The pick is the first
20
- // one, unless the text is that loop already; with no loop, a compiler's function (a function label, directives, or
19
+ // that holds a ret or a function's label is not a loop (a tail call to an earlier function). The pick is the default
20
+ // loop (defaultLoop: among the deepest innermost loops in the function of the first of them, the widest vector loop,
21
+ // else the largest), unless the text is
22
+ // that loop already; with no loop, a compiler's function (a function label, directives, or
21
23
  // a prologue/epilogue) that ends in ret is analyzed without its prologue, epilogue and ret (its body); a bare snippet
22
24
  // is analyzed as typed. Region markers (LLVM-MCA-BEGIN, wuica-begin, IACA) win: no pick. loop "whole": no pick.
23
25
  // - conditional branches to a symbol the text does not define (the loop's exits: jae .Lout) are "not taken": the
@@ -43,6 +45,9 @@ export const OUTSIDE_PREFIX = '.Lwuica_x';
43
45
  // directives after which the lines of a text are not its instructions one to one
44
46
  const STRUCTURAL = /^[ \t]*(?:[\w.$@]+:[ \t]*)*(\.(?:rept|irpc?|macro|if\w*))\b/im; // an objdump branch to an address that is not in the text
45
47
  const ADDR_LABEL = (a) => `.Lwuica_a${a.toString(16)}`;
48
+ // The page's links made before the default loop was defaultLoop's (a link without lp=) pick what "auto" picked then: the
49
+ // first loop of findLoops' list (url-state.js). Not a label (a label has no '-').
50
+ export const LEGACY_AUTO = 'auto-v1';
46
51
 
47
52
  // Splits a line (block comments already removed) into its statements outside comments: [{at, text}] (at: the column
48
53
  // of the statement's first character, 0-based). '#' and '//' start a comment, ';' separates statements; quotes kept.
@@ -294,9 +299,12 @@ export const isText = (args) => { const n = sectionName(args); return n === '.te
294
299
  export function scan(text) {
295
300
  const raw = String(text).split('\n');
296
301
  const lines = blankBlockComments(String(text)).split('\n');
297
- // clang's loop notes on a label's line or the comment line after it ("# =>This Inner Loop Header: Depth=2",
302
+ // clang's loop notes on a label's line and the comment lines after it ("# =>This Inner Loop Header: Depth=2",
298
303
  // "# in Loop: Header=BB0_4 Depth=1"): label -> text
299
304
  const notes = new Map();
305
+ // the note as the label's line and the one line after it (what was read before deeper nests' notes were: the list's
306
+ // order keeps it, findLoops)
307
+ const shortNotes = new Map();
300
308
  const labels = new Map(), symbols = new Set(), instrs = [], numeric = [], functions = new Set(), data = [];
301
309
  let inText = true, prev = true, directives = 0;
302
310
  const stack = [];
@@ -311,8 +319,13 @@ export function scan(text) {
311
319
  if (/^\d+$/.test(name)) numeric.push({ name, line: i + 1, inText });
312
320
  else if (!labels.has(name)) {
313
321
  labels.set(name, { line: i + 1, inText });
314
- const note = `${raw[i] ?? ''} ${/^\s*#/.test(raw[i + 1] ?? '') ? raw[i + 1] : ''}`;
322
+ // (the note's lines that follow: as many as the nest is deep, "# Parent Loop BB0_1 Depth=1", ...,
323
+ // "# => This Inner Loop Header: Depth=3")
324
+ let note = raw[i] ?? '';
325
+ for (let k = i + 1; k < raw.length && /^\s*#(?!\s*%bb\.).*(?:Loop|Depth=)/.test(raw[k]); k++) note += ` ${raw[k]}`;
315
326
  if (/Loop Header|in Loop:|Parent Loop/.test(note)) notes.set(name, note);
327
+ const short = `${raw[i] ?? ''} ${/^\s*#/.test(raw[i + 1] ?? '') ? raw[i + 1] : ''}`;
328
+ if (/Loop Header|in Loop:|Parent Loop/.test(short)) shortNotes.set(name, short);
316
329
  }
317
330
  }
318
331
  const body = st.text.slice(lead).trim();
@@ -351,7 +364,7 @@ export function scan(text) {
351
364
  instrs.push({ line: i + 1, col: st.at + lead, end: st.at + st.text.length, mnemonic, operands, kind, target, body });
352
365
  }
353
366
  }
354
- return { labels, symbols, instrs, numeric, functions, directives, notes, data };
367
+ return { labels, symbols, instrs, numeric, functions, directives, notes, shortNotes, data };
355
368
  }
356
369
 
357
370
  // The line a branch target refers to (a label, or a numeric label "1b" / "1f" seen from `line`), or null.
@@ -366,8 +379,9 @@ function targetLine(s, target, line) {
366
379
  return l && l.inText ? l.line : null;
367
380
  }
368
381
 
369
- // The loops: [{begin, end, label, inner}] (begin: the label's line, end: the last branch back to it; 1-based), innermost first,
370
- // then the deepest, then in the order of the code (which may put a remainder loop first: clang often does).
382
+ // The loops: [{begin, end, label, inner, depth, instructions, function, vector: {width, count}}] (begin: the label's line,
383
+ // end: the last branch back to it; 1-based), innermost first, then the deepest, then in the order of the code (which may
384
+ // put a remainder loop first: clang often does). defaultLoop picks one of them.
371
385
  export function findLoops(s) {
372
386
  const loops = [];
373
387
  for (const ins of s.instrs) {
@@ -402,25 +416,248 @@ export function findLoops(s) {
402
416
  merged = [...groups.values()].map((g) => {
403
417
  const header = `.L${g.key}`;
404
418
  const label = s.labels.has(header) ? header : g.label;
405
- const note = s.notes.get(label) ?? '';
406
- const d = /Loop Header: Depth=(\d+)/.exec(note) ?? /Depth=(\d+)/.exec(note);
407
- return { begin: g.begin, end: g.end, label, ...(d ? { clangDepth: Number(d[1]) } : {}) };
419
+ const depthOf = (note) => { const d = /Loop Header: Depth=(\d+)/.exec(note) ?? /Depth=(\d+)/.exec(note); return d ? Number(d[1]) : undefined; };
420
+ return { begin: g.begin, end: g.end, label, clangDepth: depthOf(s.notes.get(label) ?? ''), shortDepth: depthOf(s.shortNotes?.get(label) ?? '') };
408
421
  });
409
422
  }
410
423
  for (const l of merged) {
411
424
  l.inner = !merged.some((o) => o !== l && o.begin >= l.begin && o.end <= l.end && (o.begin !== l.begin || o.end !== l.end));
412
425
  // nesting depth: 1 for a loop in no other (clang's Depth when it says)
413
- l.depth = l.clangDepth ?? 1 + merged.filter((o) => o !== l && o.begin <= l.begin && o.end >= l.end && (o.begin !== l.begin || o.end !== l.end)).length;
426
+ const nesting = 1 + merged.filter((o) => o !== l && o.begin <= l.begin && o.end >= l.end && (o.begin !== l.begin || o.end !== l.end)).length;
427
+ l.depth = l.clangDepth ?? nesting;
428
+ // the depth the list is ordered by: as the first two lines of clang's note give it. A loop three or more deep has its
429
+ // "Inner Loop Header: Depth=N" on a later line, which was not read before: its listDepth is then the first line's
430
+ // Depth (1), so the list keeps the order it had and an index (-loop N, lp=N in a link, the API's loop) names the
431
+ // loop it named. depth, and the default (defaultLoop), use the note's real Depth.
432
+ l.listDepth = l.shortDepth ?? nesting;
414
433
  delete l.clangDepth;
434
+ delete l.shortDepth;
415
435
  l.instructions = s.instrs.filter((x) => x.line >= l.begin && x.line <= l.end).length;
416
436
  // the function it is in: the last label before it that is not local
417
437
  let fname = null, at = -1;
418
438
  for (const [name, d] of s.labels) if (d.line <= l.begin && d.line > at && !name.startsWith('.L') && !/^\d+$/.test(name) && !name.startsWith('wuica')) { fname = name; at = d.line; }
419
439
  l.function = fname;
420
440
  }
421
- // the innermost and deepest first; among equals, the first in the code (gcc puts the main loop first, clang often its
422
- // remainder loop: -loops lists them all)
423
- return merged.sort((a, b) => Number(b.inner) - Number(a.inner) || b.depth - a.depth || a.begin - b.begin || a.end - b.end);
441
+ for (const l of merged) {
442
+ // the vector instructions (vectorWidth) and the widest of their registers: the default's preference (defaultLoop)
443
+ let width = 0, count = 0;
444
+ for (const x of s.instrs) {
445
+ if (x.line < l.begin || x.line > l.end) continue;
446
+ const w = vectorWidth(x.mnemonic, x.operands);
447
+ if (w) { count++; width = Math.max(width, w); }
448
+ }
449
+ l.vector = { width, count };
450
+ }
451
+ // the remainder loops (remainderOf): the begin lines of the loops each one continues
452
+ for (const l of merged) l.remainderOf = merged.filter((a) => a !== l && isRemainder(s, a, l)).map((a) => a.begin);
453
+ // the order of the list (the indices of -loop N, lp= in the page's links, the API's loop): the innermost first, the
454
+ // deepest of them first (by listDepth), then in the order of the code. Which of them is analyzed by default is
455
+ // defaultLoop's choice, not the first.
456
+ return merged.sort((a, b) => Number(b.inner) - Number(a.inner) || b.listDepth - a.listDepth || a.begin - b.begin || a.end - b.end);
457
+ }
458
+
459
+ // ---- the default loop ------------------------------------------------------------------------------------------------
460
+ //
461
+ // The loop analyzed by default ("auto") among the loops of a text (findLoops' order; after -func):
462
+ // 1. only the innermost loops at the greatest depth (clang's "Inner Loop Header: Depth=N" notes count) that are in
463
+ // the function of the first of them (the first loop of the list; loops in no function are one group): a text
464
+ // with several functions is analyzed in the function the first deepest loop is in, never at another's loop; and
465
+ // not the remainder of another of them (isRemainder, below: the tail of an unrolled loop);
466
+ // 2. among those, the one whose vector instructions use the widest registers (zmm over ymm over xmm over none), then
467
+ // the one with more vector instructions;
468
+ // 3. then the one with more instructions, then the first in the text.
469
+ // A compiler's vectorized loop comes with a scalar remainder, sometimes a peel loop before it or a narrower vector
470
+ // epilogue, often first in the text (clang): rule 2 picks the vector loop. A function without vector code gets its
471
+ // largest loop (rule 3), as one whose scalar floating-point code touches xmm registers does (vectorWidth).
472
+ //
473
+ // A vector instruction (vectorWidth): an SSE, AVX or AVX-512 instruction that works on several elements of a vector
474
+ // register. It names an xmm, ymm or zmm register and is none of these, which scalar code uses (gcc and clang compile
475
+ // scalar float and double code to them, so they do not make a loop a vector loop):
476
+ // - scalar floating point: a mnemonic (without its v) that does not start with p and ends in ss, sd or sh (addss,
477
+ // vmulsd, vfmadd231sd, movss, ucomisd, sqrtsd, cvtss2sd, vcvtsi2sd, cvtsi2sdq), and the conversions of one value to
478
+ // an integer register (cvttsd2si, vcvtss2usi); not the broadcasts (vbroadcastss fills a whole register);
479
+ // - one element moved between a general-purpose register or memory and a vector register: movd, movq, pinsr*,
480
+ // pextr*, insertps, extractps, movlpd, movhpd (and their v forms, vmovw);
481
+ // - zero idioms (xorps xmm0, xmm0; vpxor xmm1, xmm1, xmm1: the same register throughout): what compilers put before
482
+ // a cvtsi2sd to break its dependency;
483
+ // - copies from register to register (movaps xmm1, xmm0; vmovdqa64 zmm1, zmm2 without a mask): no work on elements;
484
+ // - the floating-point logic of xmm registers (andps, andnps, orps, xorps and their pd forms): fabs, negation and
485
+ // copysign of a scalar (andpd xmm0, [mask]). On ymm and zmm they count (no compiler uses those for scalars); a
486
+ // 128-bit vector loop always has other vector instructions (its loads, stores, arithmetic).
487
+ // MMX registers (mm0-mm7) and mask registers (k0-k7) do not make an instruction vector by themselves.
488
+
489
+ const VREG = /(?:^|[^\w])%?([xyz])mm([0-9]|[12][0-9]|3[01])(?![\w])/gi;
490
+ const WIDTH = { x: 128, y: 256, z: 512 };
491
+ const ELEMENT = /^(?:movd|movq|movw|pinsr[bwdq]|pextr[bwdq]|insertps|extractps|movlpd|movhpd)$/;
492
+ const ZERO = /^(?:xorp[sd]|pxor[dq]?|psub[bwdq]|pcmpgt[bwdq]|andnp[sd]|pandn[dq]?)$/;
493
+ const COPY = /^mov(?:ap[sd]|up[sd]|dq[au](?:8|16|32|64)?)$/;
494
+ const FP_LOGIC = /^(?:andn?p[sd]|orp[sd]|xorp[sd])$/;
495
+
496
+ // The width (128, 256 or 512) of the widest vector register of a vector instruction (see above), or 0 if it is not one.
497
+ export function vectorWidth(mnemonic, operands) {
498
+ let width = 0;
499
+ const regs = [];
500
+ for (const m of String(operands ?? '').matchAll(VREG)) {
501
+ width = Math.max(width, WIDTH[m[1].toLowerCase()]);
502
+ regs.push(`${m[1]}mm${m[2]}`.toLowerCase());
503
+ }
504
+ if (!width) return 0;
505
+ const mn = String(mnemonic).toLowerCase();
506
+ const base = mn.startsWith('v') ? mn.slice(1) : mn;
507
+ if (!base.startsWith('p') && !base.startsWith('broadcast') && /(?:ss|sd|sh)$/.test(base.replace(/^(cvtu?si2s[sdh])[lq]$/, '$1'))) return 0;
508
+ if (/^cvtt?s[sdh]2u?si[lq]?$/.test(base)) return 0;
509
+ if (ELEMENT.test(base)) return 0;
510
+ const ops = String(operands ?? '').split(/,(?![^[(]*[\])])/).map((o) => o.trim()).filter(Boolean);
511
+ const regOnly = ops.every((o) => /^%?[xyz]mm\d+$/i.test(o)); // (no memory operand, no immediate, no mask)
512
+ if (ZERO.test(base) && regOnly && ops.length >= 2 && new Set(regs).size === 1) return 0;
513
+ if (COPY.test(base) && regOnly && ops.length === 2) return 0;
514
+ if (FP_LOGIC.test(base) && width === 128) return 0;
515
+ return width;
516
+ }
517
+
518
+ // ---- remainder loops ------------------------------------------------------------------------------------------------
519
+ //
520
+ // A loop b is the remainder of a loop a (a's leftover iterations: the scalar tail after an unrolled or vectorized loop)
521
+ // when, as the text shows: a comes first and its only exit is its back branch, a compare of a register that a writes
522
+ // with a register x that it does not write (the bound: "cmp rsi, r15; jbe"); b's back branch compares the same x, not
523
+ // written between the two loops, with a register c that b only advances (add, sub, inc, dec, lea of c and a constant);
524
+ // and c's value at b comes from a: between the loops c is only advanced or copied (mov c, r: then r), and in a it is
525
+ // the compared register itself, or differs from it by a constant (its last write copies it, or the compared register's
526
+ // first write copies c, and both are otherwise only advanced). b then starts where a stopped and runs to the bound a stopped at, which a's last step did
527
+ // not reach: fewer iterations than one step of a. Anything else (a call, another exit of a, a write of c that is not
528
+ // an advance or a copy, a bound in memory) is no remainder.
529
+
530
+ const GPR_FAMILY = (op) => {
531
+ const r = String(op).trim().replace(/^%/, '').toLowerCase();
532
+ let m = /^r(\d+)[dwb]?$/.exec(r);
533
+ if (m && Number(m[1]) >= 8 && Number(m[1]) <= 15) return `r${m[1]}`;
534
+ m = /^(?:[re]?([abcd])x|([abcd])[lh])$/.exec(r);
535
+ if (m) return m[1] ?? m[2];
536
+ m = /^(?:[re]?(si|di|bp|sp)|(si|di|bp|sp)l)$/.exec(r);
537
+ return m ? m[1] ?? m[2] : null;
538
+ };
539
+ const ATT = (x) => /%/.test(x.operands);
540
+ const operandsOf = (x) => String(x.operands).split(/,(?![^[(]*[\])])/).map((o) => o.trim()).filter(Boolean);
541
+ const NO_WRITE = /^(?:cmp\w*|test\w*|bt[lqw]?|j\w+|push\w*|nop\w*|ucomis[sd]|comis[sd]|prefetch\w*)$/i;
542
+ const IMPLICIT = { call: ['a', 'c', 'd', 'si', 'di', 'r8', 'r9', 'r10', 'r11'], syscall: ['a', 'c', 'r11'], cpuid: ['a', 'b', 'c', 'd'],
543
+ rdtsc: ['a', 'd'], cqo: ['d'], cqto: ['d'], cdq: ['d'], cltd: ['d'], cltq: ['a'], cdqe: ['a'], cwtl: ['a'] };
544
+ // the general-purpose registers an instruction writes (families: 'a', 'si', 'r8', ...); null: it may write any
545
+ function writes(x) {
546
+ const mn = x.mnemonic.toLowerCase();
547
+ if (/^call/.test(mn)) return IMPLICIT.call;
548
+ if (IMPLICIT[mn]) return IMPLICIT[mn];
549
+ if (/^(?:rep|stos|movs|lods|scas|cmps)/.test(mn) || /^(?:rep|repe|repne)\b/.test(x.body ?? '')) return null;
550
+ const out = [];
551
+ if (/^(?:i?mul|i?div)[bwlq]?$/.test(mn) && operandsOf(x).length === 1) out.push('a', 'd');
552
+ if (NO_WRITE.test(mn)) return out;
553
+ const ops = operandsOf(x);
554
+ if (!ops.length) return out;
555
+ const dest = ATT(x) ? ops[ops.length - 1] : ops[0];
556
+ const f = GPR_FAMILY(dest);
557
+ if (f) out.push(f);
558
+ if (/^(?:xchg|xadd|cmpxchg)\w*$/.test(mn)) for (const o of ops) { const g = GPR_FAMILY(o); if (g) out.push(g); }
559
+ if (/^pop/.test(mn)) out.push('sp');
560
+ return out;
561
+ }
562
+ // "c += constant": add, sub, inc, dec of c, or lea of c and a constant into c
563
+ function advances(x, c) {
564
+ const mn = x.mnemonic.toLowerCase(), ops = operandsOf(x);
565
+ if (/^(?:inc|dec)[bwlq]?$/.test(mn)) return ops.length === 1 && GPR_FAMILY(ops[0]) === c;
566
+ if (/^(?:add|sub)[bwlq]?$/.test(mn) && ops.length === 2) {
567
+ const [src, dst] = ATT(x) ? ops : [ops[1], ops[0]];
568
+ return GPR_FAMILY(dst) === c && /^\$?-?(?:0x[0-9a-f]+|\d+)$/i.test(src);
569
+ }
570
+ if (/^lea[lqw]?$/.test(mn) && ops.length === 2) {
571
+ const [src, dst] = ATT(x) ? ops : [ops[1], ops[0]];
572
+ const m = ATT(x) ? /^-?(?:0x[0-9a-f]+|\d+)?\((%\w+)\)$/i.exec(src) : /^(?:\w+\s+ptr\s+)?\[\s*(\w+)\s*(?:[+-]\s*(?:0x[0-9a-f]+|\d+))?\s*\]$/i.exec(src);
573
+ return GPR_FAMILY(dst) === c && !!m && GPR_FAMILY(m[1]) === c;
574
+ }
575
+ return false;
576
+ }
577
+ // a loop's back branch and its compare: {bound, varying, only} (only: no other branch, call or ret in the loop), or null
578
+ function loopExit(s, l) {
579
+ const body = s.instrs.filter((x) => x.line >= l.begin && x.line <= l.end);
580
+ const back = body[body.length - 1], cmp = body[body.length - 2];
581
+ if (!back || !cmp || back.kind !== 'jcc' || !/^cmp[bwlq]?$/i.test(cmp.mnemonic)) return null;
582
+ const ops = operandsOf(cmp);
583
+ if (ops.length !== 2) return null;
584
+ const fams = ops.map(GPR_FAMILY);
585
+ if (fams.some((f) => !f)) return null; // (a bound in memory or an immediate: not this kind)
586
+ const written = new Set();
587
+ for (const x of body) { const w = writes(x); if (w === null) return null; for (const f of w) written.add(f); }
588
+ const inv = fams.filter((f) => !written.has(f)), vary = fams.filter((f) => written.has(f));
589
+ if (inv.length !== 1 || vary.length !== 1) return null;
590
+ const only = !body.slice(0, -1).some((x) => x.kind !== 'other');
591
+ return { bound: inv[0], varying: vary[0], only, body, written };
592
+ }
593
+ export function isRemainder(s, a, b) {
594
+ if (!(a.end < b.begin)) return false;
595
+ const ea = loopExit(s, a), eb = loopExit(s, b);
596
+ if (!ea || !eb || !ea.only || ea.bound !== eb.bound) return false;
597
+ const c0 = eb.varying;
598
+ if (!eb.body.every((x) => { const w = writes(x); return w !== null && (!w.includes(c0) || advances(x, c0)); })) return false;
599
+ // between the loops: the bound is not written; c is only advanced, or copied from a register the same holds for
600
+ let c = c0;
601
+ const between = s.instrs.filter((x) => x.line > a.end && x.line < b.begin);
602
+ for (let k = between.length - 1; k >= 0; k--) {
603
+ const x = between[k], w = writes(x);
604
+ if (w === null || w.includes(eb.bound)) return false;
605
+ if (!w.includes(c)) continue;
606
+ if (advances(x, c)) continue;
607
+ const ops = operandsOf(x);
608
+ if (/^mov[lq]?$/i.test(x.mnemonic) && ops.length === 2) {
609
+ const src = GPR_FAMILY(ATT(x) ? ops[0] : ops[1]);
610
+ if (src && src !== c) { c = src; continue; }
611
+ }
612
+ return false;
613
+ }
614
+ // c in a is a's compared register, or a copy of it or of it plus a constant (lea c, [varying + k]): its last write in a
615
+ return offsetOf(ea.body, c, ea.varying) || offsetOf(ea.body, ea.varying, c, true);
616
+ }
617
+
618
+ // In a loop's body (straight code), whether y ends as x plus a constant: the last write of y copies x or x plus a constant
619
+ // (mov, lea). first: whether, instead, y's first write so copies x and y and x are otherwise only advanced.
620
+ function offsetOf(body, y, x, first = false) {
621
+ if (y === x) return true;
622
+ const ws = body.filter((i) => (writes(i) ?? []).includes(y));
623
+ const copy = first ? ws[0] : ws[ws.length - 1];
624
+ if (!copy || !copiesPlus(copy, y, x)) return false;
625
+ if (!first) return true;
626
+ return ws.slice(1).every((i) => advances(i, y)) && body.filter((i) => (writes(i) ?? []).includes(x)).every((i) => advances(i, x));
627
+ }
628
+ // mov y, x or lea y, [x + k]
629
+ function copiesPlus(i, y, x) {
630
+ const ops = operandsOf(i);
631
+ if (ops.length !== 2) return false;
632
+ const [src, dst] = ATT(i) ? ops : [ops[1], ops[0]];
633
+ if (GPR_FAMILY(dst) !== y) return false;
634
+ if (/^mov[lq]?$/i.test(i.mnemonic)) return GPR_FAMILY(src) === x;
635
+ if (!/^lea[lqw]?$/i.test(i.mnemonic)) return false;
636
+ const m = ATT(i) ? /^-?(?:0x[0-9a-f]+|\d+)?\((%\w+)\)$/i.exec(src) : /^(?:\w+\s+ptr\s+)?\[\s*(\w+)\s*(?:[+-]\s*(?:0x[0-9a-f]+|\d+))?\s*\]$/i.exec(src);
637
+ return !!m && GPR_FAMILY(m[1]) === x;
638
+ }
639
+
640
+ // The index of the loop analyzed by default (see above) in a list of findLoops (or a part of it), or -1 for none.
641
+ export function defaultLoop(loops) {
642
+ if (!loops.length) return -1;
643
+ // the first of the deepest innermost loops (by depth: the list is ordered by listDepth, findLoops)
644
+ const inner = loops.some((l) => l.inner) ? loops.filter((l) => l.inner) : loops;
645
+ const deepest = Math.max(...inner.map((l) => l.depth));
646
+ const top = /** @type {any} */ (inner.find((l) => l.depth === deepest));
647
+ let best = -1;
648
+ loops.forEach((l, k) => {
649
+ if (l.inner !== top.inner || l.depth !== top.depth || (l.function ?? null) !== (top.function ?? null)) return;
650
+ // the remainder of another of these loops is not the default
651
+ if (l.remainderOf?.some((at) => loops.some((a) => a.begin === at && a.inner === top.inner && a.depth === top.depth && (a.function ?? null) === (top.function ?? null)))) return;
652
+ if (best < 0 || betterDefault(l, loops[best])) best = k;
653
+ });
654
+ return best;
655
+ }
656
+
657
+ // a before b as the default (rules 2 and 3 above)
658
+ function betterDefault(a, b) {
659
+ const va = a.vector ?? { width: 0, count: 0 }, vb = b.vector ?? { width: 0, count: 0 };
660
+ return (va.width - vb.width || va.count - vb.count || (a.instructions ?? 0) - (b.instructions ?? 0) || b.begin - a.begin) > 0;
424
661
  }
425
662
 
426
663
  const PROLOGUE = [
@@ -487,7 +724,7 @@ export function preparePaste(text, { loop = 'auto', func = null } = {}) {
487
724
  }
488
725
  const named = (l) => (l.label.startsWith('.Lwuica_a') ? `0x${l.label.slice(9)}` : l.label);
489
726
  // a loop by its label ("-loop .LBB0_12", "-loop 0x10"): as its index
490
- if (typeof loop === 'string' && loop !== 'auto' && loop !== 'whole') {
727
+ if (typeof loop === 'string' && loop !== 'auto' && loop !== 'whole' && loop !== LEGACY_AUTO) {
491
728
  const name = loop;
492
729
  const hits = loops.flatMap((l, i) => (named(l) === name || l.label === name || named(l) === `.${name}` || (/^0x/i.test(name) && named(l).toLowerCase() === name.toLowerCase()) ? [i] : []));
493
730
  const k = hits.length ? hits[0] : -1;
@@ -505,8 +742,8 @@ export function preparePaste(text, { loop = 'auto', func = null } = {}) {
505
742
  }
506
743
  /** @type {any} */
507
744
  const out = { text: asm, objdump: od.objdump, loops: loops.map((l) => ({ begin: l.begin, end: l.end, label: named(l), function: l.function, instructions: l.instructions, depth: l.depth, inner: l.inner })),
508
- choice: null, choosable: false, pick: null, body: null, alignment: null, address: null, stubs: [], notes: [], fallback: new Map() };
509
- if (loop !== 'auto' && loop !== 'whole' && !(Number.isInteger(loop) && loop >= 0)) {
745
+ choice: null, auto: false, choosable: false, pick: null, body: null, alignment: null, address: null, stubs: [], notes: [], fallback: new Map() };
746
+ if (loop !== 'auto' && loop !== 'whole' && loop !== LEGACY_AUTO && !(Number.isInteger(loop) && loop >= 0)) {
510
747
  out.error = `loop: ${JSON.stringify(loop)} is not "auto", "whole", the index of a loop (0-based) or its label`;
511
748
  return out;
512
749
  }
@@ -531,7 +768,9 @@ export function preparePaste(text, { loop = 'auto', func = null } = {}) {
531
768
  if (pf.unweighted) out.notes.push({ line: null, column: null, severity: 'note', message: 'perf annotate: a symbol\'s header has no sample count, so the samples are each symbol\'s own percentages (not of all the samples)' });
532
769
  // perf annotate with several loops: "auto" picks the one whose own instructions (not those of a loop nested in it)
533
770
  // have the most samples, the first of equals
534
- if (pf.perf && loop === 'auto' && loops.length > 1) {
771
+ // the pick is the default (out.auto: the page says so; not for LEGACY_AUTO, a link's own pick)
772
+ const automatic = loop === 'auto';
773
+ if (pf.perf && (loop === 'auto' || loop === LEGACY_AUTO) && loops.length > 1) {
535
774
  const inside = (a, b) => a !== b && a.begin >= b.begin && a.end <= b.end;
536
775
  const heat = loops.map((l) => code.filter((x) => x.line >= l.begin && x.line <= l.end && !loops.some((n) => inside(n, l) && x.line >= n.begin && x.line <= n.end))
537
776
  .reduce((n, x) => n + (pf.samples.get(x.line) ?? 0), 0));
@@ -554,7 +793,7 @@ export function preparePaste(text, { loop = 'auto', func = null } = {}) {
554
793
  }
555
794
  if (out.choosable && loop !== 'whole') {
556
795
  if (loops.length) {
557
- const k = Number.isInteger(loop) ? loop : 0;
796
+ const k = Number.isInteger(loop) ? loop : loop === LEGACY_AUTO ? 0 : defaultLoop(loops);
558
797
  out.choice = k;
559
798
  out.pick = { begin: loops[k].begin, end: loops[k].end };
560
799
  } else {
@@ -563,6 +802,7 @@ export function preparePaste(text, { loop = 'auto', func = null } = {}) {
563
802
  }
564
803
  // the source line of each instruction of the pick (caveats.js names lines with them)
565
804
  out.pick = { ...out.pick, lines: code.filter((x) => x.line >= out.pick.begin && x.line <= out.pick.end).map((x) => x.line) };
805
+ out.auto = automatic;
566
806
  }
567
807
  }
568
808
  // data directives among the analyzed instructions (the pick's, or the whole text's): their bytes are instructions of
@@ -594,8 +834,8 @@ export function preparePaste(text, { loop = 'auto', func = null } = {}) {
594
834
  return out;
595
835
  }
596
836
 
597
- // A text that replaces an editor's text (a paste over most of it, an example, an import) starts with the first loop again (the page's
598
- // pick goes back to auto).
837
+ // A text that replaces an editor's text (a paste over most of it, an example, an import) starts with the default loop again (the
838
+ // page's pick goes back to auto).
599
839
  // Not an edit: what the old and the new text share at their start and end is less than half of the old one.
600
840
  export function replacesText(before, after) {
601
841
  if (before === after) return false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wuica-cli",
3
- "version": "0.1.10",
3
+ "version": "0.1.12",
4
4
  "description": "x86-64 basic-block throughput prediction in WebAssembly: a bit-exact Rust/WebAssembly port of uiCA, as a library, a CLI and an MCP server",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
@@ -58,5 +58,8 @@
58
58
  "url": "git+https://github.com/jtl06/wuica.git",
59
59
  "directory": "packages/wuica"
60
60
  },
61
- "homepage": "https://wuica.jacen.li"
61
+ "homepage": "https://wuica.jacen.li",
62
+ "bugs": {
63
+ "url": "https://github.com/jtl06/wuica/issues"
64
+ }
62
65
  }