# il2cpp-post-export-optimizer **Repository Path**: xuewuli/il2cpp-post-export-optimizer ## Basic Information - **Project Name**: il2cpp-post-export-optimizer - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: codex/evidence-retention - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-09-23 - **Last Updated**: 2026-11-24 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # il2cpp-post-export-optimizer An independent, out-of-tree optimizer for exported IL2CPP C++ trees. The current `il2cpp` checkout is never a build dependency. It may be supplied as an explicit read-only reference source when an implementation detail needs to be compared. The current editor target is Tuanjie `2022.3.62t15`. Extract the original IL2CPP payload and Android SDK/NDK from that installation, and bind them to a matching export, compilation database, and cache. Changing editors requires a new input identity. The reference checkout supplies no authoritative generator, generated C++, or managed inputs. For an existing Windows t15 Android ARM64 development Player with the supported direct Bee compile recipe, the opt-in fresh-array rule can use the original Player DAG and stripped DLL. Build the CLI in Release, then run: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --bee-dag "$project/Library/Bee/Playerf2304b6a.dag.json" --bee-assembly mscorlib.dll ` --editor-root "$t15/Editor" --clang .artifacts/toolchain/llvm-18.1.8/bin/clang.exe ` --selected-tu mscorlib__3.cpp --output "$newOutput" --enable-experimental-fresh-array ``` Use your actual Player DAG filename and generated TU; `$newOutput` must be a new directory outside the project and toolchains. The optimizer replays the original converter into temporary storage, compares the entire C++ and data trees, then proves accesses in the selected TU. It publishes a generated source tree and a report with native compile arguments. Omitting the enable flag publishes unchanged source. Unsupported recipes or stale inputs fail closed. This route neither builds an APK nor enables the rule by default. For a **two-assembly t15 export** produced with the supported Release converter recipe (one input DLL plus the pinned stripped mscorlib), try delayed aggregate initialization on one generated C++ file: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --aggregate-assembly "$capture/ShipInit.dll" --corelib "$stripped/mscorlib.dll" ` --editor-root "$t15/Editor" --bundle "$r2/artifact-bundle" ` --generated-root "$capture/generated-cpp" --selected-tu ShipInit.cpp ` --output "$newOutput" --enable-experimental-aggregate-init ``` The optimizer replays the stock converter and compares the entire generated tree before applying the rule. It binds a managed method through its registration table, verifies IL and C++ field stores, and checks the layout with the t15 NDK compiler. The result is **only the selected TU**, under `$newOutput/generated-cpp/`, plus `optimization-report.json`; use it in place of the same TU in the matching export. Omitting the enable flag gives a byte-identical TU without replay or analysis. The rule currently accepts a narrow form of static methods and structs made of nested Int64 fields with no padding or references. Full Player exports with additional assemblies are not supported by this route. See the [C# example](examples/aggregate-init/ShipInit.cs) and [measured scope](docs/array-loop-range-report.md#p3-large-initializer-stock-t15-c-witness-2026-11-18). To **locate** a conditional initializer of an externally defined value in a three-assembly export, pass the second user DLL explicitly. For example, use the output of the [mixed fixture reproduction command](docs/array-loop-range-report.md#p3-mixed-initializer-stock-cross-assembly-fixture-2026-11-19): ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --aggregate-assembly "$capture/MixedRunner.dll" --aggregate-dependency "$capture/MixedTypes.dll" ` --corelib "$stripped/mscorlib.dll" --editor-root "$t15/Editor" --bundle "$r2/artifact-bundle" ` --generated-root "$capture/generated-cpp" --selected-tu MixedRunner.cpp ` --output "$newOutput" --enable-experimental-aggregate-init ``` This mode replays the stock converter with the dependency, target and core DLLs. Inspect `Methods` in the report: `MethodBodyBound` identifies the registered native function only. `OperationsBound` also maps the IL reads, stores and calls to byte ranges in the original TU and checks the surrounding guard and finally paths. An optional `CandidateSourceSha256` identifies the proposed TU so it can be compared with a measured one. The output TU remains unchanged: a matching byte image at the consumer in one ARM64 build does not establish what a subsequent build will do with padding or who else can observe an externally supplied destination during publication. For a **private local** initialized from a previous value, add `--apply-private-local-aggregate` to that command to allow a rewrite. The local must remain private while the new value is constructed. The compiler must confirm that fixed-width integer fields cover every byte, including all nested records. The output retains the layout assertions. External `ref` destinations and padded locals still produce the original TU. To reproduce both layouts from C# with the stock editor: ```powershell python examples/aggregate-init/local/reproduce.py "$t15/Editor" "$stripped/mscorlib.dll" "$denseCapture" dense python examples/aggregate-init/local/reproduce.py "$t15/Editor" "$stripped/mscorlib.dll" "$paddedCapture" padded ``` Use either new capture directory as `$capture` above; see the [object and semantics results](docs/array-loop-range-report.md#private-local-aggregate-publication). For a three-assembly t15 export generated with `--generics-option=EnableFullSharing`, the **argument materialization** rule looks for a large value loaded from a byref only to initialize a wrapper's by-value parameter. For the supported static receiver call it removes the intermediate local and keeps the private parameter copy. Pass the caller DLL, the DLL defining the value and generic callee, and the original generated TU: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --aggregate-assembly "$capture/Receiver.dll" --aggregate-dependency "$capture/Types.dll" ` --corelib "$stripped/mscorlib.dll" --editor-root "$t15/Editor" ` --generated-root "$capture/generated-cpp" --selected-tu Receiver.cpp ` --output "$newOutput" --enable-experimental-aggregate-argument ``` This route uses the ARM64 Android-22 Release headers and compiler from the same editor installation; no benchmark bundle or example sources are required. The filenames above come from the [reproducible example](examples/aggregate-argument/reproduce.py). The rule discovers method tokens and source locations from the supplied inputs. It replays the stock converter, verifies the typed call and layout, and syntax-checks the delivered replacement with the target NDK Clang. The report maps the IL load and call to original TU byte ranges. Unsupported sites leave the TU unchanged. Use the argument switch on its own; the initializer rule uses a different conversion recipe. Before exporting a Player, inspect a stripped caller DLL together with the DLL defining its generic callee: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --inspect-aggregate-argument --aggregate-assembly "$stripped/SeaWarRes.dll" ` --aggregate-dependency "$stripped/Unity.Collections.dll" ``` The JSON on stdout identifies each supported direct by-value operand by caller, IL offsets and metadata tokens. The value type may be defined in either input. `ValueCallEdges` counts as managed evidence only; `RewriteShapeCandidates` counts the narrower existing managed rewrite shape. Neither means a native edit was made. Inspection accepts no output directory. If you have a complete directory of stripped DLLs and the corresponding generated tree, add `--aggregate-assembly-dir "$stripped"` to the enabled argument command above (no bundle). The caller, dependency and corelib must all be direct entries of that directory. This profile stages the top-level DLLs in ordinal filename order, replays the pinned original t15 full-sharing converter and requires the whole supplied C++ tree to match. It is a direct converter input profile; it does not import arbitrary Player/Bee flags. By default broader inventories are observation-only. For a uniquely matched operand, `Methods[].Status = NativeOperandObserved` reports the registered symbol, original load/call byte ranges, wrapper, metadata slot and shared target. Check `Edits` and `ArgumentEditProfile` separately. For the bounded **ordered byte snapshot** rule, explicitly add `--apply-ordered-snapshot` to the directory-input command. For example: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --aggregate-assembly-dir "$stripped" --aggregate-assembly "$stripped/SeaWarRes.dll" ` --aggregate-dependency "$stripped/Unity.Collections.dll" --corelib "$stripped/mscorlib.dll" ` --editor-root "$t15/Editor" --generated-root "$originalCpp" --selected-tu SeaWarRes__4.cpp ` --output "$newOutput" --enable-experimental-aggregate-argument --apply-ordered-snapshot ``` This mode accepts one managed operand edge in the caller/dependency scan. It snapshots a trivial struct with scalar fields at its original load, including padding. The shared callee gets the private snapshot's address. The pinned target compiler must show the original two whole-object copies and the proposed single copy at the same capture point, with the rest of the caller passing the IR checks. Edit eligibility is specific to the original t15 Android ARM64 API 22 `-Os` recipe; other Player build settings need their own proof. The existing three-DLL rule and plain inspection do not enable this mode. See the [measured game caller](docs/aggregate-argument-copy-scout.md#optimizer-produced-ordered-snapshot). To import one cross-TU reference-field getter in this stock t15 full-sharing profile, select the enclosing caller by TU and managed MethodDef token (eight hexadecimal digits, including `06`). For the game capture: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --aggregate-assembly-dir "$stripped" --aggregate-assembly "$stripped/ITClient.dll" ` --corelib "$stripped/mscorlib.dll" --editor-root "$t15/Editor" --generated-root "$originalCpp" ` --selected-tu ITClient__104.cpp --caller-token 0600a69f ` --enable-experimental-reference-getter --output "$newOutput" ``` The optimizer inspects that caller's IL calls. It requires exactly one candidate to pass the existing same-module managed proof before looking up its registered native symbol in the assembly's original t15 C++ shards. The file lookup only nominates a TU; the typed definition, call and layout must still pass the native checks. If none or multiple qualify in IL, it leaves the caller unchanged. To select a particular target explicitly, add `--getter-tu ITClient__105.cpp --getter-token 0600a5a4` (both together). The output is the selected caller TU plus a report. Omit the enable switch with the same selectors for a byte-identical caller. This narrow rule works on a direct, registered AOT call to an ordinary getter on a sealed class; it retains the receiver's existing null check and the original getter definition. It assumes the pinned non-interposed Release profile without live rebinding, instrumentation or a requirement to observe the getter as a separate native frame. Use it independently of the aggregate write flags. See the [game caller evidence](docs/ship-static-optimization-candidates.md). To try the caller-only iterator rule on the same original t15 Android ARM64 capture, select the two NormalShip callers in one TU: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --aggregate-assembly-dir "$stripped" --aggregate-assembly "$stripped/ITClient.dll" ` --aggregate-dependency "$stripped/PaiPai.UnityExt.dll" --corelib "$stripped/mscorlib.dll" ` --editor-root "$t15/Editor" --generated-root "$originalCpp" --selected-tu ITClient__104.cpp ` --caller-tokens '0600a6a1,0600a6a3' --enable-experimental-iterator-guard --output "$newOutput" ``` For NormalShip Text and Effect on this same export, change the token list to `'0600a6a2,0600a6a4'` and use a new output directory. The two [measured selections](docs/ship-static-optimization-candidates.md#caller-only-iterator-end-flag) each start from the original TU; their output files are separate alternatives. On a proven direct call, a non-null element address allows the caller to skip reading the private end flag. A null address still reads the flag, including when the flag is false. The shared implementation, its stores and its managed exception path stay in place. Output is one caller TU in `generated-cpp/` and an `optimization-report.json` with one row per requested method. If a method fails eligibility, no sibling is rewritten. To produce the disabled control, replace the enable switch with `--iterator-guard` and use a fresh output directory. The guard remains experimental: skipping a load on one path adds a branch on the other. To apply the iterator guard **and** shared-generic Count to the same selected methods, use the same original inputs with the explicit composition mode. For NormalShip Model and Sprite: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --aggregate-assembly-dir "$stripped" --aggregate-assembly "$stripped/ITClient.dll" ` --aggregate-dependency "$stripped/PaiPai.UnityExt.dll" --corelib "$stripped/mscorlib.dll" ` --editor-root "$t15/Editor" --generated-root "$originalCpp" --selected-tu ITClient__104.cpp ` --caller-tokens '0600a6a1,0600a6a3' --compose-count-iterator ` --enable-experimental-shared-count --enable-experimental-iterator-guard --output "$newOutput" ``` Install the one file under `generated-cpp/` as the replacement for the original caller TU. Both proofs must pass for every requested caller; an ineligible caller withholds the whole selection. The final TU must also pass preprocessing, layout and typed AST checks before the overlay is published. To get the disabled control, omit both enable switches and choose a new output directory. Supplying just one enable switch is invalid. This mode takes explicit tokens in one TU; it does not run discovery or compose a third rule. For the separate experimental shared-generic `Count` rule, select the caller and supply the stripped assembly defining the getter. Example for the same stock t15 Android ARM64 API 22 `-Os` full-sharing capture: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --aggregate-assembly-dir "$stripped" --aggregate-assembly "$stripped/ITClient.dll" ` --aggregate-dependency "$stripped/PaiPai.UnityExt.dll" --corelib "$stripped/mscorlib.dll" ` --editor-root "$t15/Editor" --generated-root "$originalCpp" --selected-tu ITClient__104.cpp ` --caller-token 0600a6a3 --shared-count --enable-experimental-shared-count --output "$newOutput" ``` The rule imports a closed generic getter whose complete body subtracts two Int32 fields. It supports two caller shapes: - A caller without exception regions reads the dictionary twice from the same argument field. Both sites and their null checks must pass together; neither read is moved across the intervening code. - An instance caller reads its dictionary field and calls the getter once at method entry, before its later, separate `try/finally` regions. The void caller may take one enum argument defined in the caller's module with `System.UInt64` storage, in addition to the original parameterless form. The optimizer checks the managed enum definition and the ordered native parameters: receiver, `uint64_t` argument and runtime-method pointer. The Count still reads from the receiver. The managed and native proofs must both place that call before the protected code. A plain local pointer initialized by a built-in conversion from a null literal is allowed before the call; the pointer declaration and initialization are left intact. An expression that calls a function or converts a class object to a pointer is not admitted by this check. The dictionary null check, metadata setup and cleanup code stay in place. The shared entry is retained. Omit the enable switch to produce a byte-identical overlay; an unsupported caller yields `NoEdits` and a reason. It has the same Release frame and runtime-interposition assumptions as the reference getter above. To optimize Model and Sprite **in the same output file**, use the command above with `--caller-tokens '0600a6a1,0600a6a3'` in place of `--caller-token 0600a6a3`. All tokens are MethodDefs in the selected assembly; their generated callers must be in the selected TU. Supply one selector and list each token once. The report identifies each caller that was applied or refused. An ineligible caller does not discard eligible ones. The command validates all accepted changes together before publishing; conflicting edits or a failed combined verification produce no overlay. If you know the managed MethodDefs but not their generated C++ files, omit `--selected-tu` and pass the tokens as a list. For example: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --aggregate-assembly-dir "$stripped" --aggregate-assembly "$stripped/ITClient.dll" ` --aggregate-dependency "$stripped/PaiPai.UnityExt.dll" --corelib "$stripped/mscorlib.dll" ` --editor-root "$t15/Editor" --generated-root "$originalCpp" ` --shared-count --caller-tokens '0600a374,0600a3e4,0600a7c4' ` --enable-experimental-shared-count --output "$newOutput" ``` Tokens belong to the exact stripped assembly supplied in this command. One stock replay supplies its registration table and generated assembly shards. `Locations` reports the decision for each requested token; `TranslationUnits` reports what was actually applied. Only a registered definition confirmed in the candidate file can be considered for an edit. The file scan recognizes the stock t15 assembly shard names and signature layout. A null registration slot, missing definition or ambiguous match gets a refusal reason; it cannot authorize a rewrite. Omitting the enable switch skips lookup and leaves `generated-cpp/` empty because no TU was selected. To inspect all callers in a **known** TU instead, use discovery below. To find callers without knowing any MethodDef tokens, replace the token selector with `--discover-callers` and keep `--selected-tu`, `--shared-count` and the experimental enable switch. The optimizer intersects the selected assembly's stock method-pointer registration with function definitions in that TU. Each candidate then goes through the same IL, registration and native checks as an explicitly selected caller. The report counts callers considered, admitted and refused; one admitted caller can contribute more than one edit. Omitting the enable switch skips discovery and returns the original TU bytes; zero considered in this case means the scan did not run. To discover callers in more than one TU of the same assembly, replace `--selected-tu ITClient__104.cpp` with `--selected-tus 'ITClient__103.cpp,ITClient__104.cpp'`. Keep `--shared-count --discover-callers` and use a new output directory. Supply distinct, exact generated filenames, with no spaces around the commas. One invocation replays the stock converter once and shares registration data across the selected files. `generated-cpp/` contains every selected TU, including byte-identical copies for those with no candidates. Under `TranslationUnits` the report lists each TU's source and output hashes, counts, and per-method decisions; `Work` records actual replay and AST counts. Validation fails the whole batch if independently verified edits would change another selected TU's proof inputs. The single-TU form and its report remain available for focused runs. To apply **both the reference getter and shared `Count` to the same TU**, use one output directory and request composition explicitly: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --aggregate-assembly-dir "$stripped" --aggregate-assembly "$stripped/ITClient.dll" ` --aggregate-dependency "$stripped/PaiPai.UnityExt.dll" --corelib "$stripped/mscorlib.dll" ` --editor-root "$t15/Editor" --generated-root "$originalCpp" --selected-tu ITClient__104.cpp ` --compose-count-getter --shared-count --discover-callers --enable-experimental-shared-count ` --caller-token 0600a69f --enable-experimental-reference-getter --output "$newOutput" ``` Here `--caller-token` selects the enclosing method for the **reference getter**; `--discover-callers` finds the **Count** callers throughout the selected TU. Both rules propose edits to the same original bytes. The optimizer checks their combined output before publishing one caller TU. Use the per-rule decisions in `optimization-report.json` to see what applied. The separate commands above remain available for a single rule. To reuse an observed class-initialization flag in the Sprite caller, select the assembly that **owns the static field**, `SeaWarRes.dll`: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --class-init-reuse --runtime-profile stock-t15-android-nonreload ` --aggregate-assembly-dir "$stripped" --aggregate-assembly ITClient.dll ` --aggregate-dependency SeaWarRes.dll --corelib mscorlib.dll ` --editor-root "$t15/Editor" --generated-root "$originalCpp" --selected-tu ITClient__104.cpp ` --caller-token 0600a6a3 --enable-experimental-class-init-reuse --output "$newOutput" ``` The supported target for this standalone experiment is an original t15 Android ARM64 non-slim VM without class or metadata replacement. Supplying the profile declares the intended target; the optimizer checks the Editor sources and compiler configuration but cannot identify the VM in a shipped game. A custom, reloading or hot-patched VM is outside this contract. The first guard observes the completion flag **before** any slow call. Only a nonzero observation skips the repeat check; a zero observation keeps the entire stock guard in the loop, even if the first slow call returns normally. No managed reference is cached by the rewrite. Omit `--enable-experimental-class-init-reuse` to copy the TU unchanged with no replay. See `Methods` in `optimization-report.json` for the decision and [the native comparison](docs/ship-static-optimization-candidates.md#observed-class-initialization-in-the-sprite-loop) for the cost of the extra condition. To try the **caller-only Sprite append** on the measured original 77-assembly t15 export: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --sprite-append --runtime-profile stock-t15-android-nonreload ` --aggregate-assembly-dir "$stripped" --aggregate-assembly ITClient.dll ` --aggregate-dependency SeaWarRes.dll --corelib mscorlib.dll ` --editor-root "$t15/Editor" --generated-root "$originalCpp" --discover-callers ` --enable-experimental-sprite-append --output "$newOutput" ``` Discovery finds direct calls to the closed `NativeList.Add` in ITClient. It rejects direct byref arguments at IL, locates the registered definitions of eligible callers in one stock replay, and publishes the verified TU overlays together. A failed native proof for either caller withholds both rewrites. For just NormalShip, replace `--discover-callers` with `--selected-tu ITClient__104.cpp --caller-token 0600a6a3`; for NormalStatic use `--selected-tu ITClient__103.cpp --caller-token 0600a5dd`. Both modes require the IL and C++ proofs to identify the same private Sprite value. With warm metadata and spare capacity it copies the caller's 168-byte value directly to the list slot. Later appends in the same caller invocation reuse the validated closed method and layout; they still read the current list, length, capacity and data pointer. Growth and unproven runtime states use the stock Add. Other instantiations and shared definitions are unchanged. This rule admits one fingerprinted export and a non-lazy, write-barrier-disabled Android ARM64 target; it does not identify or qualify the runtime in a deployed game. Omit the experimental enable to skip replay and rewriting. In single-caller mode the `Managed`, `ClosedBinding` and `Methods` report entries describe the managed site, registration evidence and both edits (one local and one call). `ClosedBinding.Admission = CheckedT15V31SpriteAppend` means the tool followed the selected call's MethodInfo through the v31 tables to the two Add implementations, element type and resize slot. An inconsistent or ambiguous binding yields no edits. The managed inventory, caller lowering and runtime profile still restrict this experiment to the measured export. To remove the two shared dictionary Count calls **and** specialize Sprite append in the same NormalShip caller, run both rules together against stock: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --compose-count-append --shared-count --sprite-append ` --enable-experimental-shared-count --enable-experimental-sprite-append ` --runtime-profile stock-t15-android-nonreload ` --aggregate-assembly-dir "$stripped" --aggregate-assembly ITClient.dll ` --aggregate-dependency SeaWarRes.dll --corelib mscorlib.dll ` --editor-root "$t15/Editor" --generated-root "$originalCpp" ` --selected-tu ITClient__104.cpp --caller-token 0600a6a3 --output "$newOutput" ``` The explicit Sprite command requires both proofs for that caller. To discover **all supported Count and closed list Add sites in one TU**, use the following form instead. It retains callers where only one rule applies: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --compose-count-append --discover-callers --shared-count --list-append ` --enable-experimental-shared-count --enable-experimental-list-append ` --runtime-profile stock-t15-android-nonreload ` --aggregate-assembly-dir "$stripped" --aggregate-assembly ITClient.dll ` --aggregate-dependency SeaWarRes.dll --corelib mscorlib.dll ` --editor-root "$t15/Editor" --generated-root "$originalCpp" ` --selected-tu ITClient__104.cpp --output "$newOutput" ``` Use the stock export as input. Separate runs of the two rules each produce a complete replacement for the TU; they cannot be overlaid on each other. The combined discovery command verifies all admitted edits on the same final C++ before publishing. Omit both enable flags to copy the stock TU without replay; providing just one enable flag is an error. Add `--reuse-completed-append` to a `--list-append` command to reuse a successful first fitting append's metadata checks at the same site within one caller invocation. The option also works with combined Count discovery. Capacity and data are read on each visit. Growth uses the original Add. This experiment requires the same pinned non-reload runtime profile and experimental enable flags. [ARM64 costs and scope](docs/array-loop-range-report.md#reuse-completed-fitting-appends) With `--list-append --discover-callers`, add `--discover-constructed-appends` to include the MaterialTrade, AllianceGold and SystemSupplies loops of `GetChangeSpeedPosList` in the supported t15 `ITClient__104.cpp`. Each appends a locally constructed 16-byte value to the same list field. The optimizer checks each IL call and reports its own C++ replacement range. The combined Count command accepts the same option. With `--reuse-completed-append`, each loop has its own completion flag. Repeated fitting iterations have shorter ARM64 paths on this input. Growth takes more instructions, and the three-loop TU is 452 bytes larger than the one-loop version. [ARM64 measurements and limits](docs/array-loop-range-report.md#constructed-value-appends-in-three-sibling-loops) The same option also selects the repeated `ParsePbPosList` Add in TU 104. It recognizes a private 56-byte local copied before a conditional field update, then acquires the instance list receiver at the original call. The other two Add sites in that method retain stock behavior. With completed append reuse, the measured repeated fitting path drops from 88 to 39 ARM64 instructions. TU executable sections grow by 276 bytes relative to the three-loop version. [Acceptance and growth costs](docs/array-loop-range-report.md#copied-value-append-in-normalship-parsepbposlist) In TU 99 the same option also covers the repeated Add in `EcsRoleManager_Base.ParsePbPosList` and `ParsePbCarPosList`. Both take the address of `this.TempPosList` before constructing the value. The fast path reads the current list header after the position getter returns. An exception from the getter therefore still precedes the append, and growth still uses the stock Add. To run both versions of the route loop alongside the TU 104 rules, pass `--selected-tus 'ITClient__99.cpp,ITClient__104.cpp'` and `--discover-constructed-appends` to the combined command above. Add `--reuse-completed-append` to reproduce the measured repeated paths. [TU 99 coverage and ARM64 costs](docs/array-loop-range-report.md#prepared-instance-appends-in-two-tu-99-route-loops) On the same plural Count/list discovery command, add `--specialize-position-indexer` to discover closed `RepeatedField.get_Item` calls independently of append discovery. Supported callers include the paired route reads in TU 99 and two TU 101 route calculations. In `CalculateCarPositions` the next-position read stays conditional. In `CalculateEndPosition` the rule specializes reads of `i` and `i-1` in the descending loop and leaves the separate index-zero exit on the stock getter. For the static route helpers in TU 10, select `--selected-tus ITClient__10.cpp` on the same command. The rule follows the field path from a local or static method argument to the list and checks the original index argument at each read. The second read reloads the fields and uses the original signed `i+1`. Each replacement stays at its original call site. The same option also handles the paired reads of `i` and `i+1` at the head of supported role-movement loops. It reloads the two fields of `moveInfo.RolePosList.PosLists` at each read and preserves the original getter as the fallback. Use automatic TU selection to discover the registered callers in both `RoleStateHelper` and `EcsRoleProxy`. In those supported callers the optimizer also discovers reads of element zero whose result immediately supplies a `PixelX`, `PixelY` or `PixelZ` getter. The original coordinate getter and its receiver null check stay at the call site. The report lists each proven IL offset under `Managed.CoordinateReads` and the registered native getters under `ClosedBinding.CoordinateGetters`. An in-range index with a non-null backing array copies one Position reference into the original result slot. Other accesses go through the original getter. The per-TU `Rules.PositionIndexer` report lists all matching IL call offsets, the offsets left unchanged, and refusal reasons for unsupported callers. [Descending loop coverage and ARM64 comparison](docs/array-loop-range-report.md#descending-position-reads-in-calculateendposition) [Static route helper coverage and ARM64 comparison](docs/array-loop-range-report.md#field-backed-position-reads-in-static-route-helpers) To process several TUs against one stock replay, replace `--selected-tu ITClient__104.cpp` in the combined discovery command with `--selected-tus 'ITClient__103.cpp,ITClient__104.cpp'`. Supply exact basenames from the generated directory, without duplicates. This mode shares the managed inputs, registration index and generic Count body. Each TU has its own typed verification and per-rule decisions under `TranslationUnits` in the report. The output directory is published as a unit: if the final proofs cannot coexist, no replacement file is published. To have the optimizer **find TUs with supported Position reads**, use `--auto-position-tus` in place of `--selected-tus` on the enabled combined discovery command. For example, on the certified t15 game export: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --compose-count-append --discover-callers --shared-count --list-append ` --enable-experimental-shared-count --enable-experimental-list-append ` --specialize-position-indexer --auto-position-tus ` --reuse-completed-append --discover-constructed-appends ` --runtime-profile stock-t15-android-nonreload ` --aggregate-assembly-dir "$stripped" --aggregate-assembly ITClient.dll ` --aggregate-dependency SeaWarRes.dll --corelib mscorlib.dll ` --editor-root "$t15/Editor" --generated-root "$originalCpp" ` --stock-replay-metadata "$export/data/Metadata/global-metadata.dat" --output "$newOutput" ``` Position proofs determine the TU selection. Shared Count and list Add then discover eligible sites throughout those TUs, including other callers. TUs containing only Count or Add candidates fall outside this selection. The two append modifiers in the example reproduce the measured append edits. The stock metadata option selects certified replay reuse. See `PositionTuSelection` for coverage and per-method decisions, `TranslationUnits` for actual edits, and `Work` for parse counts. For repeat runs on the **certified t15 game export**, add `--stock-replay-metadata "$export/data/Metadata/global-metadata.dat"` to the enabled `--selected-tus` Count and list-append command. Supply the original generated C++ and the metadata from that conversion. The CLI checks the 77 assemblies, generator configuration, editor payload and both output hashes, then analyzes a private copy. A mismatch rejects the run. The report records `CertifiedStockReplay` and `Work.StockReplays = 0`. Omitting the option runs the converter as usual. Both modes verify the inputs again before publishing. [Scope and iteration time](docs/array-loop-range-report.md#reusing-the-stock-conversion-for-the-tu-99104-batch) To find closed list Add calls in one generated TU and apply the supported ones together, use `--list-append --discover-callers`. For example: ```powershell dotnet src/Optimizer.Cli/bin/Release/net8.0/Optimizer.Cli.dll optimize ` --list-append --enable-experimental-list-append --runtime-profile stock-t15-android-nonreload ` --aggregate-assembly-dir "$stripped" --aggregate-assembly ITClient.dll ` --aggregate-dependency SeaWarRes.dll --corelib mscorlib.dll ` --editor-root "$t15/Editor" --generated-root "$originalCpp" ` --selected-tu ITClient__104.cpp --discover-callers --output "$newOutput" ``` The report records the candidate calls in that TU and why each was applied or refused. The optimizer verifies all admitted edits together on the final C++ before publishing one replacement file. To inspect just NormalShip Text, replace `--discover-callers` with `--caller-token 0600a6a2`. For each candidate, the optimizer follows its closed Add and static receiver, derives the value layout, and checks that the append reads a private, fully copied local. Direct field stores and stores through single-use addresses of nested fields can qualify. A direct byref argument does not. Omit the enable flag to get stock bytes with no replay. This experimental mode uses the same pinned t15 export and runtime profile as Sprite append. The Sprite-specific discovery command retains its narrower element proof. On the measured TU this mode combined Model, Text, Sprite and Effect. Each fitting append saved one full element transfer; the four callers added 980 B of ARM64 code in total. See the [per-caller sizes and verification limits](docs/array-loop-range-report.md#discover-four-closed-list-appends-in-one-selected-tu). Development follows the [IL-guided C++ optimizer design](docs/superpowers/specs/2026-09-24-il-guided-cpp-optimizer-design.md) and [project workflow](AGENTS.md). The delivery target is a unified optimizer; individual experimental rules and indexing tools do not establish that this end-to-end product is complete. ## Bootstrap From this repository, run: ```powershell powershell -NoProfile -ExecutionPolicy Bypass -File tools/Seed-OptimizerRepository.ps1 dotnet build Optimizer.sln -c Release powershell -NoProfile -ExecutionPolicy Bypass -File tools/Smoke-Help.ps1 ``` Large generated trees and generator binaries are stored under `.artifacts/` and are ignored by Git. No command in this repository invokes IL2CPP during the bootstrap smoke test. ### Mainland download sources The LLVM 18.1.8 installer source is recorded in the analysis-toolchain manifest. An optional mainland access proxy (not an LLVM official mirror) is: ```text https://ghfast.top/https://github.com/llvm/llvm-project/releases/download/llvmorg-18.1.8/LLVM-18.1.8-win64.exe ``` Verify availability when downloading. The pinned installer SHA-256 is `94af030060d88cc17e9f00ef1663ebdc1126b35e16bebdfa1e807984b70abd8f`; the hash, rather than the mirror response, is the acceptance gate. `.NET` restore uses `NuGet.config`, with Huawei Cloud first and `nuget.org` as an explicit fallback. Restore explicitly when reproducing the checkout: ```powershell dotnet restore --configfile NuGet.config ``` Mirror availability is not treated as provenance: every downloaded artifact must still match its recorded SHA-256. ## Scope and non-goals IL and managed metadata provide semantic facts for transformations on exported C++. The first planned consumers are cross-TU call simplification and checks whose non-null or array-length facts can be proved; intrinsic coverage expands by semantic category. Simple-copy is an existing bounded experiment, not the product's entire scope. Implementation, unified-flow integration, and measured native benefit are tracked separately. Design coverage does not imply that all of these rules are implemented or enabled. The optimizer does not modify IL2CPP source or use LLVM IR as its production output. Editor export and baseline generation are input-preparation steps; ordinary optimization operates on the supplied matching bundle. `tools/Export-TuanjieNativeBundle.ps1` can create a fresh Android export from the pinned Tuanjie Editor in an isolated external work project. The script writes `Assets/csc.rsp` with `-langversion:10.0`, excludes stale Unity caches and Android output, and records a file-level manifest. A generated export is not considered replayable until a matching `compile_commands.json` is captured; the manifest remains `PendingCompilerDatabase` otherwise. For a new input, choose fresh paths and export with explicit editor identity (replace the source project path with the controlled input project): ```powershell $editorRoot = 'C:\Program Files\Tuanjie\Hub\Editor\2022.3.62t15' $editorVersion = '2022.3.62t15' $attemptRoot = '.artifacts\t15-input-new' # Must be unused for this attempt. $workRoot = Join-Path $attemptRoot 'work-project' $nativeRoot = Join-Path $attemptRoot 'native-bundle\android-project' $androidTools = Join-Path $editorRoot 'Editor\Data\PlaybackEngines\AndroidPlayer' pwsh -NoProfile -File tools/Export-TuanjieNativeBundle.ps1 ` -UnityEditorRoot $editorRoot -UnityEditorVersion $editorVersion ` -UnityEditorExe (Join-Path $editorRoot 'Editor\Tuanjie.exe') ` -SourceProject 'E:\path\to\controlled-project' ` -WorkRoot $workRoot -OutputRoot (Join-Path $attemptRoot 'native-bundle') pwsh -NoProfile -File tools/Replay-TuanjieNativeCompile.ps1 ` -BundleRoot $nativeRoot -NdkRoot (Join-Path $androidTools 'NDK') ` -OutputRoot (Join-Path $attemptRoot 'native-replay') pwsh -NoProfile -File tools/Capture-CompilerDatabase.ps1 ` -BundleRoot $nativeRoot -ReplayRoot (Join-Path $attemptRoot 'native-replay') ``` The capture records every compiler action from Bee's completed DAG and updates the bundle manifest to `ReplayableWithCompilerDatabase`. IL2CPP lump sources are retained in the external replay cache because they are part of that exact replay input. The separately generated baseline tree still requires a matching native bundle before it can be used for an optimizer result. Extract the matching generator using the fresh export's version evidence and capture the analysis toolchain with the same editor's Android tools: ```powershell $generatorRoot = Join-Path $attemptRoot 'generator' $toolchainManifest = Join-Path $attemptRoot 'toolchain\analysis-toolchain.json' pwsh -NoProfile -File tools/Extract-UnityIl2Cpp.ps1 ` -UnityEditorRoot $editorRoot -UnityEditorVersion $editorVersion ` -EditorVersionEvidencePath (Join-Path $workRoot 'ProjectSettings\ProjectVersion.txt') ` -DestinationArtifactRoot $generatorRoot -TargetTriple 'aarch64-linux-android22' pwsh -NoProfile -File tools/Capture-AnalysisToolchain.ps1 ` -UnityEditorRoot $editorRoot -OutputPath $toolchainManifest ``` `Capture-AnalysisToolchain.ps1` also needs its configured LLVM installation and installer. Supply `-ToolchainRoot` and `-InstallerPath` if they differ from the script defaults. Analysis LLVM is separate from the editor's native compiler. Use the fresh export's generated source/data as the baseline. If a separate `Generate-Baseline.ps1` run is needed, pass the matching extracted payload, `ManagedStripped` assemblies, and actual conversion switches explicitly, then verify its identity against the export. File counts and byte equality must be measured for that input; they are not fixed properties of an editor version. Create and validate a self-contained baseline artifact bundle with: ```powershell $generatedRoot = Join-Path $nativeRoot 'tuanjieLibrary\src\main\Il2CppOutputProject\Source\il2cppOutput' $bundleRoot = Join-Path $attemptRoot 'artifact-bundle' pwsh -NoProfile -File tools/New-ArtifactBundle.ps1 ` -EditorRoot $editorRoot -EditorVersion $editorVersion ` -GeneratorPayloadRoot (Join-Path $generatorRoot 'unity-editor-payload') ` -NativeBundleRoot $nativeRoot ` -CompilerDatabasePath (Join-Path $nativeRoot 'compile_commands.json') ` -BaselineGeneratedCppRoot $generatedRoot ` -OriginalDll (Join-Path $workRoot 'Library\Bee\artifacts\Android\ManagedStripped\Assembly-CSharp.dll') ` -CscResponseFile (Join-Path $workRoot 'Assets\csc.rsp') ` -AnalysisToolchainManifest $toolchainManifest -OutputRoot $bundleRoot dotnet run --project src\Optimizer.Cli\Optimizer.Cli.csproj -c Release -- ` validate-bundle $bundleRoot ``` The validator hashes the complete tree and rejects missing roots, path escapes, source-root outputs, and compiler databases whose first executable is IL2CPP. The bundle also retains the export's `input/csc.rsp` so the C# 10 language version is part of the recorded managed-input provenance. Validate the captured analysis toolchain before AST/IR work: ```powershell dotnet run --project src\Optimizer.Cli\Optimizer.Cli.csproj -c Release -- ` validate-toolchain $toolchainManifest ``` The AST and IR tools use this LLVM payload as an analysis oracle; their output is never treated as equivalent to the Unity native compiler's code generation. Evidence lifecycle and rolling retention are defined in [`docs/evidence-retention-policy.md`](docs/evidence-retention-policy.md). For repeated analysis iterations, `index-tree` and `emit-ir-tree` accept an external `--cache-root` plus the complete provenance key (`--clang-version`, `--target-triple`, `--toolchain-fingerprint`, `--bundle-identity`, and `--rule-version`). `FastIterative` reuses hash-valid Brotli-compressed TU entries; `FullAudit` rebuilds every translation unit. The cache is disposable, versioned binary data, while the emitted manifests remain canonical JSON. `FastIterative` still defaults to `FullExport`; request `--output-mode SelectedProjection` and explicit selection inputs to load and emit only selected TUs. See the [audit runbook](docs/audit-runbook.md) for scope and measurement rules. A complete index export alone is not a complete audit. ## Analysis and materialization After emitting a matching C++ index, IL/C++ mapping, O0 IR analysis, and planning report, materialize a separate optimized tree with the following template. Replace the placeholders with outputs from the same validated input: ```powershell dotnet run --project src\Optimizer.Cli\Optimizer.Cli.csproj -c Release -- ` optimized-tree ` --planning-report ` --cpp-index ` --bundle $bundleRoot ` --baseline-root (Join-Path $bundleRoot 'baseline\generated-cpp') ` --output ``` The materializer selects only index shards referenced by transformed method identities, then fully parses and hash-checks those shards and every rewritten source file. This keeps repeated materialization fast without weakening the full-bundle audit path; the baseline tree is never overwritten.