From 86b0af8194b7233a888aa80baf0eb5607c940a32 Mon Sep 17 00:00:00 2001 From: Joe Savona Date: Fri, 7 Jun 2024 10:28:38 -0700 Subject: [PATCH] compiler: Scope-based reordering Extends instruction reordering further to allow reordering of instructions in different scopes. The basic idea is that each instructions within a scope maintain their original order with respect to each other, but instructions for different scopes can be reordered relative to other scopes. This allows interleaved or nested scopes to be reordered to avoid the interleaving/nesting. There are lot of things still very broken about this, but the one new fixture shows an example of this working. Note that this approach works very well for interleaving. We'll probably need to add a bit more to handle nesting - in general it's better to move nested scopes first before their parent scope, but the current algorithm for reordering doesn't take this into account yet. [ghstack-poisoned] --- .../src/Entrypoint/Pipeline.ts | 8 +- .../src/Optimization/InstructionReordering.ts | 153 ++++++++++++++++-- .../compiler/reorder-interleaved.expect.md | 58 +++++++ .../fixtures/compiler/reorder-interleaved.js | 7 + 4 files changed, 207 insertions(+), 19 deletions(-) create mode 100644 compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reorder-interleaved.expect.md create mode 100644 compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reorder-interleaved.js diff --git a/compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Pipeline.ts b/compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Pipeline.ts index bd679701bf..982d094137 100644 --- a/compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Pipeline.ts +++ b/compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Pipeline.ts @@ -72,6 +72,7 @@ import { import { alignMethodCallScopes } from "../ReactiveScopes/AlignMethodCallScopes"; import { alignReactiveScopesToBlockScopesHIR } from "../ReactiveScopes/AlignReactiveScopesToBlockScopesHIR"; import { pruneAlwaysInvalidatingScopes } from "../ReactiveScopes/PruneAlwaysInvalidatingScopes"; +import pruneInitializationDependencies from "../ReactiveScopes/PruneInitializationDependencies"; import { stabilizeBlockIds } from "../ReactiveScopes/StabilizeBlockIds"; import { eliminateRedundantPhi, enterSSA, leaveSSA } from "../SSA"; import { inferTypes } from "../TypeInference"; @@ -92,7 +93,6 @@ import { validatePreservedManualMemoization, validateUseMemo, } from "../Validation"; -import pruneInitializationDependencies from "../ReactiveScopes/PruneInitializationDependencies"; export type CompilerPipelineValue = | { kind: "ast"; name: string; value: CodegenFunction } @@ -203,9 +203,6 @@ function* runWithEnvironment( deadCodeElimination(hir); yield log({ kind: "hir", name: "DeadCodeElimination", value: hir }); - instructionReordering(hir); - yield log({ kind: "hir", name: "InstructionReordering", value: hir }); - pruneMaybeThrows(hir); yield log({ kind: "hir", name: "PruneMaybeThrows", value: hir }); @@ -233,6 +230,9 @@ function* runWithEnvironment( inferReactiveScopeVariables(hir); yield log({ kind: "hir", name: "InferReactiveScopeVariables", value: hir }); + instructionReordering(hir); + yield log({ kind: "hir", name: "InstructionReordering", value: hir }); + alignMethodCallScopes(hir); yield log({ kind: "hir", diff --git a/compiler/packages/babel-plugin-react-compiler/src/Optimization/InstructionReordering.ts b/compiler/packages/babel-plugin-react-compiler/src/Optimization/InstructionReordering.ts index 825c7aed0d..1d31b1be55 100644 --- a/compiler/packages/babel-plugin-react-compiler/src/Optimization/InstructionReordering.ts +++ b/compiler/packages/babel-plugin-react-compiler/src/Optimization/InstructionReordering.ts @@ -5,10 +5,15 @@ import { IdentifierId, Instruction, InstructionId, + MutableRange, + ReactiveScope, + isMutableEffect, makeInstructionId, markInstructionIds, } from "../HIR"; +import { printIdentifier } from "../HIR/PrintHIR"; import { + eachInstructionLValue, eachInstructionValueLValue, eachInstructionValueOperand, eachTerminalOperand, @@ -16,6 +21,8 @@ import { import { mayAllocate } from "../ReactiveScopes/InferReactiveScopeVariables"; import { getOrInsertDefault } from "../Utils/utils"; +const DEBUG = false; + /** * WIP early exploration of instruction reordering. This is a fairly aggressive form and has * some issues. The idea of what's implemented: @@ -82,6 +89,39 @@ export function instructionReordering(fn: HIRFunction): void { ); } markInstructionIds(fn.body); + + /** + * Instructions have been reordered and renumbered, so all the reactive scope ranges are now + * incorrect. Walk the HIR again to recalculate the ranges of each scope based on where it + * is mutated. + */ + const scopes = new Map(); + for (const [, block] of fn.body.blocks) { + for (const instr of block.instructions) { + for (const operand of [ + ...eachInstructionValueOperand(instr.value), + ...eachInstructionLValue(instr), + ]) { + if ( + isMutableEffect(operand.effect, operand.loc) && + operand.identifier.scope !== null + ) { + const scope = operand.identifier.scope; + let range = scopes.get(scope); + if (range === undefined) { + range = { start: instr.id, end: makeInstructionId(instr.id + 1) }; + scopes.set(scope, range); + } else { + range.start = makeInstructionId(Math.min(range.start, instr.id)); + range.end = makeInstructionId(Math.max(range.end, instr.id + 1)); + } + } + } + } + } + for (const [scope, range] of scopes) { + scope.range = range; + } } function findSingleUseLoadLocals(fn: HIRFunction): Set { @@ -120,6 +160,15 @@ function findSingleUseLoadLocals(fn: HIRFunction): Set { function getLastAssignments(fn: HIRFunction): LastAssignments { const lastAssignments: LastAssignments = new Map(); + for (const param of fn.params) { + const place = param.kind === "Identifier" ? param : param.place; + if ( + place.identifier.name !== null && + place.identifier.name.kind === "named" + ) { + lastAssignments.set(place.identifier.name.value, makeInstructionId(0)); + } + } for (const [, block] of fn.body.blocks) { for (const instr of block.instructions) { for (const lvalue of eachInstructionValueLValue(instr.value)) { @@ -148,7 +197,7 @@ type LastAssignments = Map; type Dependencies = Map; type Node = { instruction: Instruction | null; - dependencies: Array; + dependencies: Set; depth: number | null; }; @@ -167,14 +216,14 @@ function reorderBlock( ): void { const dependencies: Dependencies = new Map(); const locals = new Map(); - let previousIdentifier: IdentifierId | null = null; + const previousByScope = new Map(); for (const instr of block.instructions) { const node: Node = getOrInsertDefault( dependencies, instr.lvalue.identifier.id, { instruction: instr, - dependencies: [], + dependencies: new Set(), depth: null, } ); @@ -182,19 +231,27 @@ function reorderBlock( getReorderingLevel(instr, lastAssignments, singleUseLoadLocals) === ReorderingLevel.None ) { - if (previousIdentifier !== null) { - node.dependencies.push(previousIdentifier); + const scopes = getAllScopes(instr); + if (scopes.size === 0) { + const previouIdentifier = previousByScope.get(null); + if (previouIdentifier != null) { + node.dependencies.add(previouIdentifier); + } + previousByScope.set(null, instr.lvalue.identifier.id); } - previousIdentifier = instr.lvalue.identifier.id; } for (const operand of eachInstructionValueOperand(instr.value)) { - if ( + const scope = operand.identifier.scope; + if (scope !== null && previousByScope.has(scope)) { + const previous = previousByScope.get(scope)!; + node.dependencies.add(previous); + } else if ( operand.identifier.name !== null && operand.identifier.name.kind === "named" ) { const previous = locals.get(operand.identifier.name.value); if (previous !== undefined) { - node.dependencies.push(previous); + node.dependencies.add(previous); } locals.set(operand.identifier.name.value, instr.lvalue.identifier.id); } else { @@ -202,9 +259,10 @@ function reorderBlock( dependencies.has(operand.identifier.id) || globalDependencies.has(operand.identifier.id) ) { - node.dependencies.push(operand.identifier.id); + node.dependencies.add(operand.identifier.id); } } + previousByScope.set(scope, instr.lvalue.identifier.id); } dependencies.set(instr.lvalue.identifier.id, node); @@ -214,18 +272,18 @@ function reorderBlock( lvalue.identifier.id, { instruction: null, - dependencies: [], + dependencies: new Set(), depth: null, - } + } as Node ); - lvalueNode.dependencies.push(instr.lvalue.identifier.id); + lvalueNode.dependencies.add(instr.lvalue.identifier.id); if ( lvalue.identifier.name !== null && lvalue.identifier.name.kind === "named" ) { const previous = locals.get(lvalue.identifier.name.value); if (previous !== undefined) { - node.dependencies.push(previous); + node.dependencies.add(previous); } locals.set(lvalue.identifier.name.value, instr.lvalue.identifier.id); } @@ -259,12 +317,13 @@ function reorderBlock( } dependencies.delete(id); globalDependencies.delete(id); - node.dependencies.sort((a, b) => { + const deps = [...node.dependencies]; + deps.sort((a, b) => { const aDepth = getDepth(env, a); const bDepth = getDepth(env, b); return bDepth - aDepth; }); - for (const dep of node.dependencies) { + for (const dep of deps) { emit(dep); } if (node.instruction !== null) { @@ -272,7 +331,32 @@ function reorderBlock( } } + const printEmitted = new Set(); + function print(id: IdentifierId, depth: number = 0): void { + if (printEmitted.has(id)) { + console.log(` ${"| ".repeat(depth)}$${id} (emitted)`); + return; + } + printEmitted.add(id); + const node = dependencies.get(id) ?? globalDependencies.get(id); + if (node == null) { + return; + } + const deps = [...node.dependencies]; + deps.sort((a, b) => { + const aDepth = getDepth(env, a); + const bDepth = getDepth(env, b); + return bDepth - aDepth; + }); + for (const dep of deps) { + print(dep, depth + 1); + } + console.log(` ${"| ".repeat(depth)}${printNode(id, node, deps)}`); + } + + DEBUG && console.log(`\nbb${block.id}:`); for (const operand of eachTerminalOperand(block.terminal)) { + DEBUG && print(operand.identifier.id); emit(operand.identifier.id); } /** @@ -295,8 +379,10 @@ function reorderBlock( ) === ReorderingLevel.Global && (block.kind === "block" || block.kind === "catch") ) { + DEBUG && console.log(`global $${id}`); globalDependencies.set(id, node); } else { + DEBUG && print(id); emit(id); } } @@ -343,3 +429,40 @@ function getReorderingLevel( } } } + +function printNode( + id: IdentifierId, + node: Node, + deps: Array +): string { + let printed: string = ""; + const { instruction } = node; + if (instruction !== null) { + switch (instruction.value.kind) { + case "FunctionExpression": + case "ObjectMethod": { + printed = `[${instruction.id}] ${instruction.value.kind}`; + break; + } + default: { + printed = `[${instruction.id}] ${printIdentifier(instruction.lvalue.identifier)} = ${instruction.value.kind} ${[...eachInstructionValueOperand(instruction.value)].map((operand) => printIdentifier(operand.identifier)).join(", ")}`; + } + } + } + return `$${id} ${printed} deps=[${deps.map((x) => `$${x}`)}]`; +} + +function getAllScopes(instr: Instruction): Set { + const scopes = new Set(); + for (const operand of eachInstructionLValue(instr)) { + if (operand.identifier.scope !== null) { + scopes.add(operand.identifier.scope); + } + } + for (const operand of eachInstructionValueOperand(instr.value)) { + if (operand.identifier.scope !== null) { + scopes.add(operand.identifier.scope); + } + } + return scopes; +} diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reorder-interleaved.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reorder-interleaved.expect.md new file mode 100644 index 0000000000..f85dcba791 --- /dev/null +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reorder-interleaved.expect.md @@ -0,0 +1,58 @@ + +## Input + +```javascript +function Component(props) { + const a = []; + const b = []; + a.push(props.a); + b.push(props.b); + return [a, b]; +} + +``` + +## Code + +```javascript +import { c as _c } from "react/compiler-runtime"; +function Component(props) { + const $ = _c(7); + let t0; + if ($[0] !== props.a) { + const a = []; + + a.push(props.a); + + t0 = a; + $[0] = props.a; + $[1] = t0; + } else { + t0 = $[1]; + } + let t1; + if ($[2] !== props.b) { + const b = []; + b.push(props.b); + t1 = b; + $[2] = props.b; + $[3] = t1; + } else { + t1 = $[3]; + } + let t2; + if ($[4] !== t0 || $[5] !== t1) { + t2 = [t0, t1]; + $[4] = t0; + $[5] = t1; + $[6] = t2; + } else { + t2 = $[6]; + } + return t2; +} + +``` + +### Eval output +(kind: exception) Fixture not implemented \ No newline at end of file diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reorder-interleaved.js b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reorder-interleaved.js new file mode 100644 index 0000000000..ffccf089bf --- /dev/null +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reorder-interleaved.js @@ -0,0 +1,7 @@ +function Component(props) { + const a = []; + const b = []; + a.push(props.a); + b.push(props.b); + return [a, b]; +}