@go-go-golems/compiler-toolkit 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,67 @@
1
+ // std/dataflow.js — a worklist solver for monotone dataflow problems over any graph view, in either direction. Ported
2
+ // from the workbench's stdlib (src/stdlib/flow/solve.ts) without its round-robin schedule; the lattice is the
3
+ // caller's: { bottom(), join(a, b), equal(a, b) } (tk.lattice.sets is one), plus an optional widen at loop heads.
4
+
5
+ import { TkError } from '../diag.js';
6
+ import { asGraph, depthFirst } from './graph.js';
7
+
8
+ export function dataflow(
9
+ view,
10
+ { dir = 'forward', bottom, join, equal, transfer, boundary, widen, max = 100_000 },
11
+ ) {
12
+ for (const [k, f] of Object.entries({ bottom, join, equal, transfer }))
13
+ if (typeof f !== 'function')
14
+ throw new TypeError(`dataflow: '${k}' is a function (spread a lattice such as tk.lattice.sets)`);
15
+ const g = asGraph(view);
16
+ const fwd = dir === 'forward';
17
+ if (!fwd && dir !== 'backward')
18
+ throw new TypeError(`dataflow: dir is 'forward' or 'backward', got '${dir}'`);
19
+ const { postorder, retreating } = depthFirst(g);
20
+ const heads = new Set(retreating.map(e => e.to));
21
+ const preds = new Map(g.nodes.map(n => [n, []]));
22
+ for (const n of g.nodes) for (const s of g.succ(n)) preds.get(s)?.push(n);
23
+ const IN = new Map();
24
+ const OUT = new Map();
25
+ for (const n of g.nodes) {
26
+ IN.set(n, bottom());
27
+ OUT.set(n, bottom());
28
+ }
29
+ const order = fwd ? [...postorder].reverse() : postorder;
30
+ const reach = new Set(postorder);
31
+ const work = [...order];
32
+ const queued = new Set(work);
33
+ let iterations = 0;
34
+ while (work.length) {
35
+ if (++iterations > max)
36
+ throw new TkError(
37
+ `dataflow: no fixpoint after ${max} visits (is transfer monotone? does the lattice need widen?)`,
38
+ );
39
+ const n = work.shift();
40
+ queued.delete(n);
41
+ const sources = (fwd ? preds.get(n) : g.succ(n)).filter(x => reach.has(x));
42
+ let x = fwd
43
+ ? n === g.entry
44
+ ? (boundary ?? bottom())
45
+ : bottom()
46
+ : sources.length
47
+ ? bottom()
48
+ : (boundary ?? bottom());
49
+ for (const s of sources) x = join(x, fwd ? OUT.get(s) : IN.get(s));
50
+ const before = fwd ? IN.get(n) : OUT.get(n);
51
+ if (widen && heads.has(n)) x = widen(before, x, n);
52
+ if (fwd) IN.set(n, x);
53
+ else OUT.set(n, x);
54
+ const y = transfer(n, x);
55
+ const old = fwd ? OUT.get(n) : IN.get(n);
56
+ if (!equal(old, y)) {
57
+ if (fwd) OUT.set(n, y);
58
+ else IN.set(n, y);
59
+ for (const t of fwd ? g.succ(n) : preds.get(n))
60
+ if (reach.has(t) && !queued.has(t)) {
61
+ work.push(t);
62
+ queued.add(t);
63
+ }
64
+ }
65
+ }
66
+ return { in: n => IN.get(n), out: n => OUT.get(n), iterations };
67
+ }
@@ -0,0 +1,197 @@
1
+ // std/graph.js — graph algorithms over any view { nodes, entry, succ } (a function's blocks, a call graph, anything).
2
+ // Ported from the workbench's stdlib (src/stdlib/graph/: orders, dominators, loops, scc), same algorithms and
3
+ // conventions: Cooper-Harvey-Kennedy dominators (the entry is its own immediate dominator), natural loops grouped by
4
+ // header with the single-outside-predecessor preheader rule.
5
+
6
+ import { TkError, describe } from '../diag.js';
7
+
8
+ /** a function, or a view; a view's entry defaults to its first node */
9
+ export function asGraph(x, opts = {}) {
10
+ if (x && x.graph && x.blocks) x = x.graph;
11
+ if (!x || !Array.isArray(x.nodes) || typeof x.succ !== 'function')
12
+ throw new TypeError(`expected a function or a graph view { nodes, succ, entry? }, got ${describe(x)}`);
13
+ return { nodes: x.nodes, succ: x.succ, entry: opts.root ?? x.entry ?? x.nodes[0] };
14
+ }
15
+
16
+ /** postorder, reverse postorder and the retreating edges of a depth-first walk from the entry */
17
+ export function depthFirst(view) {
18
+ const g = asGraph(view);
19
+ const post = [];
20
+ const retreating = [];
21
+ const state = new Map(); // 1 on the stack, 2 done
22
+ if (g.entry === undefined) return { postorder: [], rpo: [], retreating };
23
+ const stack = [[g.entry, 0, g.succ(g.entry)]];
24
+ state.set(g.entry, 1);
25
+ while (stack.length) {
26
+ const top = stack[stack.length - 1];
27
+ const [n, i, succ] = top;
28
+ if (i < succ.length) {
29
+ top[1]++;
30
+ const s = succ[i];
31
+ const st = state.get(s);
32
+ if (st === 1) retreating.push({ from: n, to: s });
33
+ else if (!st) {
34
+ state.set(s, 1);
35
+ stack.push([s, 0, g.succ(s)]);
36
+ }
37
+ } else {
38
+ stack.pop();
39
+ state.set(n, 2);
40
+ post.push(n);
41
+ }
42
+ }
43
+ return { postorder: post, rpo: [...post].reverse(), retreating };
44
+ }
45
+
46
+ function predecessors(g, within) {
47
+ const preds = new Map(g.nodes.map(n => [n, []]));
48
+ for (const n of g.nodes) for (const s of g.succ(n)) if (!within || within.has(s)) preds.get(s)?.push(n);
49
+ return preds;
50
+ }
51
+
52
+ /** immediate dominators; dominates(a, b); the tree as children lists */
53
+ export function dominators(view, opts = {}) {
54
+ const g = asGraph(view, opts);
55
+ const { rpo } = depthFirst(g);
56
+ const index = new Map(rpo.map((n, i) => [n, i]));
57
+ const preds = predecessors(g);
58
+ const entry = rpo[0];
59
+ const idom = new Map(entry === undefined ? [] : [[entry, entry]]);
60
+ const meet = (a, b) => {
61
+ while (a !== b) {
62
+ while (index.get(a) > index.get(b)) a = idom.get(a);
63
+ while (index.get(b) > index.get(a)) b = idom.get(b);
64
+ }
65
+ return a;
66
+ };
67
+ for (let changed = true; changed; ) {
68
+ changed = false;
69
+ for (const n of rpo) {
70
+ if (n === entry) continue;
71
+ let pick = null;
72
+ for (const p of preds.get(n)) if (idom.has(p)) pick = pick === null ? p : meet(p, pick);
73
+ if (pick !== null && idom.get(n) !== pick) {
74
+ idom.set(n, pick);
75
+ changed = true;
76
+ }
77
+ }
78
+ }
79
+ const dominates = (a, b) => {
80
+ for (let x = b; x !== undefined; ) {
81
+ if (x === a) return true;
82
+ const p = idom.get(x);
83
+ if (p === x) return false;
84
+ x = p;
85
+ }
86
+ return false;
87
+ };
88
+ const children = n => [...idom].filter(([c, p]) => p === n && c !== n).map(([c]) => c);
89
+ return { idom, rpo, dominates, children, idomOf: n => (idom.get(n) === n ? null : (idom.get(n) ?? null)) };
90
+ }
91
+ dominators.on = 'cfg';
92
+
93
+ /** strongly connected components (Tarjan), each SCC after every SCC it reaches: callees before callers */
94
+ export function scc(view) {
95
+ const g = asGraph(view);
96
+ const index = new Map();
97
+ const low = new Map();
98
+ const on = new Set();
99
+ const stack = [];
100
+ const out = [];
101
+ let next = 0;
102
+ for (const root of g.nodes) {
103
+ if (index.has(root)) continue;
104
+ const work = [[root, 0, g.succ(root)]];
105
+ index.set(root, next);
106
+ low.set(root, next++);
107
+ stack.push(root);
108
+ on.add(root);
109
+ while (work.length) {
110
+ const top = work[work.length - 1];
111
+ const [n, i, succ] = top;
112
+ if (i < succ.length) {
113
+ top[1]++;
114
+ const s = succ[i];
115
+ if (!index.has(s)) {
116
+ index.set(s, next);
117
+ low.set(s, next++);
118
+ stack.push(s);
119
+ on.add(s);
120
+ work.push([s, 0, g.succ(s)]);
121
+ } else if (on.has(s)) low.set(n, Math.min(low.get(n), index.get(s)));
122
+ } else {
123
+ work.pop();
124
+ if (work.length) {
125
+ const p = work[work.length - 1][0];
126
+ low.set(p, Math.min(low.get(p), low.get(n)));
127
+ }
128
+ if (low.get(n) === index.get(n)) {
129
+ const comp = [];
130
+ let x;
131
+ do {
132
+ x = stack.pop();
133
+ on.delete(x);
134
+ comp.push(x);
135
+ } while (x !== n);
136
+ out.push(comp.reverse());
137
+ }
138
+ }
139
+ }
140
+ }
141
+ return out;
142
+ }
143
+
144
+ /** natural loops, one per header (all its latches), innermost first; for a function, loops know its values */
145
+ export function loops(view) {
146
+ const isFn = !!(view && view.blocks);
147
+ const g = asGraph(view);
148
+ const { dominates } = dominators(g);
149
+ const preds = predecessors(g);
150
+ const latches = new Map();
151
+ for (const b of g.nodes)
152
+ for (const s of g.succ(b))
153
+ if (dominates(s, b)) {
154
+ const l = latches.get(s) ?? [];
155
+ if (!l.includes(b)) l.push(b);
156
+ latches.set(s, l);
157
+ }
158
+ const all = [];
159
+ for (const [header, group] of latches) {
160
+ const body = new Set([header]);
161
+ const work = [...group];
162
+ while (work.length) {
163
+ const x = work.pop();
164
+ if (body.has(x)) continue;
165
+ body.add(x);
166
+ work.push(...preds.get(x));
167
+ }
168
+ const outside = preds.get(header).filter(q => !body.has(q));
169
+ const preheader = outside.length === 1 && g.succ(outside[0]).length === 1 ? outside[0] : null;
170
+ const exits = new Set();
171
+ for (const x of body) for (const y of g.succ(x)) if (!body.has(y)) exits.add(y);
172
+ all.push({
173
+ header,
174
+ latches: group,
175
+ body: [...body],
176
+ exits: [...exits],
177
+ preheader,
178
+ /** a block of the loop, or a value defined in one */
179
+ contains: x => body.has(x && typeof x === 'object' && 'kind' in x ? x.block : x),
180
+ values: () => {
181
+ if (!isFn) throw new TkError('loop.values() needs the loops of a function, not of a view');
182
+ return [...body].flatMap(b => b.values());
183
+ },
184
+ });
185
+ }
186
+ all.sort((a, b) => a.body.length - b.body.length);
187
+ for (const l of all)
188
+ l.depth =
189
+ all.filter(o => o.body.length > l.body.length && l.body.every(b => o.body.includes(b))).length + 1;
190
+ return {
191
+ all,
192
+ innermostFirst: () => [...all],
193
+ of: block => all.find(l => l.body.includes(block)) ?? null,
194
+ depthOf: block => all.filter(l => l.body.includes(block)).length,
195
+ };
196
+ }
197
+ loops.on = 'cfg';
@@ -0,0 +1,23 @@
1
+ // std/lattice.js — lattices to spread into a dataflow problem.
2
+
3
+ export const sets = {
4
+ bottom: () => new Set(),
5
+ join: (a, b) => {
6
+ const u = new Set(a);
7
+ for (const x of b) u.add(x);
8
+ return u;
9
+ },
10
+ equal: (a, b) => a.size === b.size && [...a].every(x => b.has(x)),
11
+ };
12
+
13
+ /** a flat lattice of constants: undefined (nothing yet) < a value < TOP (not a constant) */
14
+ export const TOP = Symbol('top');
15
+ export const constants = {
16
+ bottom: () => new Map(),
17
+ join: (a, b) => {
18
+ const m = new Map(a);
19
+ for (const [k, v] of b) m.set(k, !m.has(k) || m.get(k) === v ? v : TOP);
20
+ return m;
21
+ },
22
+ equal: (a, b) => a.size === b.size && [...a].every(([k, v]) => b.get(k) === v),
23
+ };
@@ -0,0 +1,76 @@
1
+ // std/passes.js — passes every IR gets for free from its ops' declarations: fold uses the eval lambdas, dce the
2
+ // effect flags, verifySSA the block structure. Each is an ordinary tk.pass.
3
+
4
+ import { TkError } from '../diag.js';
5
+ import { ATTR_TYPES } from '../ir.js';
6
+ import { Pass } from '../pass.js';
7
+ import { dominators } from './graph.js';
8
+
9
+ /** evaluate pure ops whose arguments are all constants, with the ops' own eval lambdas */
10
+ export const fold = new Pass('fold')
11
+ .about("evaluate pure ops whose arguments are constants (the IR's const op), with their eval lambdas")
12
+ .each(v => {
13
+ const c = v.ir.constOp;
14
+ if (!c || v.op === c || !v.pure || !v.spec.eval || !v.args.length || !v.args.every(a => a.op === c))
15
+ return;
16
+ const k = c.attrNames[0];
17
+ const r = v.spec.eval(
18
+ v.args.map(a => a.attrs[k]),
19
+ v.attrs,
20
+ {},
21
+ );
22
+ if (!ATTR_TYPES[c.attrs[k]](r)) return;
23
+ v.replaceWith(b => b[c.name](r));
24
+ });
25
+
26
+ /** erase pure values and phis that nothing uses, until none is left; an expression graph's root is live */
27
+ export const dce = new Pass('dce').about('erase pure values and phis that nothing uses').run(fn => {
28
+ for (let changed = true; changed; ) {
29
+ changed = false;
30
+ for (const v of fn.values().reverse())
31
+ if (!v.erased && v !== fn.root && (v.pure || v.kind === 'phi') && !v.uses.length) {
32
+ v.erase();
33
+ changed = true;
34
+ }
35
+ }
36
+ });
37
+
38
+ /** throw if the function is not well formed SSA: terminators last, phis first and per predecessor, defs dominate uses */
39
+ export const verifySSA = new Pass('verify-ssa')
40
+ .about('check the block structure and that every definition dominates its uses')
41
+ .run(fn => {
42
+ if (fn.expr) return;
43
+ const bad = [];
44
+ const { dominates } = dominators(fn);
45
+ for (const b of fn.blocks) {
46
+ const vs = b.values();
47
+ if (!b.terminator) bad.push(`${b.name} has no terminator`);
48
+ vs.forEach((v, i) => {
49
+ if (v.op.terminator && i !== vs.length - 1) bad.push(`${b.name}: ${v.kind} is not the last value`);
50
+ if (v.kind === 'phi' && vs.slice(0, i).some(x => x.kind !== 'phi'))
51
+ bad.push(`${b.name}: phi ${v.ref} after a non-phi`);
52
+ for (const a of v.args)
53
+ if (!a.uses.includes(v)) bad.push(`${v.ref} uses ${a.ref}, whose use list does not know it`);
54
+ if (v.kind === 'phi') {
55
+ const preds = b.preds;
56
+ if (v.incomingBlocks.length !== preds.length || !preds.every(p => v.incomingBlocks.includes(p)))
57
+ bad.push(
58
+ `phi ${v.ref} in ${b.name} has inputs from [${v.incomingBlocks.map(x => x.name)}], the block's predecessors are [${preds.map(x => x.name)}]`,
59
+ );
60
+ v.args.forEach((a, k) => {
61
+ if (a.kind !== 'param' && !dominates(a.block, v.incomingBlocks[k]))
62
+ bad.push(`phi ${v.ref}: ${a.ref} does not dominate the end of ${v.incomingBlocks[k].name}`);
63
+ });
64
+ } else
65
+ for (const a of v.args) {
66
+ if (a.erased) bad.push(`${v.ref} uses the erased ${a.ref}`);
67
+ else if (a.kind !== 'param' && (a.block === b ? vs.indexOf(a) > i : !dominates(a.block, b)))
68
+ bad.push(`${v.ref} (${v.kind}) in ${b.name} uses ${a.ref}, which does not dominate it`);
69
+ }
70
+ });
71
+ }
72
+ if (bad.length)
73
+ throw new TkError(
74
+ `verify-ssa: ${fn.name}: ${bad.length} problem${bad.length > 1 ? 's' : ''}\n ${bad.join('\n ')}`,
75
+ );
76
+ });