diff --git a/Build/dlr-patches/0111-interpreted-rule-runs-compiled.patch b/Build/dlr-patches/0111-interpreted-rule-runs-compiled.patch
new file mode 100644
index 000000000..456015f43
--- /dev/null
+++ b/Build/dlr-patches/0111-interpreted-rule-runs-compiled.patch
@@ -0,0 +1,80 @@
+diff --git a/src/core/Microsoft.Dynamic/Interpreter/LightLambda.cs b/src/core/Microsoft.Dynamic/Interpreter/LightLambda.cs
+--- a/src/core/Microsoft.Dynamic/Interpreter/LightLambda.cs
++++ b/src/core/Microsoft.Dynamic/Interpreter/LightLambda.cs
+@@ -151,6 +151,16 @@
+ return CreateCustomDelegate(delegateType);
+ }
+
++ ///
++ /// Runs , a compilation of the same lambda with the delegate type this LightLambda was made
++ /// for, from the next call on (DynamicUtils: an interpreted rule whose compiled rule the site never picked up).
++ ///
++ internal void UseCompiled(Delegate compiled) {
++ if (compiled is not null && _compiled is null) {
++ _compiled = compiled;
++ }
++ }
++
+ private bool TryGetCompiled() {
+ // A nested lambda light-compiled when it first runs (LightCompiler.CompileOnFirstCall); one the light compiler
+ // cannot interpret is compiled.
+diff --git a/src/core/Microsoft.Dynamic/Utils/DynamicUtils.cs b/src/core/Microsoft.Dynamic/Utils/DynamicUtils.cs
+--- a/src/core/Microsoft.Dynamic/Utils/DynamicUtils.cs
++++ b/src/core/Microsoft.Dynamic/Utils/DynamicUtils.cs
+@@ -113,6 +113,7 @@
+ // we failed the rule because we have a compiled target available, return the compiled target
+ Debug.Assert(CachedBindingInfo.LastInterpretedFailure.CompiledTarget is not null);
+ var res = CachedBindingInfo.LastInterpretedFailure.CompiledTarget;
++ CachedBindingInfo.LastInterpretedFailure.Rebound++;
+ CachedBindingInfo.LastInterpretedFailure = null;
+ return res;
+ }
+@@ -133,7 +134,10 @@
+ private T/*!*/ CreateDelegate(DynamicMetaObjectBinder/*!*/ binder, DynamicMetaObject/*!*/ binding, CachedBindingInfo/*!*/ bindingInfo) {
+ var lambda = Compile(binding, bindingInfo);
+ try {
+- return lambda.LightCompile(Int32.MaxValue);
++ T result = lambda.LightCompile(Int32.MaxValue);
++ // the interpreted rule, which can run its compiled body itself (CachedBindingInfo.CheckCompiled)
++ bindingInfo.Light = (result as Delegate)?.Target as Microsoft.Scripting.Interpreter.LightLambda;
++ return result;
+ } catch (NotImplementedException ex) {
+ // the interpreter doesn't support every expression, fall back to compiling the lambda
+ PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, $"LightBind fallback {binder.GetType().Name}: {ex.Message}");
+@@ -249,6 +253,23 @@
+ [ThreadStatic]
+ public static CachedBindingInfo LastInterpretedFailure;
+
++ // The LightLambda of the interpreted rule; null if it is not one.
++ public Microsoft.Scripting.Interpreter.LightLambda Light;
++
++ // How often the rule has failed because its compiled target was ready, how often that failure had the site bind
++ // again and pick up the compiled rule (Bind, from LastInterpretedFailure), and how many failures that did not the
++ // rule may have before it runs its compiled target itself. A binder that binds the site some other way never picks
++ // it up, and a site whose rules come in a different order can hold both the interpreted rule and the compiled one:
++ // the interpreted one, never matching, stays before the other in the site's rules and runs in the interpreter, to
++ // fail, on every call (a `!=` site over four or eight classes, 2.2-3 times as slow), millions of times. A failure
++ // that rebinds is the scheme working and is not counted; nor is it there to count every time: a site with more classes
++ // than it keeps rules for finds the interpreted rule in the binder's cache again and again, and switching such a rule
++ // to its compiled target in place (32 failures) left the binder's cache with rules behind a LightLambda's Run: 60
++ // classes 18% slower. Hence a count that only a rule stuck before its compiled one reaches.
++ private int _failuresForCompiled;
++ public int Rebound;
++ private const int MaxFailuresForCompiled = 4096;
++
+ public CachedBindingInfo(DynamicMetaObjectBinder binder, int compilationThreshold)
+ : base(binder, compilationThreshold) {
+ }
+@@ -269,6 +290,12 @@
+ }
+
+ if (CompiledTarget is not null) {
++ var light = Light;
++ if (light is not null && ++_failuresForCompiled - Rebound > MaxFailuresForCompiled) {
++ // run the compiled rule in place from the next call on, and match this one
++ light.UseCompiled(CompiledTarget as Delegate);
++ return true;
++ }
+ LastInterpretedFailure = this;
+ return false;
+ }
diff --git a/Build/dlr-patches/0112-compile-rewriter.patch b/Build/dlr-patches/0112-compile-rewriter.patch
new file mode 100644
index 000000000..b7b877ea7
--- /dev/null
+++ b/Build/dlr-patches/0112-compile-rewriter.patch
@@ -0,0 +1,33 @@
+diff --git a/src/core/Microsoft.Dynamic/Interpreter/LightDelegateCreator.cs b/src/core/Microsoft.Dynamic/Interpreter/LightDelegateCreator.cs
+--- a/src/core/Microsoft.Dynamic/Interpreter/LightDelegateCreator.cs
++++ b/src/core/Microsoft.Dynamic/Interpreter/LightDelegateCreator.cs
+@@ -13,6 +13,16 @@
+ using Microsoft.Scripting.Utils;
+
+ namespace Microsoft.Scripting.Interpreter {
++ ///
++ /// A hook for the language: , if set, is given each interpreted lambda's tree just before it is
++ /// compiled to IL, and what it returns is compiled instead. It must return a lambda of the same type and parameters that
++ /// computes the same thing - for instance one whose constants are typed so that loading them is cheaper. The interpreter
++ /// keeps running the tree it was given. Process-wide: set it once, to something that holds no state of one runtime.
++ ///
++ public static class LightCompilation {
++ public static Func Rewriter { get; set; }
++ }
++
+
+ ///
+ /// Manages creation of interpreted delegates. These delegates will get
+@@ -256,6 +266,12 @@
+ lambda = Expression.Lambda(_compiledDelegateType, lambda.Body, lambda.Name, lambda.Parameters);
+ }
+
++ // the language's last word on the tree before it is compiled to IL (LightCompilation.Rewriter)
++ var rewriter = LightCompilation.Rewriter;
++ if (rewriter is not null) {
++ lambda = rewriter(lambda);
++ }
++
+ if (HasClosure) {
+ _compiled = LightLambdaClosureVisitor.BindLambda(lambda, Interpreter?.ClosureVariables ?? _closureVariables);
+ } else {
diff --git a/Build/dlr-patches/README.md b/Build/dlr-patches/README.md
index faf55db42..61f101069 100644
--- a/Build/dlr-patches/README.md
+++ b/Build/dlr-patches/README.md
@@ -33,6 +33,8 @@ the apply step instead of with a confusing CS1061 deep inside IronRuby.
| `0108-ThreadLocal-no-dead-thread-roots.patch` | `ThreadLocal`'s entries (the interpreter's current frame among them) held the Thread that owns them, and an entry stays in the array after its thread has finished, until the array next grows. Every Ruby thread that had run interpreted code was kept alive that way, and with it the CLR's native record of the dead thread and its `ManagedThreadId`: thousands of dead threads piled up in the runtime's thread list, which the finalizer thread walks to remove each one and every GC suspension walks too (`Thread.new { }.join` in a loop spent most of its process CPU in `ThreadStore::RemoveThread`). An entry now carries a per-thread token object instead (weakly mapped from the Thread for `TryGetValue`, patch 0001), so a finished thread is collected and its id reused; a new thread that gets the id replaces the stale entry on first use. |
| `0109-interpret-deep-try-nesting.patch` | The CLR's JIT takes time cubic in how deeply a method's try regions nest under exception filters: for each block of a filter it goes through every region the filter's try encloses and walks that region's chain of enclosing regions up to the filter (`BasicBlock::VisitEHEnclosedHandlerSecondPassSuccs`, called by every flow-graph walk with exception edges; .NET 8 to 10, and .NET 11's is no better). IronRuby's begin/rescue is filters and finallys, four or more try expressions a level, so `begin ... rescue; end` nested 500 deep and compiled up front (`-X:CompilationThreshold 0`, as IronRuby.Tests run) spent over a minute in `DynamicMethod.CreateDelegate` (`DeepNesting1`: 75 s); interpreted it takes 1.5 s. The light compiler now records how deeply a lambda's try expressions nest - or those of a lambda nested in it, such as a block, which a compile of the outer one compiles too - and `LightDelegateCreator.Compile` leaves a lambda deeper than 64 (some 15 levels of begin/rescue) interpreted, which is linear. A lambda the light compiler cannot interpret is still compiled, and so is everything under `-X:NoAdaptiveCompilation`. `DeepNesting1` now takes 2.4 s; the 500-deep script alone, compiled up front, 0.4 s more than an empty one (1000 deep: 0.7 s). |
| `0110-compile-nested-lambdas-on-first-call.patch` | The light compiler compiled every lambda nested in the one it compiled - a block, a closure - with it, whether or not it ever ran. `LightCompiler.CompileOnFirstCall` lets the language name the nested lambdas to compile when a delegate made from one first runs instead (IronRuby: lambda literals, `->`). The variables such a lambda closes over are found by a walk of its tree, so the enclosing lambda boxes them and hands them over in the same order as before; the nested lambda is compiled against exactly those (a variable the walk missed fails loudly as "unbound variable"). `LightDelegateCreator` holds the lambda until its first run (`EnsureLightCompiled`), its `LightLambda` gets the interpreter then (or, for a lambda the light compiler cannot interpret, the compiled delegate), and a compile of the enclosing lambda to IL light-compiles the ones still pending to learn how deeply their try expressions nest (0109). prism's `Serialize::Loader#define_load_node_lambdas` makes 152 lambdas and the first parse calls a few: its first call went from 160 to 105 ms. |
+| `0111-interpreted-rule-runs-compiled.patch` | A rule `DynamicUtils.LightBind` makes runs interpreted until its count runs out, then compiles in the background and, once compiled, fails its test so that the site binds again and the binder hands out the compiled rule (`CachedBindingInfo.LastInterpretedFailure`). When the site gets the compiled rule some other way - IronRuby's shared rules, which serve every receiver class whose method resolves the same, are handed to a site as it binds - the interpreted one can stay ahead of it in the site's rules, never matching, and run in the interpreter to fail on every call: `recv != other` over four or eight classes took 2.2-3 times as long in some processes and not in others (gap 12, perf/twospeed). Such a rule now runs its compiled target itself (`LightLambda.UseCompiled`) once it has failed for it 4096 times without the site binding again (a stuck rule fails millions of times; the rules of a site with more classes than it keeps rules for fail far fewer, and switching those in place after 32 failures made 60 classes 18% slower), and matches again. |
+| `0112-compile-rewriter.patch` | `Microsoft.Scripting.Interpreter.LightCompilation.Rewriter`: a hook the language sets to rewrite an interpreted lambda's tree just before `LightDelegateCreator` compiles it to IL (the interpreter keeps the tree it had). IronRuby's `CompiledConstantsRewriter` uses it so that a compiled body loads its constants - its call sites among them - as objects given their class by `Unsafe.As`: `LambdaExpression.Compile` casts each closure constant to its type on every load, and in Ruby's bodies each such cast is a call of the runtime's cast helper, 7-12% of a small Ruby method's instructions. Unset, nothing changes. |
`Util/check-dlr-patches.sh DLR_DIR` checks that a DLR checkout has all of these applied:
a local one is patched once and falls behind when a new patch lands here.
diff --git a/CLAUDE.md b/CLAUDE.md
index 9bb4a27f9..7f3b466e3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -169,6 +169,7 @@ invalid definition is a build error (`IRGEN001`). To read what was generated, bu
| `Src/Ruby/Builtins/UnicodeProperties.Generated.cs` | `Util/gen-unicode-properties.rb` | |
| `Src/Ruby/Runtime/Utf8MacTables.Generated.cs` | `Util/gen-utf8-mac.rb` (with CRuby) | the oracle CRuby's UTF8-MAC converters change |
| `Src/Ruby/Builtins/InspectPrintable.Generated.cs` | `Util/gen-inspect-printable.rb` (with CRuby) | the oracle CRuby's Onigmo ctype tables change |
+| `Src/Ruby/Builtins/CaseFoldGroups.Generated.cs` | `Util/gen-case-fold-groups.rb` (with CRuby) | the oracle CRuby's case folding (its Unicode version) changes |
| `*/AotSubclasses.Generated.cs` | `Util/aot/gen-subclasses.rb` | a library class is added |
| `Src/Libraries/Rbs/RbsNodes.Generated.cs` | `Src/Libraries/Rbs/generate.rb` | |
diff --git a/Docs/block-calling-convention.md b/Docs/block-calling-convention.md
new file mode 100644
index 000000000..185c16526
--- /dev/null
+++ b/Docs/block-calling-convention.md
@@ -0,0 +1,270 @@
+# A block that is not a Proc until it escapes: design
+
+Status: design (round thirty-seven, perf/bcc); stage 0, the attribution, done in perf/stage0 - see
+"Stage 0: measured" below, which replaces the arithmetic bounds of section 4. It follows `Docs/light-frame-literal-blocks.md`,
+whose three experiments removed the candidates one by one: the full call site costs nothing
+(perf/literalsite), publishing the frame's scope costs nothing (perf/procscope), and allocating the
+scope and the Proc costs what reusing them does (`IR_PARKED_SCOPES=0` leaves every time as it is). What
+is left is the work of the block protocol itself. This document says what that work is, what CRuby does
+instead, a representation that could skip it, and stages that can each be built and kept on their own.
+**Stage 0 is a measurement**, because the gain of every later stage depends on which steps cost what,
+which this host cannot show (no `perf`; callgrind does not name JIT code).
+
+## 1. The cost model
+
+### Measured (round thirty-seven, this host, Release net10.0, ns and bytes per call of the caller)
+
+The caller is a light method; `ny` is `def ny; yield; end`, `keep` is `def keep(&b) = b`, `pass` is
+`def pass(&b) = ny(&b)`. Bytes are the thread's allocated bytes; 22 B of each line is the driver's
+(`nb0`, a call without a block, has them too).
+
+| shape | CRuby ns | IronRuby ns | bytes | parking off: ns, bytes | light frames off: ns, bytes |
+|---|---|---|---|---|---|
+| `nb0`: `nb` | 36 | 59 | 22 | 37, 22 | 30, 22 |
+| `ny1`: `ny { 1 }` | 50-53 | 160-161 | 70 | 169, 358 | 185, 518 |
+| `nys`: `s = 0; ny { s += 1 }; s` | 63 | 158 | 54 | 174, 342 | 184, 502 |
+| `e1`: `a.each { \|x\| }` over [1] | 73-75 | 142-145 | 70 | 161, 358 | 136, 70 |
+| `e1s`: `s = 0; a.each { \|x\| s += x }; s` | 81 | 147 | 54 | 161, 342 | 142, 54 |
+| `pon`: `pass { 1 }` (passed on) | 85 | 195 | 358 | 194, 358 | 254, 702 |
+| `cv`: `keep { 1 }.call` (converted) | 239 | 172 | 358 | 170, 358 | 205, 542 |
+
+What it says:
+
+- **A literal block costs IronRuby about 100 ns per call against CRuby's 15-40.** `ny { 1 }` is 160
+ against 50; the yield itself is about 11 ns (perf/yieldloop), as CRuby's is.
+- **The bytes are not the time.** With parking, a call allocates 48 bytes beyond the driver; without it
+ 336, and the time moves by 10 ns or less. Light frames off (a scope at entry) adds 160 bytes and
+ ~25 ns to the Ruby-callee shapes. The ~290 bytes a literal used to cost, by the classes' fields (not
+ measured one by one): the method scope (~140), the Proc (~80), its BlockParam (~48), the locals tuple
+ (~24).
+- **Passing a block on is never parked** (`pon`: 358 bytes and 195 ns, parking on or off): the callee
+ that names its block (`&b`) converts the Proc as a method's (`ConvertAsMethodFrame`), which is not
+ reusable.
+- **Converting is already cheaper than CRuby** (`cv` 172 against 239): CRuby makes its Proc and moves
+ the frame's environment to the heap then (`vm_make_env_object`); IronRuby already has both.
+
+### What IronRuby does per call of `ny { 1 }` from a light method (read from the code)
+
+| step | where | what |
+|---|---|---|
+| 1 | caller | the scope made on demand: `TakeParkedScope` (an exchange) and `ReuseParkedScopeLazy` (a dozen fields), or `CreateMethodScopeLazy`; the locals tuple made at entry (`MakeLocalsStorage`: a body with a literal keeps its locals in a heap tuple) |
+| 2 | caller | the Proc: `InstantiateParkedBlock` (the parked Proc taken, `ReuseParked`, `TryReuse`), or `new Proc` |
+| 3 | caller | the call through the light site, the Proc its block argument (perf/literalsite) |
+| 4 | callee | `CreateRfcForMethod(proc)`: the Proc becomes the callee's flow-control frame (`ConvertAsFrame`: kind, the reusable flag, `_activeFlowControlScope`) - it is what a `break` in the block targets |
+| 5 | callee | `yield`: `ReuseBfcForYield` (the Proc's `YieldBlockParam` reset), `RubyOps.Yield0`/`Yield1` -> the dispatcher -> the block's compiled lambda |
+| 6 | block | entry: `EnterScopeFreeBlock` or `TakeReusableBlockScope`/`CreateReusableBlockScope` (a block that reads an enclosing local reaches it through `Proc.LocalScope`) |
+| 7 | callee | after the yield: `LightMethodYield` (the BlockParam's return reason: break?) |
+| 8 | callee | exit: `LeaveLightMethodFrame(rfc, scope)`: the Proc is an active rfc, so the slow path, `LeaveMethodFrame` |
+| 9 | caller | exit: `BeginPark` / `StageParkedProc` / `EndPark` (an exchange, `ClearForPark`, `ClearCallState`) |
+
+### What CRuby does
+
+The caller's control frame holds a captured block, `rb_captured_block { self, ep, code.iseq }`, written by
+`send` with no allocation; the callee receives a *block handler*, that pointer tagged as an iseq block
+(`VM_BH_FROM_ISEQ_BLOCK`). `yield` (`vm_invoke_iseq_block`) pushes a frame for the block whose `ep` is the
+captured one, so the block reads the caller's locals in the caller's own stack frame. `break` finds its
+target by the captured `ep`. Nothing is on the heap until something asks for a Proc (`&b`, `proc`,
+`binding`): `rb_vm_make_proc` then moves the environment to the heap (`vm_make_env_object`) and every
+frame that shares it follows. Steps 1, 2, 4, 8 and 9 above have no counterpart; 5-7 are a frame push.
+
+## 2. The representation
+
+A **block descriptor**: what a callee needs to yield to a literal, and nothing it needs only when the
+block escapes.
+
+ sealed class BlockDescriptor : RuntimeFlowControl // it is the callee's flow-control frame, as the Proc is now
+ object Self
+ BlockDispatcher Dispatcher // the literal's code
+ MutableTuple Locals // the caller frame's tuple (or null: a narrow literal)
+ FrameHeader Frame // the caller's rfc, declaring scope, module, shape, block, callee name
+ Proc Materialized // the Proc made from it, once something asked
+
+- **One per (literal, frame), reused across calls of the frame**, as the parked Proc is now, but taken
+ with no exchange: a light frame owns its descriptors in CLR locals for the call (the caller is the
+ only one that runs the literal), and a recursive or concurrent call of the same method has its own
+ frame and its own descriptors. So the per-call work of steps 1, 2 and 9 becomes: fill four fields.
+- **The scope is made from it on demand** - `binding`, `eval`, `local_variables`, a TracePoint, a callee
+ that answers LightScopeRequired, `$~` - from `Frame` and `Locals`, exactly as the light frame's lazy
+ scope is made today, and kept on the descriptor (one scope per invocation: the frame's own lazy scope
+ takes the descriptor's if it exists).
+- **The Proc is made from it on demand** (`Materialize`): when a callee converts the block (`&b` in a
+ Ruby callee, `Proc.new`, `define_method`, `proc`, `lambda`, a C# method whose block parameter is a
+ `Proc` and not a `BlockParam`), or stores it. The Proc's scope is the descriptor's scope, made then;
+ from then on the descriptor answers with that Proc and is not reused by the frame's next call (it
+ escaped). That is CRuby's `rb_vm_make_proc`.
+
+What each kind of callee does with it:
+
+| callee | today | with a descriptor |
+|---|---|---|
+| a library `[BlockNotKept]` iterator (Array#each, Integer#times...) | `CreateBfcForBlockNotKept(proc)`: the Proc's reused BlockParam | a BlockParam over the descriptor (its `Proc` property materializes); the yield goes to `Dispatcher` with `Self` and the descriptor as the block's parent frame |
+| a Ruby method that only yields (`def ny; yield; end`, a light frame) | step 4, 5, 7, 8 | the descriptor is its rfc; `yield` calls `Dispatcher` directly; `LightMethodYield` reads the descriptor's flow state |
+| a Ruby method that passes it on (`def pass(&b) = ny(&b)`) | converted as a method's: never reused, 358 bytes | stage (c): a `&b` that is only passed on passes the descriptor (the light frame's block parameter is a descriptor until something reads `b` otherwise) |
+| a method that converts it (`&b` read, `Proc.new`, `define_method`) | the Proc | `Materialize` |
+
+## 3. Every way it can escape or be observed
+
+| how | what must happen |
+|---|---|
+| `&b` read as an object, stored, returned, `b.call` | `Materialize`: the Proc, over the scope made from the frame now; the descriptor is spent |
+| `Proc.new`/`proc`/`lambda` with no block of their own, `define_method`, `instance_exec(&b)` | the same, through the BlockParam's `Proc` |
+| `binding` in the block, `eval`, `local_variables`, `__method__` | the block's scope is made with the descriptor's scope as its parent, made now from `Frame` and `Locals` |
+| `binding`/`eval` in the caller after the call | the caller's lazy scope is the descriptor's if one was made (one scope per invocation) |
+| a TracePoint `:b_call`/`:line` in the block, `binding.local_variables` | as `binding` in the block |
+| `$~`, `$_` set by a callee of the block | through LightScopeRequired: the block's scope, with the descriptor's scope as parent |
+| `break` | the descriptor is the callee's rfc, as the Proc is now (`SetFlowControl(Break, converter)`); after the frame returned, `LocalJumpError` as today (the frame header says the method has left) |
+| `return` in the block | not in the first stages (the narrow shape has none) |
+| `next`, `redo`, raise, throw | the block's own; nothing reaches the descriptor |
+| a Fiber suspended in the block, `Enumerator#next` | the descriptor stays in use until the callee returns; the frame does not reuse it while its call is in flight (it owns it for the call) |
+| another thread running the block (a callee that hands it to `Thread.new`) | that is a conversion (`Thread.new` takes a Proc): materialized |
+| re-entrancy: the block calls the caller's method again | a new frame, its own descriptors |
+| `yield` after the callee returned (a Proc kept and called) | only a materialized Proc can be kept; its scope's frame header says the method left |
+| `block_given?` in the callee | true: the descriptor is a block |
+| `Proc#==`, `object_id` of the block | only on a materialized Proc |
+
+## Stage 0: measured (perf/stage0)
+
+`Src/IronRuby.Tests/Perf/BlockCostHarness.cs`, run as `IronRuby.Tests /blockcost [N]` (not a test: the
+driver runs it only for that switch). It hosts a runtime, takes real objects from Ruby code - a literal's
+compiled block dispatcher, a method scope, its declaring scope and module - and times the runtime calls the
+compiled code makes, each alone and then together, Stopwatch over 3,000,000 iterations, best of five after
+a warm-up, Release net10.0; then the same calls end to end through Ruby. Two runs agree to a few ns.
+
+| step (ns per call) | alone |
+|---|---|
+| the locals tuple (`MakeLocalsStorage`) | 6 |
+| a scope made (`CreateMethodScopeLazy`, allocation and its collection) | 45-55 |
+| a Proc made (`new Proc`) | 16-17 |
+| **the parked cycle**: take the scope, reinitialize it, make the Proc again, stage, park | **45-48** |
+| - take and park with nothing between (`TakeParkedScope`, `BeginPark`, `EndPark`) | 23-25 |
+| - plus the scope reinitialized (`ReuseParkedScopeLazy`) | +6 |
+| - plus the Proc made again and staged (`InstantiateParkedBlock`, `StageParkedProc`) | +8 |
+| - the scope's fields cleared and set again, alone (`ClearCallState`, `Reinitialize`) | 7 |
+| - one `Interlocked.CompareExchange`, against a `Volatile.Write` | 10.4 against 2.5 |
+| the light callee's entry and exit (`EnterLightMethod`, `LeaveLightMethodFrame`) | 3 |
+| a yield to `{ 1 }` (`ReuseBfcForYield`, `Yield0`, the block, `LightMethodYield`) | 15-17 |
+| a `[BlockNotKept]` yield to `{ \|x\| }` (`CreateBfcForBlockNotKept`, `Yield`, `LeaveProcConverter`) | 15-17 |
+| `nyl`, all its steps together (parked on every call) | 68-73 |
+| `e1`, all its steps together | 52-53 |
+
+End to end, ns per call with the caller's loop: `nb0` (a call without a block) 42-53, `nyp` (`ny(&PY)`, a stored
+Proc) 98-101, `nyl` (`ny { 1 }`) 148-155; `e0` (no call) 24-26, `ep` (`a.each(&PE)`) 86-92, `e1` (`a.each { |x| }`)
+133-145. So:
+
+- **The literal itself costs 50-54 ns** (`nyl` - `nyp`, `e1` - `ep`), and the parked cycle plus the locals
+ tuple is 52: **the literal's cost is the parked cycle, entirely.** Of it, about 16 ns are its two atomics
+ (the take's and the park's), 6 the scope's reinitialization, 8 the Proc made again, 6 the tuple, and the
+ rest the cycle's checks and clearing.
+- **Passing any block and yielding to it costs another 55-63 ns** (`nyp` - `nb0`, `ep` - `e0`): the yield 16,
+ the callee's conversion 3, and 35-45 ns in the compiled code around them - the call site with a block, the
+ library rule's flow-control frame, the light frames' prologues and epilogues - which no runtime call
+ stands for and the harness cannot split further. CRuby's whole `ny { 1 }` is 14 ns over its `nb`.
+- **The sums hold**: `nyl`'s steps (68-73) are its end to end minus `nb0` (about 100) less those 35 ns; `e1`'s
+ (52) are its end to end minus `e0` less the 60 of calling `each` with a block at all.
+
+### The stages, by these numbers
+
+| stage | what it removes | measured bound per call | of |
+|---|---|---|---|
+| A: `[BlockNotKept]` iterators, narrow literals | the parked cycle and the tuple for those calls | up to ~50 ns (`e1` 133-145 -> ~85-90, `ep`'s) | CRuby 73 |
+| B: Ruby methods that only yield | the parked cycle, and the conversion | up to ~55 ns (`nyl` 148-155 -> ~95-100, `nyp`'s) | CRuby 50 |
+| C: pass-on | the 336 bytes and the unparked Proc of every pass-on | not measured here | |
+| D: literals that read locals | as A and B for those | as A and B | |
+| (none) the call with a block, the yield | 35-63 ns of compiled-code work around a block call | not reached by the convention: gap 1's call sites | |
+
+**Which pays most for one round's work: A.** It needs the descriptor only on the library side (a
+`CreateBfcForBlockNotKept` overload, the narrow shape's instantiation in the caller) and takes up to the
+same ~50 ns as B, which needs the light callee's entry, yield and `block_given?` to take a descriptor.
+
+**A step cheap to cut by itself, without the new convention: the park's atomic.** `EndPark` publishes the
+parked scope with `Interlocked.CompareExchange`; a `Volatile.Write` does the same job (a call that parked in
+the meantime loses its scope to the garbage; a taker's exchange still makes what it takes its own) and is
+8 ns cheaper per call of every method with a parked literal - about 15% of the literal's cost. perf/iter3
+tried exactly this and saw nothing end to end, where the host's noise was larger than 8 ns; the harness
+shows it. It is a round of its own (the take must stay atomic: two threads may reach for the same parked
+scope).
+
+### Stage A, simulated before it was built (perf/stagea)
+
+The harness times `e1`'s call as stage A would make it (the rows "e1: all steps (descriptor, ...)"): the
+Proc taken from its slot by the thread that owns it, with no atomic, its scope never made, a frame header
+filled for the scope to be made from on demand, the yield, and the Proc given back. ns per call, two runs:
+
+| `e1`'s steps | ns | bytes |
+|---|---|---|
+| parked, as now (after perf/endpark) | 40-44 | 24 (the tuple) |
+| descriptor, the whole header stored per call | 57-62 | 24 |
+| descriptor, only the fields that change per call stored (the tuple, the rfc) | 41-47 | 24 |
+| descriptor, no header (not sound: a scope made on demand could not be made) | 29-33 | 0 |
+
+**Stage A does not pay.** Filling the header is a set of reference stores into a heap object, each a GC
+write barrier, which is what the parked scope's reinitialization costs too; the stage-0 bound took the fill
+as free. The tuple cannot be dropped (`Locals = null` above): a `send(:binding)` in a narrow literal shows the
+method's locals, in CRuby too. And the end to end does not sit in the runtime steps alone: `ept` (`ep` with a
+narrow literal in a branch never taken) is 100-102 ns against `ep`'s 90-92 and `e1`'s 145-151, so having a
+literal costs the frame 10 ns and evaluating it 45-49, of which the steps a descriptor would replace are about
+29. Stages B and D carry the same fill. What would pay is the block reaching the caller's state in place, as
+CRuby's captured `ep` does, which objects passed through call sites cannot do.
+
+## 4. Stages
+
+Each behind a switch of its own, with its matrix before its code, keepable alone.
+
+**Stage 0 - attribution (no runtime change).** Where do the ~100 ns of `ny { 1 }` and the ~70 of
+`a.each { |x| }` go among steps 1-9? A `perf` profile on a host that has it (`Util/perf/profile.sh` with
+a shape driver), or the steps timed one by one in C# (a test harness that runs the emitted sequence with
+each step replaced by a no-op that keeps its result). The table of steps above is the checklist. Expected
+outcome: an upper bound for each stage below; build only the stages whose steps carry the time.
+
+**Stage A - `[BlockNotKept]` library iterators, narrow literals, light callers.** The literal of the
+narrow shape (`MethodDefinition.HasOnlyNarrowLiterals`) given to a `[BlockNotKept]` library method is
+passed as a descriptor with `Locals = null` (the literal reads no local) and `Frame` the light frame's
+header; `CreateBfcForBlockNotKept` gains an overload taking it. Removes steps 1, 2 and 9 for those calls
+(the scope is never made unless escaped). Upper bound: `e1` 142 -> about `nb0` + the iterator + the
+yield, by the table near 90 (CRuby 73). Matrix: `Util/literal-block-light-matrix.rb` sections 1-5 for
+Array#each, #map, Integer#times, Hash#each; the escape rows of section 3 above (a `binding` through
+`send` in the block, `$~` set through `send`, a TracePoint `:b_call` binding, `break` with an ensure,
+Enumerator#next suspended in the block, re-entrancy, four threads); `IR_LIGHT_FRAMES=0`,
+`IR_PARKED_SCOPES=0`, the switch off.
+
+**Stage B - Ruby methods that only yield.** A light callee whose block is a descriptor uses it as its rfc
+and yields to `Dispatcher` directly (steps 4, 5, 8 lose their Proc work). Needs the light frame's yield
+(`YieldCall` in `LightFrameRewriter`) and `LightMethodYield` to take a descriptor, and `block_given?`,
+`defined?(yield)` and `super` (which passes the block on) to see one. Upper bound: `ny1` 160 -> about
+`nb0` + one yield, near 75 (CRuby 50). Matrix: block-given, block-pass, block-scope-reuse (all three),
+block-nest-reuse, light-entry, light-rest, parked-scope, parked-iterator, plus a new row set for a Ruby
+callee that yields, passes on, converts, and calls `block_given?`, each with a descriptor.
+
+**Stage C - pass-on.** A light frame whose `&b` is only passed on (`def pass(&b) = ny(&b)`,
+`IsScopeFree`'s block pass) keeps a descriptor as a descriptor; any other read of `b` materializes.
+Upper bound: `pon` 195 -> near `ny1` after stage B, and its 336 bytes to the driver's. Matrix:
+block-pass-matrix, and a pass-on chain of three with a conversion at each depth.
+
+**Stage D - literals that read the frame's locals.** `Locals` the frame's tuple; the block's compiled
+code reads its parent tuples from the descriptor instead of `Proc.LocalScope` (BlockDefinition's
+`CreateScopeWithParent`). This is the general case (`e1s`, `nys`) and the one where CRuby's frame-pointer
+design matters most; it needs the block's lambda to take a parent that is not a scope, which touches
+every closure access. Upper bound: `e1s`, `nys` to stage A's and B's numbers.
+
+## 5. What the method JIT and the light frames must change
+
+- **Light frames** (`MethodDefinition.TransformLightFrame`, `LightFrameRewriter`): the literal's
+ instantiation becomes the descriptor's fill (stage A on); the lazy scope takes the descriptor's scope
+ (one per invocation); the exit drops `BeginPark`/`EndPark` for bodies whose literals are all
+ descriptors; a light callee's entry takes a descriptor as its rfc (stage B); its block parameter may be
+ a descriptor (stage C), with every read of it that is not a pass-on materializing.
+- **Call sites** (`RubyCallAction`, `MethodDispatcher`, the library binder): the block argument's static
+ type is `object` (a Proc or a descriptor); rules that bind a `Proc` parameter materialize; rules that
+ bind a `BlockParam` take either. `[BlockNotKept]` is what says a library method takes a descriptor.
+- **The method JIT** (`Runtime/Jit`): it never wraps a method that uses its block (the screen), so stages A
+ and C do not reach it; a typed body that *calls* an iterator with a literal block (stage A's caller)
+ bails today at the call with a block (`EmitCall`: "call with a block") unless it is a nested block loop
+ in an outlined core iterator (`JitCompiler.Nest.cs`), so nothing changes there either. Stage B makes a
+ yielding method's entry take a descriptor, which the JIT's entry stubs (`JitStub`) must pass through
+ untouched (they forward `blk`).
+- **The block-loop tier** (`BlockLoopSite`, OSR): it outlines a block into a C# iterator's loop from the
+ BlockParam's Proc; with a descriptor it reads `Dispatcher`/`Self` from it, and a block-loop copy that
+ needs the block's scope asks the descriptor.
+- **BlockParam** keeps one shape: it gains a descriptor field and a `Proc` property that materializes;
+ `IsLibProcConverter`, `Break`, `ReturnReason`, `MethodYield` read the descriptor where they read the Proc's
+ frame.
diff --git a/Docs/jit-resume-deopt.md b/Docs/jit-resume-deopt.md
index fddd4cd43..ff1d92034 100644
--- a/Docs/jit-resume-deopt.md
+++ b/Docs/jit-resume-deopt.md
@@ -2,7 +2,8 @@
Status: stage 1 is implemented behind `-X:JITResume` (off by default; `Src/Ruby/Runtime/Jit/JitResume.cs`,
`JitCompiler.Resume.cs`, matrix section 11 of `Util/jit-matrix.rb`), narrowed as its section says; the rest
-is design only. It answers gap 1 of `Util/perf/LEDGER.md`
+is design only, including a second look at stage 2 (round thirty-seven: the slices counted, not built) and stage 3a at the end (a yield in an outlined loop, gap 18), whose matrix is
+`Util/yield-loop-matrix.rb`. It answers gap 1 of `Util/perf/LEDGER.md`
("Calls of other methods from hot bodies"): `CallSite.Target` is 24-32% of every benchmark,
and Richards, Towers, DeltaBlue, Bounce and CD's `tree_insert` all wait on one rule of the
method JIT.
@@ -377,3 +378,316 @@ the `while` statement with `#resume` clear, and the generic code evaluates the c
the first's index, which would run an iteration whose condition nobody evaluated. Then
`-X:JITResume` on by default, after a full sweep and the benchmark suite, if stages 1-4
measured as faster.
+
+## Stage 2 again (round thirty-seven, 2026-11-28): what a general call needs, the slices, their reach
+
+Asked again after perf/jiteach and perf/jiteqq: both found that taking one more construct past the screen only moves
+a method to its next refusal, which is usually an ordinary call. So: what would a typed body need to make a call of
+any method, and is there a slice of that which is sound in one step and reaches something hot? This section answers
+from the code as it stands and from counts; nothing was built.
+
+### What a general call needs
+
+A call of an arbitrary method is an effect that can do anything: redefine methods, reassign constants, enable a
+TracePoint, write the caller's locals through a binding, raise, re-enter the method. Four things follow.
+
+- **Its result.** `Obj`, always: no profile of a callee's result makes a typed value without a guard, and a guard
+ after the call is a deopt after an effect. Code after it that consumes the value takes it as an object (the
+ self-guarded tail of stage 1, or nothing speculative at all).
+- **A deopt after it.** It must never re-run the call. Restarting the generic body does (that is the current rule's
+ whole reason), so a deopt after a call must continue in generic code: a per-operation fallback (A) where the
+ operation's result is an object, or a resume at the next statement boundary with the frame state written into the
+ scope (B, stage 3) where it is typed or the world changed. Until B exists, nothing that can deopt may follow a
+ call.
+- **What it invalidates.** The entry checked the method version, the constant version and tracing once, on the way
+ in. After a call every one may have moved: each later speculative operation re-checks what it depends on itself
+ (A's rule: `GlobalMethodVersion`, the constant version, `TracePoint.ActiveEvents`), or the body is handed to the
+ resumable generic body at the next statement (B). Self's class and the shape of its instance variables can change
+ too (`extend`, `instance_variable_set`, `remove_instance_variable`), which the typed body's unguarded ivar slots
+ assume; an ivar read after a call has to be the generic read or a re-guarded one.
+- **Exceptions and frames.** The callee's backtrace must show this method at the call's line, once: stage 1's
+ `JitResumeInfo.Slow` (a lambda named as the generic body's frame, keeping the line in `PrecompiledFrames` while the
+ call runs) does that without a frame on the fast path. A `rescue` around the call is the generic body's; a typed body
+ with one around a call is declined. The callee may need the caller's scope (a protected or missing method, a refined
+ name, a library method that reads it): the light-scope site answers `LightScopeRequired` and the call is made again
+ through the full site with the scope made once, with the method's block in it (`CreateMethodScopeLazy`, which takes
+ the block off the reusable list), in the light frame's try/filter/finally so `return` from a proc made there and
+ LocalJumpError after the method returned are right. Once that scope exists the locals live in it (see "Once the
+ scope exists"): the call that made it must be the last thing the typed body does, or the body resumes (B).
+
+### The narrowest slice that is sound now
+
+A typed body whose one general call is its **last** operation: the call's result is the method's value, nothing
+after it can deopt or read a local, so nothing has to be resumed, re-checked or written back; a scope the call makes
+is made with the final values of the locals. Everything above reduces to: stage 1's fallback site as the primary
+path, the light frame's try/filter/finally, `blk` into the scope, the stack check, the line for the backtrace.
+Slightly wider and as sound: the call followed only by things that speculate on nothing and read no local (a
+literal, `self`, an instance variable read whose slot is re-guarded).
+
+### Reach, counted before building
+
+From the census of 33818f7 + c0c3335 (`census.rb -l -a`, Src/StdLib and AWFY, 28,377 methods), the methods whose one
+and only screen refusal is a `MethodCall`, each def read with prism:
+
+| Where the refused call is | Methods |
+|---|---|
+| the body's last statement, the name nowhere else, and the body that one statement (a wrapper: `def a(x) = b(x)`) | 3,574 |
+| the last statement, after a prefix of 1 / 2 / 3 or more statements | 219 / 81 / 43 |
+| the last statement, but the same name called elsewhere in the body too | 142 |
+| followed only by a literal, self or a local or instance variable read | 96 |
+| not a statement of the body (inside a condition, an argument, a loop) | 5,736 |
+
+A wrapper's typed body would be the call and nothing else: what the generic light frame already is, a site and no
+scope (perf/jcall and perf/resume2 measured exactly that and found nothing). What could gain is the 343 with a typed
+prefix. Among AWFY's: Richards' `run_task` and DeltaBlue's `AbstractConstraint#add_constraint` (a prefix of self
+calls), `queue_packet` (its prefix writes `@queue_count` and then two attributes of another object: a deopt after an
+effect, declined by the slice before its call is reached), Havlak's `SimpleLoop#set_parent`, SOM's
+`Dictionary#resize`, `Queens#queens`, the harnesses' loops. And the ceiling, `Util/bench/jit-resume2-shapes.rb` by
+clock against CRuby 4.0 (`ab.rb -r 5`, load 1.6-2.2): `queue_packet` 1.00, `add_input` 0.99 - already level, nothing
+for any form of this to win - `schedule` 1.12 (a `while` whose body calls `t.step`: a call in a loop, which the slice
+does not take) and `find_task` 1.60 (an element read and `raise ... if t.nil?`: no general call at all).
+
+### So
+
+Not built. The tail slice is sound and wide on paper, but it is perf/jcall's shape with the frame cost gone, and its
+methods are either wrappers (nothing to gain) or ones already at CRuby's speed on the measured shapes; the time left
+in gap 1's shapes is in a loop of calls (`schedule`) and in a raise guard (`find_task`). What would move `schedule` is
+not a general call from a typed body but a call *into* a typed body: `t.step` on a receiver whose class the profile
+saw, entering the callee's typed body directly with unboxed arguments (`-X:JITCalls` for other receivers than self,
+the callee's own deopts absorbed at the boundary, stage 4), inside a loop the typed body owns - which needs stage 3's
+resume for the loop as soon as the callee is not known pure. That, or stage 3 itself, is the next step on this gap;
+another slice of stage 2 is not.
+
+## Stage 3, first step: resume at a top-level statement, sharing 3a's generic tail (round thirty-seven, design)
+
+Chosen over stage 4's narrow slice (a typed loop calling a pure typed callee) by what the JIT declines in AWFY
+(`IR_JIT_VERBOSE=1`, Richards, DeltaBlue, Havlak, CD, Json, Bounce, Towers, List on c0c3335): every hot method it
+turns away after the screen is turned away by the effect rule - Richards' `append`, `release` and `hold_self`
+("a deopt after an effect"), DeltaBlue's and Havlak's `Vector#remove_first`, Havlak's `split_bucket`, Json's
+`read_required_char`, and Json's `skip_white_space` ("a loop in a body that can deopt and has an effect"). None
+is a loop waiting for a call into a pure typed callee; Richards' `schedule` calls `run_task`, which is the
+benchmark's work and not pure.
+
+### The step
+
+A typed body may deopt after an effect when the failing operation stands in a **top-level statement** of the
+method body (or in the condition or body of a top-level `while`) and nothing observable happened in that
+statement before the guard. It then **resumes at the start of that statement** in generic code, with its frame
+state written into the scope, instead of restarting the body.
+
+- **Per-statement purity.** The compiler tracks `_pure` per top-level statement as it does per body now. A deopt
+ after an effect *within the same statement* still declines the body. For a top-level `while`, the statement is
+ re-entered at its head: sound only if the failing guard is in the condition or before the first effect of the
+ iteration (the OSR copy's rule), since the iterations already run left their effects and their locals.
+- **The generic suffix.** Statements `k..n` of the body, compiled by the AstGenerator exactly as the generic body
+ compiles them (the same sites, line markers, TraceLineExpressions, `return` as `gen.Return`), as a lambda over the
+ method's scope: `Func` (scope, self, block -> the method's value). Built the
+ first time statement `k` resumes, cached on the specialization, cold code. This is stage 3a's "generic tail"
+ (way 2) with a different start: 3a's tail is the suffix of a loop body after the yield, run for one iteration and
+ then handed back to the loop; this one is the suffix of the method body, run to the end. One compiler serves both:
+ `GenericSuffix.Compile(Statements list, int start, MethodDeclaration ast, bool endsIteration)`.
+- **The frame state.** The typed body throws `JitResumeException(k, object[] locals)` with its live typed locals
+ boxed through the representation funnel (`NarrowLong`, booleans as `true`/`false`, never-assigned as nil). The
+ entry, already wrapped in the light frame's try/filter/finally by stage 1 (`WrapResumeBody`), catches it,
+ makes the scope once (stage 1's `JitFrame.Scope`: `CreateMethodScopeLazy` with the generic body's
+ `MethodFrameShape`, which the generic compile records for the stub, and `blk`), stores the locals into its
+ tuple by the generic body's slot order, takes element writes made since statement `k` began back
+ (`JitUndoLog` gets a mark per top-level statement, not per entry), and calls the suffix. A scope already made
+ by a call in the typed body is that scope: by the rule of "Once the scope exists", the call that made it was the
+ typed body's last act, so the resume is right after it and the tuple is already authoritative.
+- **Exceptions, flow, frames.** The suffix runs inside the entry's light-frame try/filter/finally, so `return`
+ from a proc made there, LocalJumpError after the method returned and `ensure` are the generic body's. Its lambda
+ is named as the generic body's frame (`JitStub.Named`) and carries the line markers, so a backtrace from it shows
+ the method once, at its line. Tracing: the suffix has the generic hooks. Stack: the resume checks it, as
+ `CreateMethodScope` would.
+- **Accounting.** A resume counts as a deopt for retiring the specialization (`OnDeopt`), or a body that resumes
+ on every call stays in place and is slower than the generic one.
+
+### What it unlocks, and what it is worth alone
+
+`append` (its deopt is `mouse.link` in the condition of the top-level `while`, after `packet.link = NO_WORK` in
+statement 1: it resumes at the `while` head with `mouse` written back), `add_input_and_check_priority` and
+`release` (Richards), `remove_first` (DeltaBlue, Havlak), `read_required_char` (Json). Not `skip_white_space`: its
+effect and its deopt are in the same iteration (3a's handback or stage 5). By the ledger's profiles that is
+`append` 2.1% and `add_input_and_check_priority` 2.7% of Richards, `remove_first` under 1.4% of DeltaBlue; stage 1,
+the same kind of gain, measured 13-14% on its shape and nothing on a benchmark. Alone, this step does not pay for
+its code.
+
+### So: build it as 3a's second user, not first
+
+Stage 3a's yield loop has a measured target (`ueach100`: about 40 ns per element against CRuby's 28, about 23 for
+a typed copy) and needs the same suffix compiler for its way 2. Order:
+
+1. 3a step 1 (perf/iter's): Handback and MethodReturned in `OsrLoopSite`.
+2. `GenericSuffix` with 3a step 2 as its first user (the generic tail after the yield), gated by
+ `Util/yield-loop-matrix.rb` and measured on `Util/bench/yield-shapes.rb`.
+3. This step, as `GenericSuffix`'s second user, behind `-X:JITResume=3`, gated by the rows below, measured on
+ Richards and on a shape of `append`.
+
+### Its matrix rows (to add to `Util/jit-matrix.rb` section 11 with the step)
+
+| Row | Checks |
+|---|---|
+| `append` shape: effect in statement 1, receiver of another class in the loop's condition on iteration 1, 3, n | resume at the `while` head, the statement-1 write not repeated, `mouse` the loop's value |
+| deopt in statement k after effects in statements < k, with locals of each representation (Int, Lng past 2**31, Dbl, Bool, nil, never assigned) | the write-back funnel |
+| element write in statement k, then a deopt in statement k | the per-statement undo mark: the write taken back, the statement re-run once |
+| a call in statement j that makes the scope (`binding`), a deopt in statement j+1 | the scope's tuple is the state; `local_variable_set` from the callee is seen |
+| `ensure` around the body, `return` in the suffix, a proc made by `binding.eval("proc { return 7 }")` called after the resume and after the method returned | flow and the frame's try/filter/finally |
+| an exception in the suffix | the backtrace has the method once, at the suffix's line |
+| a TracePoint enabled by a call in statement j | `:line` for statements after j, `:return` once |
+| a deopt in statement k on every call | the specialization retires (`OnDeopt`) |
+| four threads, receivers of two classes | per-invocation state |
+
+## Stage 3a: a yield in an outlined loop (gap 18)
+
+**Built (round thirty-seven, perf/yieldloop, `IR_OSR_YIELD`, on by default), narrower and simpler than the plan
+below.** The shape is as designed (`WhileLoopExpression.GetYieldIndex`; in a method's own body, not a block's or an
+eval's). What changed in the building:
+
+- No Handback answer: `Retry` already means "go on at the head with the tuple as the copy left it". One new answer,
+ `OsrYieldOutcome`, covers ways 2 and 3: the copy writes its locals home and returns it, with the BlockParam when the
+ block jumped (way 3: the glue makes the generic post-yield test, `MethodYield`, which the light frame's rewriter makes
+ `LightMethodYield`, and returns from the method) or without one (way 2, or a deopt in the tail).
+- No separate suffix compiler: the generic loop transforms its tail statements a second time, in place, inside the
+ method's lambda (`MakeYieldHandBack`): the same scope, tuple layout, sites, line markers and hooks for free. That is
+ why the tail may hold no block, lambda, definition, loop, jump or exception handling (`YieldTailFinder`: their
+ transformation is not repeatable or leaves the tail). It also means the method-JIT resume of stage 3 does **not**
+ get its suffix from here: a method body has no generic loop around the resume point to hold a second copy, and still
+ needs B's dispatch or a suffix lambda.
+- Way 1: the tail is emitted typed; if it can deopt, the locals are taken right after the yield and a deopt in the
+ tail restores them and leaves with `RunTail`; a tail that deopts after an effect of its own declines the loop.
+- Way 4: the copy's body runs in a fault handler that writes its locals home.
+
+`Util/yield-loop-matrix.rb` warms every iterator up so that its rows run in the copies, and has two rows more (`big
+counter hot`, `int overflow hot`). `IR_OSR_VERBOSE=1` prints `yield-jumps` and `yield-tails`.
+
+Second round (perf/yieldloop2): the yield's value may be its statement's - `break unless yield(e)`, `break if
+yield(e)`, `v = yield(e)` (`WhileLoopExpression.YieldStatementKind`): the copy makes the rest (the test and the loop's
+break, the store to an object slot) itself, and the generic loop makes it on the outcome's value when it finishes the
+iteration. With `__ary_size__`, `__ary_at__(i)` (on a plain Array self) and `i.succ` in the copy, the prelude's
+`take_while` and `drop_while` run in their copies. Not `uniq` (calls in its tail) or `to_h` (`element = yield(element)
+if given`, and calls). Third round (perf/yieldloop3): `sum` with a block got an Integer loop of its own in front of its
+general one, which the copy runs with `C === x` (a constant module) and a bare `break` in the tail.
+
+Status: design, with its matrix (`Util/yield-loop-matrix.rb`, which CRuby and the unchanged build print
+alike). Written in round thirty-seven (perf/yieldresume) after perf/yieldloop measured the gap:
+`def each; i = 0; while i < @a.size; yield @a[i]; i += 1; end; self; end` costs about 40 ns per element
+yielding to an empty block, CRuby 28. Of that the yield itself is about 11 ns (CRuby's about 10), and the
+rest is the loop running generic, because the loop compiler bails at the YieldCall (`[osr] emitter: node:
+YieldCall`). A typed copy of the loop with the yield as a call in it would be about 23 ns.
+
+This is a narrower problem than stage 3, and the OSR tier is the place for it, not the method JIT:
+
+- The method JIT never wraps a method that uses its block (the screen), and a yielding iterator is the
+ whole point. The OSR copy of a loop runs **inside the generic body** (a light frame's or a full one):
+ that body is the method's frame - its backtrace line, its `ensure`, its flow-control frame, its lazily
+ made scope - and the copy is entered at the top of an iteration and leaves at the top of one.
+- The yield stays a call: the block runs its own compiled code, so its frame (`block in ...`), its
+ `next`/`redo`, its TracePoint `:b_call` and its backtraces are the generic ones. Nothing is inlined.
+- The copy already leaves only at an iteration boundary: a deopt restores the snapshot taken at the top of
+ the iteration and answers `Retry`, and the generic loop runs that iteration again. That is sound up to
+ the yield - nothing observable has happened in the iteration - and it is the stage-1 rule applied per
+ iteration. So the only new question is the **tail**: the statements of the iteration after the yield.
+
+### The shape
+
+`while C; S1 ... Sk; yield E1, ..., En; T1 ... Tm; end`, with exactly one yield, in statement position,
+directly in the loop body (not in an `if`, a `begin`, a nested loop or the condition), the arguments
+plain (no splat, no block pass), and `C`, the `S` and the `E` what the copy compiles today. Anything else
+keeps today's answer (the loop bails). The method's block and its yield BlockParam are new inputs of the
+copy: the block is read once on entry, as the generic yield reads it (`MakeMethodBlockParameterRead`:
+the light frame's block parameter, or the scope's); the BlockParam is the copy's local, reused across
+iterations by `ReuseBfcForYield` as the generic loop reuses it.
+
+### The four ways out of an iteration after the yield
+
+Each of them ends either at the **next** iteration boundary, with the end-of-iteration state in the
+tuple, or by leaving the method; none restarts the iteration.
+
+1. **Normal.** Right after the yield the copy tests one guard, G: the global method version and the
+ constant version are the ones its prologue checked, `TracePoint.ActiveEvents` is 0, and the yield did
+ not break (`MethodYield`'s test). With G, the tail runs typed. A tail operation that would deopt
+ today must not: `i += 1` on an Int or Lng local that overflows has, with G (Integer#+ is still the
+ library's), a known result, the Bignum, which `JitRuntime` makes without calling Ruby; the local then
+ holds an `Obj` for the rest of the iteration. An operation whose guard fails for another reason
+ (an `Array#[]` on a receiver whose class moved, an attribute read) takes the same path: its result is
+ computed by its generic operation on the operands already evaluated, as stage 1's fallbacks are, and
+ is `Obj` from there. Once a tail operation has gone `Obj`, every later tail operation is emitted on
+ `Obj` (the self-guarded tail: stage 2's rule, applied to a tail only), and at the end of the iteration
+ the copy writes its locals into the tuple and answers **Handback**: a new answer of the site (next to
+ `Retry`) that the generic loop takes as "continue at the head, evaluating `C` yourself", the snapshot
+ not restored. A tail that went typed to the end goes on to the next iteration in the copy.
+2. **The world changed, or tracing came on** (G fails). The block may have redefined `Integer#+`
+ (`redefine +` in the matrix: CRuby calls the new `+` for the very `i += 1` that follows), reassigned
+ a constant, or enabled a TracePoint whose `:line` for `i += 1`, with a binding that sees `i`, CRuby
+ fires (`trace line`, `trace binding`). Neither can be had from typed code. The copy writes its locals
+ into the tuple and runs the **generic tail**: `T1 ... Tm` compiled by the AstGenerator exactly as the
+ generic body compiles them (the same sites, the same TraceLineExpressions), as a lambda over the
+ method's scope, built the first time it is needed and cached on the site (cold code). In a light frame
+ the scope is made as a TracePoint would make it (`LightFrame.MakeScopeIfTraced`), which needs the
+ frame's `#rfc`, self and block as copy inputs too, and is then the frame's for the rest of the call
+ (the light frame's `#scope` variable, so that the generic loop that follows uses the same one). Then
+ Handback. This is stage 3's resumable body for one resume point - after the yield - and without its
+ dispatch problem: the tail is a straight-line suffix of the loop body, inside no try region the
+ generic body would have to jump into, which is why the shape takes the yield only directly in the
+ loop body.
+3. **Break.** The block's `break v` makes the iterator return `v` (`MethodYield` answers true and the
+ generic yield returns from the method). The copy writes its locals into the tuple and answers
+ **MethodReturned(v)**, a new answer the generic loop's glue (`WhileLoopExpression`, the `osrResult`
+ test) turns into the method's own `return v` (`gen.Return`), so the method's `ensure`, the light
+ frame's finally and TracePoint's `:return` run as they do for the generic yield (`break ensure`).
+ `next` and `redo` are the block's own and need nothing.
+4. **An exception through the yield.** A `raise` or `throw` in the block, a `return` from it (a
+ MethodUnwinder aimed at the caller), Thread#raise or #kill: the copy's locals are written into the
+ tuple on the way out (a fault handler around the yield, or a finally keyed on a flag), so a `rescue`
+ or `ensure` of the method sees the loop's own counter (`raise rescue`: `["at 42", 41]`).
+
+Everything before the yield is as today: a deopt in `C`, the `S` or the `E` restores the snapshot and
+the iteration runs again generically, since nothing observable has happened in it. A redefinition by
+the block is seen by the next iteration's `C` through the prologue's version check moved to the
+iteration's safe point (it is there already: the copy's safe point checks the code epoch).
+
+### What else the state must hold
+
+- **Representation in the tuple.** A local that went `Obj` in the tail is written as the object; a typed
+ one through the representation funnel (`NarrowLong`), as the copy's exits do now.
+- **Threads and re-entrancy.** All of it is per invocation: the block, the BlockParam, the locals are
+ locals of the copy's delegate. The generic tail lambda is shared and stateless. A re-entrant call of the
+ iterator from the block (`re-entrant`, `recursion`) runs its own generic body and its own copy.
+- **The undo log.** The copy logs no element writes of its own in this shape; a tail with an element
+ write (`r << yield(x)` is a call, not a write) is declined until it is needed.
+- **The yield's arity and protocol.** `Yield0` ... `YieldN` by the argument count, as the generic yield
+ chooses; the yield's value is `Obj`.
+
+### The matrix's rows (`Util/yield-loop-matrix.rb`) and what each one checks
+
+| Rows | Checks |
+|---|---|
+| `hot`, `sizes`, `returns self`, `enumerator`, `each2` | the typed copy with a yield computes what the generic loop does, empty to 100 elements, two yielded values |
+| `break`, `break ensure`, `break each2`, `throw` | way 3: the block's break value is the method's, its `ensure` sees the loop's counter; a throw leaves through way 4 |
+| `next`, `redo`, `symbol`, `lambda`, `method`, `kept block` | the block's own protocol and the forms a block comes in, untouched by the copy |
+| `raise rescue`, `raise ensure`, `raise outside` | way 4: the counter is written back before a rescue or ensure of the method reads it |
+| `redefine +`, `redefine []` | way 2: the tail's `i += 1` calls the `+` the block defined, in the same iteration; the next `@a[i]` the `[]` |
+| `trace line`, `trace binding` | way 2: `:line` for the tail's statement, in the iteration that enabled it, with a binding that sees `i` |
+| `grow`, `shrink`, `freeze`, `ivar swap` | the next iteration's condition and element read see what the block did to the array or to `@a` (a deopt there replays nothing) |
+| `re-entrant`, `recursion`, `fiber`, `threads` | per-invocation state: the copy's block, BlockParam and locals are its own |
+| `big counter` | way 1: an `i += 2**61` past Int64 in the tail is the Bignum, handed back at the end of the iteration |
+
+### Order of work, each step gated by the matrix
+
+1. The two answers, Handback and MethodReturned, in `OsrLoopSite` and the glue, with a C# test that a
+ copy can hand back after a typed tail and that `MethodReturned` runs the method's ensure.
+2. The yield in the copy, with ways 2, 3 and 4: the block and BlockParam inputs, `Yield0`-`YieldN`, the
+ write-back on an exception, MethodReturned on a break, and the generic tail lambda run whenever G
+ fails. With G the tail runs typed only if it cannot fail - in this step a tail of `local += literal` on
+ Int/Lng locals, whose overflow makes the Bignum (way 1's first case) and hands back at the end of the
+ iteration - and any other tail always runs generic. No step may hand back *before* the tail: the
+ generic loop starts at the head, so a tail skipped there is a statement lost (`i += 1` never run), and
+ a tail run without its hooks is a `:line` lost (`trace line`, `trace binding`).
+3. The typed tail with its `Obj` continuation (way 1) for tails of more than local increments.
+
+Each step's rows: `Util/yield-loop-matrix.rb` in every mode and with the switch off; block-loop, osr,
+jit, jit-calls, parked-iterator and hot-shapes matrices; ruby/spec language/yield, break, while;
+`IR_OSR_VERBOSE=1` showing the iterator's loop specialized (the probe reaches the path). The measure is
+`Util/bench/yield-shapes.rb` (`ueach100`, `ueach100e` against CRuby) and the prelude's `take_while`,
+`sum`, `uniq` and `to_h` with a block, by clock.
diff --git a/Docs/light-frame-literal-blocks.md b/Docs/light-frame-literal-blocks.md
new file mode 100644
index 000000000..d54fb96f9
--- /dev/null
+++ b/Docs/light-frame-literal-blocks.md
@@ -0,0 +1,177 @@
+# A literal block in a light frame: what it costs, and a Proc without a method scope
+
+Status: measured and designed in round thirty-seven (perf/lazyproc); change A built in perf/literalsite
+(`IR_LIGHT_LITERAL_CALLS`, on), which also attributed the cost - see "What A measured" below. B was
+prototyped in perf/procscope and rejected by its measurement - see "What B's prototype measured". It is the remainder of
+gap 13 of `Util/perf/LEDGER.md` (the fixed cost of calling an iterator) and a case of gap 16 (a light
+frame that ends up making its scope).
+
+## What it costs
+
+`Util/bench/iter-shapes.rb`, ns per call of a light method, the callee `def nb; 1; end` ignoring its
+block, alternating rounds against CRuby 4.0 (round thirty-seven, this host):
+
+| shape | IronRuby | CRuby | what it is |
+|---|---|---|---|
+| `nb0`: `nb` | 39-43 | 32-36 | a light frame calling a light frame |
+| `nbp`: `nb(&P)` | 52-62 | 36-44 | a stored Proc passed on through the light site (`LightBlockPassEnabled`) |
+| `nby`: `return nb if a; nb { }` | 56 | 36 | a body with a literal; the hot path calls without a block |
+| `nbx`: `return nb(&P) if a; nb { }` | 108 | 48 | the same, the hot path passing a stored Proc |
+| `nbl`: `nb { }` | 116-123 | 35-40 | the literal itself |
+| `eachp` / `eachl`: `a.each(&P)` / `a.each { }` | 84 / 120 | 68 / 64 | the same through Array#each |
+
+So the literal's ~60 ns over a stored Proc is in two parts:
+
+- **About 15 ns is the Proc** (`nbl` against `nbx`): made, or made again from the parked scope
+ (`InstantiateParkedBlock`), and converted by the callee.
+- **About 45 ns is the call with a block in a body that has a literal** (`nbx` against `nbp`): the same
+ `nb(&P)` costs 108 in such a body and 62 in one without. In a light body with literal blocks
+ (`LightFrameRewriter.BlockLiterals`) a call with a block does not take the light site
+ (`blockPass = ... && !BlockLiterals`): it goes through the full site with the scope made on demand
+ (`light.LazyScope`: `TakeParkedScope` + `ReuseParkedScopeLazy`, or `CreateMethodScopeLazy`), and the
+ method then leaves through `LeaveLightMethodFrameSlow` and parks (`BeginPark`/`EndPark`). A call without
+ a block in the same body keeps the light site and costs 56 (`nby`).
+
+How the 45 ns divides between the scope, the parking around it, the frame's exit with a scope and the
+full site is **not measured**: Linux perf cannot run where this was done, and callgrind could not name the
+JIT's code. The pieces read cheap (the scope's constructor is a dozen field writes; publishing the parked
+scope with a release write instead of a compare-exchange moved nothing, perf/iter3; allocating instead of
+parking, `IR_PARKED_SCOPES=0`, costs the same). The first job of an attempt is that attribution - a
+profile on a host with perf, or the sequence the body emits timed piece by piece in C# - because it
+decides which of the two steps below is worth building.
+
+## What A measured (perf/literalsite)
+
+Built as designed below, for bodies whose literals are all of the narrow shape
+(`MethodDefinition.HasOnlyNarrowLiterals`), alternating rounds against the switch off and CRuby:
+
+| shape | switch off | A | CRuby |
+|---|---|---|---|
+| `nbx`: `return nb(&P) if a; nb { }` | 100 | 56 | 44 |
+| `nbp`: `nb(&P)` (no literal) | 56 | 56 | 40 |
+| `nbl`: `nb { }` | 118 | 114 (overlapping) | 36 |
+| `eachl`, `each1`, `times1`, `map1` | 138, 159, 164, 167 | 140, 162, 157, 172 (overlapping) | 68, 79, 93, 111 |
+
+So **the full site costs about nothing**: where the literal runs, its Proc makes the scope anyway and A
+changes nothing (`nbl`); where it does not, A takes the whole 45 ns (`nbx` falls to `nbp`), because the call
+no longer makes the scope (208 -> 24 bytes a call with parking off). The 45 ns is the scope being made and
+published: the object, `LeaveLightMethodFrameSlow`, the parking around it. That is B's ground, and B is
+what the literal's own cost (`nbl`, `each1`) needs.
+
+## What B's prototype measured (perf/procscope)
+
+A prototype of B, for timing only (`IR_PROC_SCOPE=1`, not kept): a narrow literal's Proc made over a scope
+held in `#proc-scope`, made by the same code as the frame's scope on demand but never published as the
+frame's (`#scope` stays null, so the frame leaves through the inlined fast path and does not park; the
+frame's own scope on demand takes `#proc-scope` if it exists). Six alternating rounds, ns per call:
+
+| shape | off | prototype | CRuby |
+|---|---|---|---|
+| `nbl`: `nb { }` (the callee ignores the block) | 120 | 120 | 40 |
+| `nyl`: `ny { 1 }` (the callee yields) | 164 | 169 | 54 |
+| `eachl`: `a.each { }` | 148 | 160 (1.08) | 70 |
+| `map1`: `a.map { \|x\| x + 1 }` | 193 | 198 | 117 |
+
+**Publishing costs nothing measurable** (`nbl`, where neither arm parks: 120 and 120), and where the scope
+is parked today the unpublished one cannot be, so it is allocated on every call and is slower (`eachl`).
+With A's result: neither the full site nor the publication is the literal's cost. It is the scope object
+and the Proc themselves - made, or taken parked and made again, which cost the same (`IR_PARKED_SCOPES=0`
+leaves every shape's time as it is) - and, for a callee that yields, the conversion and the yield
+(`nyl` 164 against CRuby's 54). What would take it is no heap scope and no heap Proc for a literal that
+does not escape: a block passed as the frame's locals and code, as CRuby passes a block (a pointer to the
+caller's frame), with the scope and Proc made when something asks for them - the TruffleRuby way, which in
+IronRuby means a block calling convention that is not a Proc. That is a project, not a step.
+
+A finding on the side: **parking never works for a literal given to a method that ignores its block**
+(`def nb; 1; end; nb { }`: 288 bytes a call with parking on, against 48 for `ny { }`, which yields). Such a
+callee never converts the block, as far as the bytes show, so its Proc is not marked reusable and staging
+fails on every call (not traced further). The shape is rare in real code; noted for whoever next touches
+the parking.
+
+## How a literal reaches its method today
+
+- **The method's locals.** A light body's locals are in the tuple the scope made on demand wraps
+ (`scope.LocalsTupleVariable`) whenever a block reads them through that scope; a body that can keep them in
+ CLR registers (`ScopeBuilder.TryUseRegisterLocals`) materializes the tuple when the scope is made
+ (`MaterializeLocals`). Which of the two a body with a literal of the narrow shape gets is to be read from
+ `TransformLightFrame` before B is built: B needs the tuple to be the frame's own storage. A block reaches an enclosing local through its Proc:
+ `Proc.LocalScope` is the method's scope, and the block's lambda takes the parent tuples from it
+ (`BlockDefinition`: `CreateScopeWithParent(..., bfc.Proc.LocalScope, ...)`, and the closure variables
+ `#closure` of `ScopeBuilder`). A scope-free block body (`IsLightCallBody`) runs without a scope of its
+ own and reads the enclosing locals from the same parent.
+- **The literal's Proc** is `new Proc(ProcKind.Block, self, scope, dispatcher)` with `scope` the method's
+ scope (`InstantiateBlock`/`InstantiateReusableBlock`/`InstantiateParkedBlock` all take
+ `gen.CurrentScopeVariable`, which the rewriter turns into `light.LazyScope`): the literal forces the
+ scope whether or not its body reads anything of it.
+- **Callees.** A call from a light frame without a literal block goes through a site flagged
+ `HasLightScope`, given the declaring scope; a rule that needs the caller's scope answers
+ `RubyOps.LightScopeRequired`, and the frame makes its scope and calls again through the full site
+ (`LightFrameRewriter.LightScopeCall`). In a body with literals, calls with a block are left on the full
+ site, so the literal forces the scope a second time over, at the call.
+
+## What needs a real method scope behind a literal's Proc
+
+Everything that reads `Proc.LocalScope`, or reaches the method's frame through it:
+
+| use | how it reaches the scope | detectable |
+|---|---|---|
+| the block reads or writes an enclosing local | the parent tuples from `Proc.LocalScope` | at compile time (the block's outer variables, `BlockDispatcher.OuterVariableNames`) |
+| `return` in the block | the MethodUnwinder's target is the method's frame | at compile time |
+| `binding`, `eval`, `local_variables`, `__method__` in the block, a nested literal | the block's scope, made with the method's as its parent | written in the block: at compile time; through `send`, `method`, `instance_exec`: only at run time, as LightScopeRequired from the block's own call sites |
+| `$~`, `$_` set or read by the block or a method it calls | `GetInnerMostClosureScope` walks from the block's scope to the method's | at run time (a callee that takes the scope answers LightScopeRequired) |
+| a TracePoint `:b_call`/`:line` in the block | the block's scope made for the hook, its parent the method's; `binding.local_variables` lists the method's locals | at run time (`TracePoint.ActiveEvents`) |
+| the Proc escapes: the callee names it (`&b`, `Proc.new`, `define_method`), keeps it, calls `#binding` on it | the Proc object outlives the call and carries `LocalScope` | at run time: the callee's conversion (`ConvertAsMethodFrame`, not `ConvertAsLightFrame`/[BlockNotKept]) |
+| `break` from the block | the Proc's converter (the callee's frame), and `LocalScope.IsEmpty` in `BlockParam.Break` | at run time, but needs only something non-empty |
+| constants and `def` in the block | the lexical chain from `Proc.LocalScope`, which passes through the method's scope to the declaring scope | the declaring scope gives the same lexical answers |
+
+## The design
+
+The narrowest shape that can be sound: a literal whose body **reads and writes no enclosing local, has no
+`return`, no nested literal, and none of `binding`, `eval`, `local_variables`, `__method__` written in it**,
+in a light body whose literals are all of that kind (`nb { }`, `a.each { |x| f(x) }`). Its Proc needs the
+method's scope for nothing it does itself; only the run-time reaches of the table remain. Two changes
+follow from the numbers, each worth building only if the attribution says so:
+
+**A. The call with such a literal through the light site.** In a body with literals, a call with a block
+takes the full site with the scope made on demand (`blockPass = ... && !BlockLiterals`). For a literal of
+the narrow shape the call needs the caller's scope no more than `nb(&P)` does: it can take the
+`HasLightScope` site, with LightScopeRequired (then the full site with the scope, as today) when its rule
+reads the caller's scope. What it saves is the full site's share of the 45 ns; on its own it still makes
+the scope, because the Proc does.
+
+**B. The Proc's scope made, but not as the frame's.** The light frame makes the scope object the Proc
+needs (a dozen field writes) without making it the frame's published scope: `#scope` stays null, so the
+frame leaves through the inlined `LeaveLightMethodFrame` fast path, does not park, and its own calls keep
+the light site. The Proc holds a complete method scope (the frame's tuple, self, block, rfc, declaring
+scope and module), so every run-time reach of the table finds a real scope: a block that calls `binding`
+through `send` gets a block scope whose parent is it; `$~` set by a callee lands in it; a Proc kept by the
+callee and asked for `#binding` after the method returned sees the method's locals, because the tuple is
+the frame's own. Two things change against today and are what its matrix must pin:
+
+- **One scope per invocation.** If the frame later needs a scope of its own (a call that answered
+ LightScopeRequired, `__method__`, a TracePoint), it must take the one the Proc holds, not make a second:
+ `$~` set in the block and read by the method after, `local_variable_set` through one binding and read
+ through the other. So the frame keeps the made scope in a variable of its own (`#proc-scope`), and
+ `light.LazyScope` becomes `#scope ?? (#scope = #proc-scope ?? make())`, publishing it then.
+- **Leaving.** A scope the frame never published still had a Proc over it, which a callee may have kept:
+ its flow-control frame must say the method is gone (`LeaveMethod`) when the method returns, so that a
+ `break` or a `binding.eval("return")` through it after that raises LocalJumpError as today. That is the
+ slow path of `LeaveLightMethodFrame`; B keeps it only when `#proc-scope` is non-null and the Proc is no
+ longer reusable (it escaped), and otherwise resets the scope for the next call as parking does.
+
+**Which first.** If the 45 ns is mostly the full site, A alone takes it. If it is mostly the scope's
+publication (the frame's exit with a scope, the parking around it), B takes it and A adds the rest. If it
+is the object itself, neither does much, and the literal's cost is what a heap Proc over a heap scope is
+in .NET: CRuby's literal is a stack frame field, and only escape analysis of the kind TruffleRuby does
+would remove it.
+
+## The matrix it needs first
+
+`Util/literal-block-light-matrix.rb`, before any code, printing CRuby's output on the unchanged build:
+the narrow literal passed to a light Ruby method, Array#each and Integer#times, called hot; the callee
+naming the block (`&b`) and keeping it, calling `b.binding.local_variables` after the method returned, and
+`define_method(:x, &b)`; the block calling `binding` and `local_variables` through `send`; the block
+calling `"a" =~ /a/` through `send` and the method reading `$~` after; a TracePoint `:b_call` reading
+`binding.local_variables` in the block; `break` with a value and the method's `ensure`; an exception
+through the block; a re-entrant call of the method from its block; four threads; `IR_LIGHT_BLOCKS=0`,
+`IR_PARKED_SCOPES=0` and the change's switch.
diff --git a/Docs/rescue-above-ensure.md b/Docs/rescue-above-ensure.md
new file mode 100644
index 000000000..36ae8e77d
--- /dev/null
+++ b/Docs/rescue-above-ensure.md
@@ -0,0 +1,122 @@
+# A rescue above a passed ensure: design, and why stage 2 was not built
+
+A `rescue` whose clauses do not match costs nothing extra when its class list can be decided in
+the CLR's first pass: the filter `RescuePassUnwinder || RescuePassMayTest && CannotMatch...`
+(`Body.TransformExceptionHandling`, `RubyOps`) lets the exception go through without a catch. It
+cannot when the exception has already gone through a compiled ensure clause that has not run yet
+(`RubyExceptionData.PendingPassedEnsures`): the frame catches the exception, completes its
+backtrace, matches the clauses, and throws it again. The first such frame above an ensure costs
+about 20 us, each further one about 3; CRuby about 1 (`Util/bench/rescue-above-ensure-shapes.rb`).
+`Timeout.timeout`'s raise has this shape (`Error.handle_timeout`'s rescue above the Proc's
+`ensure request.finished`) and pays 40 of its 63-76 us for it.
+
+This note asks whether the pending ensure clauses could be run from the filter itself - in the
+first pass, before the class list is looked at, which is the order Ruby wants - and the second
+pass made to skip them. The answer is no, for reasons that are about the CLR's model, not about
+the work: stage 2 was not built. The matrix rows are in `Util/raise-matrix.rb` ("a rescue above
+a passed ensure") and print CRuby's output on the unchanged build.
+
+## What exists
+
+- **`EnsureGuardExpression`** guards the statements of a body that has an ensure clause and no
+ rescue clause. Compiled, it is a try with a filter, `RubyOps.PassEnsure`, and a fault block,
+ `RubyOps.EnterPassedEnsure`, inside the try/finally whose finally is the ensure clause.
+- **`PassEnsure`** (first pass) lets the exception through when catching it would only have
+ taken note of it: the exception is marked handled, gets `$!` as its cause, and
+ `PendingPassedEnsures` is counted up. It refuses (the frame catches) for a stack overflow, a
+ stack more than `PassEnsureMaxDepth` compiled frames deep, or less than `PassEnsureStackRoom`
+ (512 KB) of stack left - room for the ensure clause, which in the second pass runs *on top of
+ the raise*: CoreCLR runs a finally funclet with the frames between the throw and the catch
+ still on the stack.
+- **`EnterPassedEnsure`** (second pass, the fault block) sets `$!` for the clause, counts
+ `PendingPassedEnsures` down, and hands the frame's part of the backtrace to the exception
+ (`RubyExceptionData.EnterPassedEnsure`), so that a backtrace taken later still has the frame.
+- **`RescuePassMayTest`** refuses while `PendingPassedEnsures` is not zero: the clauses of the
+ pending ensures will run Ruby code before Ruby would match this frame's class list.
+
+So "a clause run on top of the raise" already exists, and it is the CLR's second pass doing it in
+its own order. What stage 2 needed is something else: the clause run during the *first* pass.
+
+## What stage 2 would have been
+
+The rescue frame's filter, finding `PendingPassedEnsures > 0`, would run each pending clause
+itself, innermost first, then evaluate the class list as now, and mark the clauses as run so that
+their finally blocks do nothing when the second pass reaches them (a flag on the exception's data
+per pending clause, read by the clause's guard). The point was to keep this frame from catching
+when nothing matches.
+
+## Why it is not sound
+
+1. **CLR finally blocks between the raise and the ensure run in the second pass, and Ruby wants
+ them first.** A clause of an outer frame runs, in Ruby, after everything inside it has been
+ cleaned up. Inside it there are C# `finally` blocks of library methods - `Mutex#synchronize`
+ unlocks in one (`RubyMutex.cs`), `File.open` with a block closes the file in one - the DLR's own
+ finally blocks (a Ruby frame restoring `$!`, popping its frame record), and the light frames'
+ bookkeeping. Run from a first-pass filter, the ensure clause would run before all of them.
+ `Util/raise-matrix.rb` "pe: a Mutex unlocked before the outer ensure" prints
+ `[[:locked, false]]` on CRuby and on IronRuby today; the early clause would see `true`, and
+ one that locked the mutex again would raise "deadlock; recursive locking". "pe: a File closed
+ before the outer ensure" is the same with `closed?`. Running those CLR blocks early too is not
+ possible: a filter cannot run another frame's finally, and the second pass runs it regardless.
+ Knowing that no such block lies between - no C# frame with a finally, no Ruby frame with
+ bookkeeping - would make the case too rare to matter: every Ruby frame has one.
+
+2. **The clause cannot be called from outside its frame.** A compiled ensure clause is code of its
+ frame's method, reading the frame's locals; a light frame keeps them in CLR locals, which no
+ other code can reach. Running it from an outer frame's filter needs it compiled as a closure
+ over a heap environment, for every ensure clause, raise or not - a cost on the path that does
+ not raise, to make the path that raises and does not match cheaper.
+
+3. **What the clause does may not stay inside a filter.** The CLR runs a filter and takes any
+ exception leaving it as "false"; a filter cannot transfer control.
+ - **The clause raises** ("pe: the ensure raises": the new exception replaces the old, with the
+ old as its cause). From the filter, the new exception would have to propagate from the
+ clause's frame, through the frames between it and this one, whose filters have already
+ answered for the old exception. There is no way to restart the first pass at an inner frame
+ with another exception.
+ - **The clause jumps** - `return` ("pe: return from the ensure": `:returned`), `break`, `next`,
+ `throw` (each its row), or `retry` of a rescue between. Each ends the exception and moves
+ control to a point inside the frames the first pass is walking. A filter can only return.
+ - **Thread#raise or Thread#kill while the clause runs** ("pe: Thread#raise during the ensure",
+ "pe: Thread#kill during the ensure"): delivered at a safe point inside the clause, the
+ exception would be thrown inside the filter and swallowed by the CLR; parking it again
+ would deliver it at the wrong place (after the old exception's handling) or lose it.
+ Each of these could make the filter say "catch" for the rest of the dispatch, but by then the
+ clause has run once, and the second pass would run it again (or skip it, and the effect of the
+ jump would be lost).
+
+4. **`$!`, `cause` and the backtrace** would be the smaller problem: `$!` in the clause is the
+ propagating exception (set as `EnterPassedEnsure` sets it), `cause` is decided by `PassEnsure`
+ already, and the backtrace part the clause's frame hands over could be handed over from the
+ filter as well. They do not rescue the design from 1-3.
+
+## What the second pass would have had to skip, and how
+
+Each pending clause run from a filter: the guard's finally would test a per-clause "already run"
+mark on the exception's data (the frame's record index, which `EnterPassedEnsure` already has) and
+do nothing - `$!` restore, the clause - while the frame's own bookkeeping still ran. This part is
+easy; it is the order of everything else that is not.
+
+## What would be sound, and what it would win
+
+- **Cheaper catches**, not fewer: the first catch above a passed ensure completes the backtrace
+ the ensure began (`TakePassedEnsureCapture`, `CaptureExceptionTrace`) and throws again. Making
+ the throw again a `ExceptionDispatchInfo.Throw` of a captured dispatch, and the capture lazier,
+ would lower the 20 us without changing any order. That is ordinary profiling work, and needs a
+ sampler this environment does not have (`perf_event_open` is refused).
+- **Fewer rescue frames on the path**: for `Timeout`, `handle_timeout`'s rescue exists to turn its
+ own `ExitException` into `Timeout::Error`. An IronRuby override could test `exc.equal?(e)` in a
+ way that does not need the rescue - it cannot: the rescue is how it learns that the exception
+ passed through. Left as it is.
+
+## Rows
+
+`Util/raise-matrix.rb`, section "a rescue above a passed ensure", seventeen rows: the ensure before
+the class list (a class list that is a method call), a non-matching rescue with the ensure run
+once, the constant of the class list reassigned in the ensure, `===` defined in it, the exception
+extended with a module of the class list in it, `$!` in the ensure and after, the ensure raising
+(cause), `return`, `break`, `next` and `throw` from the ensure, `retry` above it, a Mutex and a
+File cleaned up before the outer ensure, the backtrace keeping the inner frame, and Thread#raise
+and Thread#kill while the ensure runs. CRuby's output on the unchanged build with the JIT on,
+`-X:NoJIT -X:NoOSR`, `-X:NoJITCalls` and `IR_LIGHT_FRAMES=0` (the matrix's one row that prints an
+anonymous class's address differs from run to run, as before).
diff --git a/Src/InitializerGenerator/LibraryDef.cs b/Src/InitializerGenerator/LibraryDef.cs
index 5cefe2418..b90bed206 100644
--- a/Src/InitializerGenerator/LibraryDef.cs
+++ b/Src/InitializerGenerator/LibraryDef.cs
@@ -142,6 +142,9 @@ private sealed class ModuleDef {
public ModuleKind Kind;
public bool HasCopyInclusions;
+ // RubyModuleAttribute.Name was given (not only Extends):
+ public bool HasExplicitName;
+
public TypeRef Super; // non-null for all classes except for object
// Non-null for modules nested in other Ruby modules.
@@ -415,6 +418,7 @@ public void ReflectTypes(IReadOnlyList allTypes) {
}
def.Trait = trait;
+ def.HasExplicitName = module.Name != null;
def.Extends = module.Extends ?? trait;
def.DefineIn = module.DefineIn;
@@ -997,6 +1001,26 @@ private string FormatSignature(IMethodSymbol method) {
#region Code Generation
+ ///
+ /// An assembly attribute for each module a class with a Ruby name of its own copies in: what
+ /// RubyStackTraceBuilder.GetCopyingClassName read from the attributes of every type of the assembly before.
+ ///
+ public void GenerateCopiedModuleAttributes(IndentedWriter output) {
+ var worklist = new List(_moduleDefs.Values);
+ worklist.Sort(CompareNames);
+ foreach (ModuleDef def in worklist) {
+ if (!def.HasExplicitName) {
+ continue;
+ }
+ foreach (MixinRef mixin in def.Mixins) {
+ if (mixin.Copy) {
+ output.WriteLine("[assembly: {0}(typeof({1}), typeof({2}))]", "IronRuby.Runtime.RubyCopiedModuleAttribute",
+ _known.TypeName(mixin.Module.Type), _known.TypeName(def.Trait));
+ }
+ }
+ }
+ }
+
public void GenerateCode(IndentedWriter output) {
_output = output;
diff --git a/Src/InitializerGenerator/LibraryInitializerGenerator.cs b/Src/InitializerGenerator/LibraryInitializerGenerator.cs
index bf1524343..ade47958d 100644
--- a/Src/InitializerGenerator/LibraryInitializerGenerator.cs
+++ b/Src/InitializerGenerator/LibraryInitializerGenerator.cs
@@ -116,6 +116,9 @@ internal static string Generate(Compilation compilation, Action repo
foreach (LibraryDef library in libraries) {
output.WriteLine("[assembly: {2}(typeof({0}.{1}))]", library.Namespace, library.InitializerName, "IronRuby.Runtime.RubyLibraryAttribute");
}
+ foreach (LibraryDef library in libraries) {
+ library.GenerateCopiedModuleAttributes(output);
+ }
output.WriteLine();
diff --git a/Src/IronRuby.Tests/Driver.cs b/Src/IronRuby.Tests/Driver.cs
index 2bf6839e1..ccceea7dc 100644
--- a/Src/IronRuby.Tests/Driver.cs
+++ b/Src/IronRuby.Tests/Driver.cs
@@ -167,6 +167,11 @@ bool Take(params string[] names) {
}
public static void Main(string[]/*!*/ arguments) {
+ // not a test: the block-cost harness of Docs/block-calling-convention.md, stage 0 (Perf/BlockCostHarness.cs)
+ if (arguments.Length > 0 && arguments[0] == "/blockcost") {
+ IronRuby.Tests.Perf.BlockCostHarness.Run(arguments);
+ return;
+ }
string culture = Environment.GetEnvironmentVariable("IR_CULTURE");
if (!String.IsNullOrEmpty(culture)) {
Thread.CurrentThread.CurrentCulture = new CultureInfo(culture, false);
diff --git a/Src/IronRuby.Tests/Perf/BlockCostHarness.cs b/Src/IronRuby.Tests/Perf/BlockCostHarness.cs
new file mode 100644
index 000000000..17577c900
--- /dev/null
+++ b/Src/IronRuby.Tests/Perf/BlockCostHarness.cs
@@ -0,0 +1,461 @@
+/* ****************************************************************************
+ *
+ * Stage 0 of Docs/block-calling-convention.md: where the time of a call with a literal block goes.
+ *
+ * dotnet build Src/IronRuby.Tests/IronRuby.Tests.csproj -c Release -p:IronRubyTargetFrameworks=net10.0
+ * Src/IronRuby.Tests/bin/Release/net10.0/IronRuby.Tests /blockcost [N]
+ *
+ * Not a test: the driver runs it only for /blockcost (Driver.Main), never in the suite. It hosts a runtime, takes
+ * real objects from Ruby code (a literal's block dispatcher, compiled; a method scope; the declaring scope and
+ * module), and times the runtime calls the compiled code of `def nyl(a) = ny { 1 }' and `def e1(a); a.each { |x| };
+ * 1; end' makes per call - each step alone in a loop, then the steps together - with a Stopwatch over N iterations
+ * after a warm-up, best of five. Then the same calls end to end, through Ruby, for the sum to be compared with.
+ *
+ * What it cannot time: the call sites and the light frames' prologues and epilogues themselves (compiled Ruby code,
+ * not runtime calls): those are what end to end minus the steps leaves, against the same end to end of a call
+ * without a block (nb0).
+ *
+ * ***************************************************************************/
+
+using System;
+using System.Diagnostics;
+using IronRuby.Builtins;
+using IronRuby.Runtime;
+using IronRuby.Runtime.Calls;
+using Microsoft.Scripting;
+using Microsoft.Scripting.Hosting;
+
+namespace IronRuby.Tests.Perf {
+ internal static class BlockCostHarness {
+ internal static long ProtoNew;
+ private const string Source = @"
+PE = proc { |x| }
+PY = proc { 1 }
+class BcO
+ def nb; 1; end
+ def ny; yield; end
+ def nb0(a) = nb
+ def nyl(a) = ny { 1 }
+ def e1(a); a.each { |x| }; 1; end
+ def e0(a); 1; end
+ def ep(a); a.each(&PE); 1; end
+ def ept(a); return a.each { |y| } unless a; a.each(&PE); 1; end
+ def nyp(a) = ny(&PY)
+ def grab(&b) = b
+ def lit1 = grab { 1 }
+ def litx = grab { |x| }
+ def sc(a) = binding
+end
+def bc_run_nb0(o, a, n); i = 0; while i < n; o.nb0(a); i += 1; end; end
+def bc_run_nyl(o, a, n); i = 0; while i < n; o.nyl(a); i += 1; end; end
+def bc_run_e1(o, a, n); i = 0; while i < n; o.e1(a); i += 1; end; end
+def bc_run_e0(o, a, n); i = 0; while i < n; o.e0(a); i += 1; end; end
+def bc_run_ep(o, a, n); i = 0; while i < n; o.ep(a); i += 1; end; end
+def bc_run_ept(o, a, n); i = 0; while i < n; o.ept(a); i += 1; end; end
+def bc_run_nyp(o, a, n); i = 0; while i < n; o.nyp(a); i += 1; end; end
+";
+
+ internal static void Run(string[] args) {
+ int n = (args.Length > 1) ? Int32.Parse(args[1]) : 5_000_000;
+ var engine = IronRuby.Ruby.CreateEngine();
+ engine.Execute(Source);
+
+ object o = (object)engine.Execute("BcO.new"); // typed: a dynamic would send every call below through the binder
+ var lit1 = (Proc)engine.Execute("BcO.new.lit1"); // `{ 1 }': its dispatcher is the literal's code
+ var litx = (Proc)engine.Execute("BcO.new.litx"); // `{ |x| }'
+ var binding = (Binding)engine.Execute("BcO.new.sc(1)");
+ RubyScope bscope = binding.LocalScope;
+ while (!(bscope is RubyMethodScope)) { bscope = bscope._parent; } // a Binding's scope is a copy over the method's
+ var methodScope = (RubyMethodScope)bscope;
+ RubyScope declaringScope = methodScope._parent;
+ RubyModule declaringModule = methodScope.DeclaringModule;
+ var shape = new MethodFrameShape(new[] { "a" }, 1, "nyl");
+ var array = new RubyArray { 1 };
+
+ Console.WriteLine("block-cost harness: N = {0:N0}, best of 5 after a warm-up, ns per operation", n);
+ Console.WriteLine();
+
+ // ---- the steps, one at a time
+ Report("1a locals tuple (MakeLocalsStorage)", n, k => {
+ object last = null;
+ for (int i = 0; i < k; i++) { last = new MutableTuple