wuica-cli 0.1.9 → 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.
@@ -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
@@ -29,6 +31,8 @@ const MARKER = /^\s*(?:#|\/\/|;)\s*(?:LLVM-MCA-BEGIN|wuica-begin)(?![\w-])/im;
29
31
  const IACA = /^\s*mov[l]?\s+(?:ebx\s*,\s*111|\$111\s*,\s*%ebx)\s*$/im;
30
32
  const LABELS = /^(?:\s*(?:[\w.$@]+|"[^"]*")\s*:)*\s*/;
31
33
  const LABEL_ONE = /\s*([\w.$@]+|"[^"]*")\s*:/y;
34
+ // data directives: bytes in the code that are not an instruction's line
35
+ const DATA = /^(?:byte|short|word|hword|long|int|quad|octa|zero|fill|space|skip|ascii|asciz|string(?:8|16|32|64)?|[248]byte|value|single|float|double|[su]leb128|incbin|dc(?:b|\.\w)?|ds(?:\.\w)?)$/;
32
36
  const PREFIX = /^(?:lock|rep|repe|repz|repne|repnz|bnd|notrack|data16|data32|addr32|cs|ds|es|ss|fs|gs|rex(?:\.\w+)?|\{[\w ]+\})$/i;
33
37
  export const JCC = /^(?:j(?:a|ae|b|be|c|e|g|ge|l|le|na|nae|nb|nbe|nc|ne|ng|nge|nl|nle|no|np|ns|nz|o|p|pe|po|s|z|rcxz|ecxz)|loop(?:e|ne|z|nz)?|xbegin)$/i;
34
38
  export const JMP = /^jmp[lqw]?$/i;
@@ -37,8 +41,13 @@ const RET = /^ret[lqw]?$/i;
37
41
  const SYMBOL = /^[A-Za-z_.$@][\w.$@]*$/;
38
42
  const GPR = /^(?:[re]?(?:ax|bx|cx|dx|si|di|sp|bp|ip)|[abcd][lh]|(?:si|di|sp|bp)l|r(?:[89]|1[0-5])[dwb]?)$/i;
39
43
 
40
- export const OUTSIDE_PREFIX = '.Lwuica_x'; // an objdump branch to an address that is not in the text
44
+ export const OUTSIDE_PREFIX = '.Lwuica_x';
45
+ // directives after which the lines of a text are not its instructions one to one
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
41
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';
42
51
 
43
52
  // Splits a line (block comments already removed) into its statements outside comments: [{at, text}] (at: the column
44
53
  // of the statement's first character, 0-based). '#' and '//' start a comment, ';' separates statements; quotes kept.
@@ -63,13 +72,14 @@ export function statements(line) {
63
72
  // The syntax of assembly text: 'att' or 'intel' (null: no sign of either). A directive (.att_syntax, .intel_syntax
64
73
  // [noprefix]) before the first instruction decides; else the signs: AT&T's %registers, $immediates and (%base,...)
65
74
  // memory operands against Intel's "ptr [" and [register...] operands. Comments are left out.
75
+ /** @returns {'att' | 'intel' | null} */
66
76
  export function detectSyntax(text) {
67
77
  const lines = normalizeText(text).split('\n');
68
78
  let att = 0, intel = 0;
69
79
  for (const l of lines) {
70
80
  const code = l.replace(/(?:#|\/\/).*$/, '');
71
81
  const d = /^\s*\.(att|intel)_syntax\b/i.exec(code);
72
- if (d && att + intel === 0) return d[1].toLowerCase();
82
+ if (d && att + intel === 0) return /** @type {'att' | 'intel'} */ (d[1].toLowerCase());
73
83
  const n = syntaxSigns(code);
74
84
  att += n.att;
75
85
  intel += n.intel;
@@ -119,13 +129,16 @@ function byteColumn(rest) {
119
129
  // One-byte instructions that have operands (an objdump step of 1 for an instruction with operands must be one of these).
120
130
  const ONE_BYTE = /^(?:push|pop|xchg|in|out|ins\w*|outs\w*|stos\w*|lods\w*|movs\w*|scas\w*|cmps\w*|bswap|int)$/i;
121
131
 
122
- // {text, objdump: true, addresses: Map line -> address, bytes: Map line -> the line as .byte} or {objdump: false}.
132
+ // {text, objdump: true, addresses: Map line -> address, bytes: Map line -> the line as .byte, sources: Map line -> the
133
+ // source line in force (objdump -dS, -S: the interleaved source text, llvm-objdump's after "; ")} or {objdump: false}.
134
+ /** @returns {any} */
123
135
  export function fromObjdump(text) {
124
136
  const lines = normalizeText(text).split('\n');
125
137
  let header = false, symbolic = false, column = false, increasing = true, other = 0, plausible = true;
126
138
  const rows = [];
139
+ let last = -1; // (addresses increase within a function; perf annotate prints its functions in any order)
127
140
  for (const l of lines) {
128
- if (OD_HEADER.test(l)) { header = true; continue; }
141
+ if (OD_HEADER.test(l)) { header = true; last = -1; continue; }
129
142
  if (OD_NOISE.test(l) || /^\s*(?:$|#|\/\/|;)/.test(l)) continue;
130
143
  const m = OD_ADDR.exec(l);
131
144
  if (!m) { other++; continue; }
@@ -133,7 +146,8 @@ export function fromObjdump(text) {
133
146
  if (/<[^>]*>/.test(m[4])) symbolic = true;
134
147
  const bc = byteColumn(m[4]);
135
148
  if (bc.bytes && /\t| /.test(m[4])) column = true;
136
- if (rows.length && a <= rows.at(-1).a) increasing = false;
149
+ if (a <= last) increasing = false;
150
+ last = a;
137
151
  rows.push({ a, rest: bc.rest });
138
152
  }
139
153
  if (rows.length < 2 || !increasing) return { objdump: false };
@@ -150,6 +164,7 @@ export function fromObjdump(text) {
150
164
  if (rows.some((r) => /^\s*(?:\S+\s+)*?(?:j[a-z]{1,4}|jmp\w*|call\w*|loop[a-z]*)\s+\d+[bf]\s*$/i.test(r.rest))) return { objdump: false };
151
165
  }
152
166
 
167
+ /** @type {any[]} */
153
168
  const parsed = lines.map((l) => {
154
169
  // a function's header ("0000000000000020 <fir8>:") becomes its label (the loops' function), if it is a plain name
155
170
  const fh = /^\s*[0-9a-fA-F]+\s+<([A-Za-z_][\w.$]*)>:\s*$/.exec(l);
@@ -182,6 +197,21 @@ export function fromObjdump(text) {
182
197
  else name = `${OUTSIDE_PREFIX}${t.toString(16)}`;
183
198
  p.text = `${b[1]}${b[2]}${b[3]}${name}`;
184
199
  }
200
+ // objdump -S: a source line (llvm-objdump: "; text"; GNU objdump: the text itself) holds for the instructions after it,
201
+ // up to the next one or the next function; GNU's -l lines ("/path/file.c:12", "dot():") are not source text
202
+ const sources = new Map();
203
+ /** @type {string | null} */
204
+ let src = null;
205
+ lines.forEach((l, k) => {
206
+ const p = parsed[k];
207
+ if (p.kind === 'instr') { if (src !== null) sources.set(k + 1, src); return; }
208
+ if (/^\s*[0-9a-fA-F]+\s+<[^>]*>:\s*$/.test(l)) { src = null; return; }
209
+ if (OD_HEADER.test(l) || OD_NOISE.test(l) || p.kind === 'more' || /^\s*$/.test(l) || /^\s*\/\//.test(l)) return;
210
+ // (llvm-objdump's "; " is "# " here: a ';' that starts a line is read as '#', leadingSemicolons)
211
+ const t = l.replace(/^\s*[;#]\s?/, '').trim();
212
+ if (!t || /^\S+:\d+(?:\s*\(discriminator \d+\))?$/.test(t) || /^[\w.$]+\(\):$/.test(t)) return;
213
+ src = t;
214
+ });
185
215
  const addresses = new Map(), byteMap = new Map();
186
216
  const out = parsed.map((p, k) => {
187
217
  if (p.kind === 'blank' || p.kind === 'more') return '';
@@ -191,7 +221,62 @@ export function fromObjdump(text) {
191
221
  if (p.bytes?.length) byteMap.set(k + 1, `${p.indent}${label}.byte ${p.bytes.map((b) => '0x' + b.toString(16).padStart(2, '0')).join(', ')}`);
192
222
  return `${p.indent}${label}${p.text}`;
193
223
  });
194
- return { objdump: true, text: out.join('\n'), addresses, bytes: byteMap };
224
+ return { objdump: true, text: out.join('\n'), addresses, bytes: byteMap, sources };
225
+ }
226
+
227
+ // ---- perf annotate --------------------------------------------------------------------------------------------------
228
+
229
+ // `perf annotate --stdio` output: one block per symbol, each with its header ("Percent | Source code & Disassembly of hot
230
+ // for cycles:u (1069 samples, percent: local period)") and its lines: an instruction " 22.59 : 1413: movaps ...",
231
+ // anything else after an empty percent column " :" (perf 7 numbers those lines: " : 39 s += m[...]"). Read as the same
232
+ // lines of objdump text (an instruction as " 1413:\tmovaps ...", a source line as "; text", the function header as is),
233
+ // line for line. samples: Map line -> the instruction's percent of all the samples of the output: a block's local
234
+ // percentages (perf's default) are of its own symbol's samples, weighted by the sample count of its header (an
235
+ // approximation of perf's global-period, which weighs by period); global ones, or without a header, as given. {text,
236
+ // perf: true, samples} or {perf: false} (stdio2: true for `perf annotate --stdio2` output, which has no addresses).
237
+ const PERF_INSN = /^\s*(\d+(?:\.\d+)?)\s*:\s+([0-9a-fA-F]+):\s+(\S.*)$/;
238
+ const PERF_OTHER = /^\s*:\s?(.*)$/;
239
+ const PERF_HEADER = /^\s*Percent\s*\|/;
240
+ const PERF_COUNT = /\((\d[\d,.'\u00a0\u202f]*) samples\b/; // (with a locale's thousands separators: "5,000")
241
+ const PERF_TYPE = /percent: ([^),]*)/;
242
+ /** @returns {any} */
243
+ export function fromPerfAnnotate(text) {
244
+ const lines = normalizeText(text).split('\n');
245
+ if (lines.filter((l) => PERF_INSN.test(l)).length < 2 || !lines.some((l) => /^\s*Percent\s*\|/.test(l) || PERF_OTHER.test(l))) {
246
+ const stdio2 = /^Samples: .*\[percent: /m.test(lines.slice(0, 5).join('\n')) && lines.some((l) => /^Percent\s{2,}\S/.test(l));
247
+ return { perf: false, stdio2 };
248
+ }
249
+ const local = new Map(); // line -> [percent, its block]
250
+ /** @type {{samples: number | null, global: boolean}[]} */
251
+ const blocks = [];
252
+ /** @type {{samples: number | null, global: boolean} | null} */
253
+ let block = null;
254
+ const out = lines.map((l, k) => {
255
+ if (PERF_HEADER.test(l)) {
256
+ // each header its own count (none: unknown, not the previous header's); --percent-type global-*: already of all
257
+ // the samples
258
+ const n = PERF_COUNT.exec(l);
259
+ block = { samples: n ? Number(n[1].replace(/\D/g, '')) : null, global: /global/.test(PERF_TYPE.exec(l)?.[1] ?? '') };
260
+ blocks.push(block);
261
+ return '';
262
+ }
263
+ const m = PERF_INSN.exec(l);
264
+ if (m) { local.set(k + 1, [Number(m[1]), block]); return ` ${m[2]}:\t${m[3].trim()}`; }
265
+ const o = PERF_OTHER.exec(l);
266
+ if (!o) return ''; // the header's rule, a summary
267
+ const t = o[1].trim().replace(/^\d+\s+/, ''); // (perf 7: the listing's line number first)
268
+ if (!t || /^Disassembly of section\b/.test(t)) return '';
269
+ if (/^[0-9a-fA-F]+\s+<[^>]*>:$/.test(t)) return t;
270
+ return `; ${t}`;
271
+ });
272
+ // the percent of all samples: each block's local percentages weighted by its samples, if every such block has its
273
+ // count (one block: as given); else each symbol's own percentages, as given (unweighted: true)
274
+ const locals = blocks.filter((b) => !b.global);
275
+ const unweighted = locals.length > 1 && locals.some((b) => b.samples === null);
276
+ const total = unweighted ? 0 : locals.reduce((a, b) => a + (b.samples ?? 0), 0);
277
+ const samples = new Map();
278
+ for (const [line, [p, b]] of local) samples.set(line, total > 0 && b && !b.global && b.samples !== null ? Math.round(p * b.samples / total * 100) / 100 : p);
279
+ return { perf: true, text: out.join('\n'), samples, unweighted };
195
280
  }
196
281
 
197
282
  // ---- the statements of a text ----------------------------------------------------------------------------------------
@@ -208,19 +293,24 @@ const sectionName = (args) => (/^\s*("?)([^",\s]+)\1/.exec(args)?.[2] ?? '');
208
293
  export const isText = (args) => { const n = sectionName(args); return n === '.text' || n.startsWith('.text.'); };
209
294
 
210
295
  // {labels: Map name -> line, symbols: Set (assigned with = / .set / .equ), instrs: [{line, col, mnemonic, operands,
211
- // kind: 'jcc' | 'jmp' | 'call' | 'ret' | 'other', target}], numeric: [{name, line}]}. Lines 1-based; only .text code.
296
+ // kind: 'jcc' | 'jmp' | 'call' | 'ret' | 'other', target}], numeric: [{name, line}], data: [line]}. Lines 1-based; only
297
+ // .text code. A prefix alone on its line ("lock", then "add [rdi], eax") is part of the next instruction, not one of its
298
+ // own; data: the lines of data directives in code (.byte, .fill, ...: bytes the instructions cannot be told from).
212
299
  export function scan(text) {
213
300
  const raw = String(text).split('\n');
214
301
  const lines = blankBlockComments(String(text)).split('\n');
215
- // 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",
216
303
  // "# in Loop: Header=BB0_4 Depth=1"): label -> text
217
304
  const notes = new Map();
218
- const labels = new Map(), symbols = new Set(), instrs = [], numeric = [], functions = new Set();
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();
308
+ const labels = new Map(), symbols = new Set(), instrs = [], numeric = [], functions = new Set(), data = [];
219
309
  let inText = true, prev = true, directives = 0;
220
310
  const stack = [];
221
311
  for (let i = 0; i < lines.length; i++) {
222
312
  for (const st of statements(lines[i])) {
223
- const lead = LABELS.exec(st.text)[0].length;
313
+ const lead = /** @type {RegExpExecArray} */ (LABELS.exec(st.text))[0].length;
224
314
  LABEL_ONE.lastIndex = 0;
225
315
  let m;
226
316
  const head = st.text.slice(0, lead);
@@ -229,8 +319,13 @@ export function scan(text) {
229
319
  if (/^\d+$/.test(name)) numeric.push({ name, line: i + 1, inText });
230
320
  else if (!labels.has(name)) {
231
321
  labels.set(name, { line: i + 1, inText });
232
- 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]}`;
233
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);
234
329
  }
235
330
  }
236
331
  const body = st.text.slice(lead).trim();
@@ -240,6 +335,7 @@ export function scan(text) {
240
335
  const name = d?.[1].toLowerCase() ?? '';
241
336
  const args = d?.[2] ?? '';
242
337
  directives++;
338
+ if (inText && DATA.test(name)) data.push(i + 1);
243
339
  if (name === 'set' || name === 'equ' || name === 'equiv') { const s = /^([\w.$@]+)/.exec(args); if (s) symbols.add(s[1]); }
244
340
  else if (name === 'globl' || name === 'global') { const s = /^([\w.$@]+)/.exec(args); if (s) functions.add(s[1]); }
245
341
  else if (name === 'type') { const s = /^([\w.$@]+)\s*,\s*[@%]function/.exec(args); if (s) functions.add(s[1]); }
@@ -254,6 +350,7 @@ export function scan(text) {
254
350
  const assign = /^([\w.$@]+)\s*=/.exec(body);
255
351
  if (assign) { symbols.add(assign[1]); continue; }
256
352
  if (!inText) continue;
353
+ if (body.split(/\s+/).every((w) => PREFIX.test(w))) continue; // a prefix alone: the next instruction's
257
354
  const { mnemonic, operands } = splitInstr(body);
258
355
  let kind = 'other', target = null;
259
356
  if (JCC.test(mnemonic)) kind = 'jcc';
@@ -267,7 +364,7 @@ export function scan(text) {
267
364
  instrs.push({ line: i + 1, col: st.at + lead, end: st.at + st.text.length, mnemonic, operands, kind, target, body });
268
365
  }
269
366
  }
270
- return { labels, symbols, instrs, numeric, functions, directives, notes };
367
+ return { labels, symbols, instrs, numeric, functions, directives, notes, shortNotes, data };
271
368
  }
272
369
 
273
370
  // The line a branch target refers to (a label, or a numeric label "1b" / "1f" seen from `line`), or null.
@@ -282,8 +379,9 @@ function targetLine(s, target, line) {
282
379
  return l && l.inText ? l.line : null;
283
380
  }
284
381
 
285
- // The loops: [{begin, end, label, inner}] (begin: the label's line, end: the last branch back to it; 1-based), innermost first,
286
- // 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.
287
385
  export function findLoops(s) {
288
386
  const loops = [];
289
387
  for (const ins of s.instrs) {
@@ -307,7 +405,7 @@ export function findLoops(s) {
307
405
  const keyOf = (label) => {
308
406
  const n = s.notes.get(label) ?? '';
309
407
  if (/This (?:Inner )?Loop Header/.test(n) || !/Header=(\w+)/.test(n)) return label.replace(/^\.L/, '');
310
- return /Header=(\w+)/.exec(n)[1];
408
+ return /** @type {RegExpExecArray} */ (/Header=(\w+)/.exec(n))[1];
311
409
  };
312
410
  const groups = new Map();
313
411
  for (const l of real) {
@@ -318,25 +416,248 @@ export function findLoops(s) {
318
416
  merged = [...groups.values()].map((g) => {
319
417
  const header = `.L${g.key}`;
320
418
  const label = s.labels.has(header) ? header : g.label;
321
- const note = s.notes.get(label) ?? '';
322
- const d = /Loop Header: Depth=(\d+)/.exec(note) ?? /Depth=(\d+)/.exec(note);
323
- 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) ?? '') };
324
421
  });
325
422
  }
326
423
  for (const l of merged) {
327
424
  l.inner = !merged.some((o) => o !== l && o.begin >= l.begin && o.end <= l.end && (o.begin !== l.begin || o.end !== l.end));
328
425
  // nesting depth: 1 for a loop in no other (clang's Depth when it says)
329
- 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;
330
433
  delete l.clangDepth;
434
+ delete l.shortDepth;
331
435
  l.instructions = s.instrs.filter((x) => x.line >= l.begin && x.line <= l.end).length;
332
436
  // the function it is in: the last label before it that is not local
333
437
  let fname = null, at = -1;
334
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; }
335
439
  l.function = fname;
336
440
  }
337
- // the innermost and deepest first; among equals, the first in the code (gcc puts the main loop first, clang often its
338
- // remainder loop: -loops lists them all)
339
- 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;
340
661
  }
341
662
 
342
663
  const PROLOGUE = [
@@ -374,10 +695,18 @@ export function functionBody(s) {
374
695
  // What to analyze: see the top. text: the pasted assembly; loop: 'auto' (default), 'whole', or the index of a loop.
375
696
  // Returns {text, objdump, loops: [{begin, end, label}], choice: index | 'body' | null, choosable (there is code around the
376
697
  // loop or the body: a choice matters), pick: {begin, end, lines: [the line of each instruction]} | null,
377
- // body: {begin, end} | null, alignment: number | null, address: number | null, stubs: [names],
698
+ // body: {begin, end} | null, alignment: number | null, address: number | null, stubs: [names], lines: [the line of each
699
+ // instruction of the text],
378
700
  // notes: [{line, column, severity, message}], fallback: Map line -> text, error?}
701
+ /**
702
+ * @param {string} text
703
+ * @param {{loop?: string | number, func?: string | null}} [opts]
704
+ * @returns {any}
705
+ */
379
706
  export function preparePaste(text, { loop = 'auto', func = null } = {}) {
380
- let t = leadingSemicolons(normalizeText(text).replace(/^/, ''));
707
+ const pf = fromPerfAnnotate(normalizeText(text).replace(/^/, ''));
708
+ if (pf.stdio2) return { error: 'input: this is perf annotate --stdio2 output, which has no addresses: use perf annotate --stdio', loops: [] };
709
+ let t = leadingSemicolons(pf.perf ? pf.text : normalizeText(text).replace(/^/, ''));
381
710
  const od = fromObjdump(t);
382
711
  if (od.objdump) t = od.text;
383
712
  // code sections other than .text (gcc's main in .text.startup, -ffunction-sections): into .text, which the assembler
@@ -395,8 +724,9 @@ export function preparePaste(text, { loop = 'auto', func = null } = {}) {
395
724
  }
396
725
  const named = (l) => (l.label.startsWith('.Lwuica_a') ? `0x${l.label.slice(9)}` : l.label);
397
726
  // a loop by its label ("-loop .LBB0_12", "-loop 0x10"): as its index
398
- if (typeof loop === 'string' && loop !== 'auto' && loop !== 'whole') {
399
- const hits = loops.flatMap((l, i) => (named(l) === loop || l.label === loop || named(l) === `.${loop}` || (/^0x/i.test(loop) && named(l).toLowerCase() === loop.toLowerCase()) ? [i] : []));
727
+ if (typeof loop === 'string' && loop !== 'auto' && loop !== 'whole' && loop !== LEGACY_AUTO) {
728
+ const name = loop;
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] : []));
400
730
  const k = hits.length ? hits[0] : -1;
401
731
  // the same label in several functions (numeric labels: "1:" ... "jnz 1b"): not a guess
402
732
  if (hits.length > 1) return { error: `loop: ${JSON.stringify(loop)} names ${hits.length} loops (${hits.map((i) => `${i} in ${loops[i].function ?? 'no function'}`).join(', ')}): -func NAME or -loop N (0-based) picks one`, loops: [] };
@@ -410,14 +740,43 @@ export function preparePaste(text, { loop = 'auto', func = null } = {}) {
410
740
  for (const [line, b] of od.bytes) lines[line - 1] = b;
411
741
  asm = lines.join('\n');
412
742
  }
743
+ /** @type {any} */
413
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 })),
414
- choice: null, choosable: false, pick: null, body: null, alignment: null, address: null, stubs: [], notes: [], fallback: new Map() };
415
- 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)) {
416
747
  out.error = `loop: ${JSON.stringify(loop)} is not "auto", "whole", the index of a loop (0-based) or its label`;
417
748
  return out;
418
749
  }
419
750
  const code = s.instrs;
420
- if (Number.isInteger(loop) && loop >= loops.length) {
751
+ // .rept, .irp, .irpc, .macro and .if* make a line something else than one instruction (repeated, left out, a macro's
752
+ // call): no source lines then, and no loop picked (it could not be isolated): the whole text, said in a note
753
+ const structural = STRUCTURAL.exec(t);
754
+ out.exactLines = !structural;
755
+ if (structural && loop !== 'whole' && loops.length) {
756
+ const at = t.slice(0, structural.index).split('\n').length;
757
+ out.notes.push({ line: at, column: null, severity: 'note', message: `${structural[1]}: the text repeats or leaves out lines, so a loop cannot be isolated: the whole text is analyzed` });
758
+ loop = 'whole';
759
+ }
760
+ out.lines = code.map((x) => x.line);
761
+ // per instruction line: the interleaved source line (objdump -S, perf annotate) and the percent of samples (perf)
762
+ out.lineInfo = new Map();
763
+ for (const x of code) {
764
+ const source = od.objdump ? od.sources?.get(x.line) : undefined, samples = pf.perf ? pf.samples.get(x.line) : undefined;
765
+ if (source !== undefined || samples !== undefined) out.lineInfo.set(x.line, { ...(source !== undefined ? { source } : {}), ...(samples !== undefined ? { samples } : {}) });
766
+ }
767
+ out.profile = pf.perf ? 'perf' : null;
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)' });
769
+ // perf annotate with several loops: "auto" picks the one whose own instructions (not those of a loop nested in it)
770
+ // have the most samples, the first of equals
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) {
774
+ const inside = (a, b) => a !== b && a.begin >= b.begin && a.end <= b.end;
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))
776
+ .reduce((n, x) => n + (pf.samples.get(x.line) ?? 0), 0));
777
+ loop = heat.indexOf(Math.max(...heat));
778
+ }
779
+ if (Number.isInteger(loop) && Number(loop) >= loops.length) {
421
780
  out.error = `loop: ${loop} is not the index of a loop (0-based; the text has ${loops.length === 0 ? 'none' : `${loops.length}: 0 to ${loops.length - 1}`})`;
422
781
  return out;
423
782
  }
@@ -428,13 +787,13 @@ export function preparePaste(text, { loop = 'auto', func = null } = {}) {
428
787
  // a compiler's function (a function label, directives, objdump, or a prologue/epilogue): its body; a bare snippet
429
788
  // ("add rax, 1 / ret") is analyzed as typed
430
789
  const b = functionBody(s);
431
- const compiled = od.objdump || s.directives > 0 || [...s.labels.keys()].some((n) => !n.startsWith('.L') && !/^\d+$/.test(n)) || b?.trimmed > 0;
790
+ const compiled = od.objdump || s.directives > 0 || [...s.labels.keys()].some((n) => !n.startsWith('.L') && !/^\d+$/.test(n)) || (b?.trimmed ?? 0) > 0;
432
791
  out.body = b && compiled ? { begin: b.begin, end: b.end } : null;
433
792
  out.choosable = !!out.body;
434
793
  }
435
794
  if (out.choosable && loop !== 'whole') {
436
795
  if (loops.length) {
437
- const k = Number.isInteger(loop) ? loop : 0;
796
+ const k = Number.isInteger(loop) ? loop : loop === LEGACY_AUTO ? 0 : defaultLoop(loops);
438
797
  out.choice = k;
439
798
  out.pick = { begin: loops[k].begin, end: loops[k].end };
440
799
  } else {
@@ -443,8 +802,12 @@ export function preparePaste(text, { loop = 'auto', func = null } = {}) {
443
802
  }
444
803
  // the source line of each instruction of the pick (caveats.js names lines with them)
445
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;
446
806
  }
447
807
  }
808
+ // data directives among the analyzed instructions (the pick's, or the whole text's): their bytes are instructions of
809
+ // their own or parts of one, so the lines are not the instructions one to one: none
810
+ if (s.data.some((l) => !out.pick || (l >= out.pick.begin && l <= out.pick.end))) out.exactLines = false;
448
811
  // the exits: conditional branches (and jumps to .L labels) whose target the text does not define
449
812
  const defined = (name) => s.labels.has(name) || s.symbols.has(name);
450
813
  const seen = new Set();
@@ -471,8 +834,8 @@ export function preparePaste(text, { loop = 'auto', func = null } = {}) {
471
834
  return out;
472
835
  }
473
836
 
474
- // 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
475
- // 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).
476
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.
477
840
  export function replacesText(before, after) {
478
841
  if (before === after) return false;