Skip to content

Commit 56c46fb

Browse files
lewingCopilotCopilot
authored
Fix crossgen2 OverflowException emitting inlining info for runtime-async inliners (dotnet#134697)
With cross-module inlining enabled (`--opt-cross-module`), crossgen2 can fail while emitting the cross-module inlining info table: ``` System.OverflowException: Arithmetic operation resulted in an overflow. at ILCompiler.DependencyAnalysis.ReadyToRun.InliningInfoNode.GetData(...) ``` Debug builds assert `_index != InvalidOffset` at the same place. ## Root cause When the runtime-async variant of a cross-module generic method is compiled into the image and inlines another method, `CompileMethod` records a `Check_IL_Body` fixup for the method's typical definition, which is the `AsyncMethodVariant`. `InliningInfoNode` reduced every inliner to its primary `EcmaMethod` and looked up that method's `Check_IL_Body` import instead. Nothing ever marked that import, so it was never placed, its index stayed at `int.MinValue`, and the checked `(uint)` cast threw. For an `async` method the `EcmaMethod` is the compiler-generated thunk, so debug builds instead assert while creating the signature. In the reported app, the failing inliner was the async variant of `Task<Completion<...>>.WaitAsync(CancellationToken)` (a CoreLib generic over an app type) inlining `TimeProvider.get_System()`. The cause is the async inlining change in dotnet#125472. dotnet#133146 probably just changed codegen enough to produce this case in the reported app. The bug isn't Wasm-specific: the new test reproduces it on osx-arm64. Browser CoreCLR R2R hits it first because its targets pass `--opt-cross-module:*` by default. ## Fix `CompileMethod` and `InliningInfoNode` now share `ILBodyFixupSignature.GetSignatureMethodForCompiledMethod`, which returns the typical `EcmaMethod` or `AsyncMethodVariant` that gets a compiled method's own `Check_IL_Body` fixup, or null if it can't have one. `InliningInfoNode` keeps one inliner entry per `EcmaMethod`, but stores that identity for cross-module inliners. Cross-module inliners with no such identity (async resumption stubs, return-dropping thunks, and other wrappers) or whose identity is a compiler-generated async thunk are not reported, since no `Check_IL_Body` import describes them. Inliners inside the version bubble are still encoded by `EcmaMethod` RID. When both variants inline the same method, the entry chosen doesn't depend on enumeration order. The runtime reader (`inlinetracking.cpp`, `GetILBodyTokenInfo`) uses only the module and token from these imports, so the output means the same thing. The inlining info format is unchanged. ## IL body checks now include runtime-async and synchronized flags The IL body signature used by `Check_IL_Body` and `Verify_IL_Body` covered the IL bytes, EH clauses, locals and referenced metadata, but not the method's impl flags. Both variants of a method read the same IL through the method token, so a method whose `miAsync` flag changed while its IL stayed the same still matched, and stale cross-module inlined code was used. `miSynchronized` had the same gap: a stale inline would skip the lock. `ReadyToRunStandaloneMethodMetadata` in crossgen2 and the VM now both record `miAsync` (`0x04`) and `miSynchronized` (`0x08`) in the byte that describes the locals table. Methods without these flags produce the same blob as before. The bits are documented in `readytorun-format.md`. The VM also rejects the fixup when the runtime method has no IL header, for example the task-returning variant of a method that became runtime-async, instead of reading a header that doesn't exist. If crossgen2 and the runtime come from different sides of this change, they reject each other's IL body checks for async or synchronized methods. For `Check_IL_Body` that only costs the precompiled code. `Verify_IL_Body`, used for Debug/Checked CoreLib, fails fast, so a local build that mixes a new VM with an old CoreLib image needs a CoreLib rebuild. The R2R version is unchanged, because older runtimes reject the new blob rather than misread it. ## Validation - Added `AsyncCrossModuleGenericInliner` to the R2R test suite. It fails without the fix (on osx-arm64) and passes with it. It also covers a method whose task-returning and async variants both inline the same cross-module inlinee. The full `ILCompiler.ReadyToRun.Tests` suite passes locally: 35 passed, 13 skipped for platform. - The skip for stubs and thunks has no test. I couldn't get crossgen2 to produce a return-dropping thunk that inlines something. - Replayed the crossgen2 command line from the failing `dotnet-inspect` browser CoreCLR R2R publish (`12.0.100-alpha.1.26472.116`) with a Debug crossgen2 built from this branch. It now emits `DotnetInspect.Web.Core.dll` without asserts. - Added `src/tests/readytorun/ilbody-implflags-versioning`. It compiles a consumer with `--opt-cross-module` against helper v1 and runs it against v2, where the helper methods have byte-identical IL and differ only in impl flags. The cases are a method that becomes runtime-async (awaited, and called for its `Task`), one that stops being runtime-async, and one that becomes synchronized. Without the IL body change, all three async checks fail. Running against v1 fails all four checks, including the synchronized one. With the change the test passes. The existing `readytorun/tests` (`mainv1`/`v2`/`v3`) and `async-inline-thunks` tests still pass. These were run locally on osx-arm64 Debug. Resolves dotnet#134015 > [!NOTE] > This PR description was generated with GitHub Copilot. --------- Co-authored-by: Copilot App <[email protected]> Co-authored-by: Copilot Autofix powered by AI <[email protected]>
1 parent 03a9187 commit 56c46fb

16 files changed

Lines changed: 485 additions & 32 deletions

File tree

‎docs/design/coreclr/botr/readytorun-format.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,7 @@ ECMA 335 does not have a natural encoding for describing an overridden method. T
336336

337337
#### IL Body signatures
338338

339-
ECMA 335 does not define a format that can represent the exact implementation of a method by itself. This signature holds all of the IL of the method, the EH table, the locals table, and each token (other than type references) in those tables is replaced with an index into a local stream of signatures. Those signatures are simply verbatim copies of the needed metadata to describe MemberRefs, TypeSpecs, MethodSpecs, StandaloneSignatures and strings. All of that is bundled into a large byte array. In addition, a series of TypeSignatures follows which allow the type references to be resolved, as well as a methodreference to the uninstantiated method. Assuming all of this matches with the data that is present at runtime, the fixup is considered to be satisfied. See ReadyToRunStandaloneMetadata.cs for the exact details of the format.
339+
ECMA 335 does not define a format that can represent the exact implementation of a method by itself. This signature holds all of the IL of the method, the EH table, the locals table, and each token (other than type references) in those tables is replaced with an index into a local stream of signatures. Those signatures are simply verbatim copies of the needed metadata to describe MemberRefs, TypeSpecs, MethodSpecs, StandaloneSignatures and strings. All of that is bundled into a large byte array. The byte that describes the locals table also records the method implementation flags that change how the same IL executes: `0x04` is set for `miAsync` (runtime-async) methods and `0x08` for `miSynchronized` methods. In addition, a series of TypeSignatures follows which allow the type references to be resolved, as well as a methodreference to the uninstantiated method. Assuming all of this matches with the data that is present at runtime, the fixup is considered to be satisfied. See ReadyToRunStandaloneMethodMetadata.cs for the exact details of the format.
340340

341341
#### InjectStringThunks signatures
342342

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System.Runtime.CompilerServices;
5+
using System.Threading.Tasks;
6+
7+
/// <summary>
8+
/// Consumer that awaits a runtime-async method on a generic type from AsyncCrossModuleGenericLib,
9+
/// instantiated over a value type defined in this assembly so that the async variant of
10+
/// AsyncGenericWrapper&lt;LocalAsyncStruct&gt;.InvokeGetValueAsync() is compiled into this image.
11+
/// </summary>
12+
13+
public struct LocalAsyncStruct { public int Value; }
14+
15+
public static class AsyncGenericInlinerConsumer
16+
{
17+
[MethodImpl(MethodImplOptions.NoInlining)]
18+
public static async Task<int> UseAsync()
19+
{
20+
var wrapper = new AsyncGenericWrapper<LocalAsyncStruct>(new LocalAsyncStruct { Value = 1 });
21+
return await wrapper.InvokeGetValueAsync();
22+
}
23+
24+
[MethodImpl(MethodImplOptions.NoInlining)]
25+
public static async Task<int> AwaitValueTask()
26+
{
27+
var wrapper = new AsyncGenericWrapper<LocalAsyncStruct>(new LocalAsyncStruct { Value = 2 });
28+
return await wrapper.GetValueTask();
29+
}
30+
31+
[MethodImpl(MethodImplOptions.NoInlining)]
32+
public static Task<int> ReturnValueTask()
33+
{
34+
var wrapper = new AsyncGenericWrapper<LocalAsyncStruct>(new LocalAsyncStruct { Value = 3 });
35+
return wrapper.GetValueTask();
36+
}
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System.Runtime.CompilerServices;
5+
using System.Threading.Tasks;
6+
7+
/// <summary>
8+
/// Library with a generic type whose runtime-async method inlines a utility method.
9+
/// When the consumer awaits the method on an instantiation over one of its own value types,
10+
/// crossgen2 compiles the async variant of the method into the consumer as a CrossModuleCompileable
11+
/// generic, making the async variant a cross-module inliner of AsyncGenericUtility.GetAsyncGenericValue.
12+
/// </summary>
13+
public static class AsyncGenericUtility
14+
{
15+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
16+
public static int GetAsyncGenericValue() => 42;
17+
18+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
19+
public static int GetSharedInlineeValue() => 43;
20+
}
21+
22+
public class AsyncGenericWrapper<T>
23+
{
24+
private T _value;
25+
26+
public AsyncGenericWrapper(T value) => _value = value;
27+
28+
[MethodImpl(MethodImplOptions.NoInlining)]
29+
public async Task<int> InvokeGetValueAsync()
30+
{
31+
await Task.Yield();
32+
return AsyncGenericUtility.GetAsyncGenericValue();
33+
}
34+
35+
// Not async, so both the task-returning method and its async variant are compiled from this IL.
36+
[MethodImpl(MethodImplOptions.NoInlining)]
37+
public Task<int> GetValueTask()
38+
{
39+
return Task.FromResult(AsyncGenericUtility.GetSharedInlineeValue());
40+
}
41+
}

‎src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2011,6 +2011,56 @@ static void Validate(ReadyToRunReader reader)
20112011
}
20122012
}
20132013

2014+
/// <summary>
2015+
/// Tests cross-module generic compilation where the runtime-async variant of a method from an
2016+
/// --opt-cross-module library is compiled into the consumer and inlines another library method.
2017+
/// The inlining info must reference the IL body fixup that was recorded for the async variant.
2018+
/// </summary>
2019+
[ConditionalFact(typeof(TestPaths), nameof(TestPaths.IsNotWasmTarget))]
2020+
public void AsyncCrossModuleGenericInliner()
2021+
{
2022+
var asyncCrossModuleGenericLib = new CompiledAssembly
2023+
{
2024+
AssemblyName = "AsyncCrossModuleGenericLib",
2025+
SourceResourceNames = ["CrossModuleInlining/Dependencies/AsyncCrossModuleGenericLib.cs"],
2026+
Features = { RuntimeAsyncFeature },
2027+
};
2028+
var consumer = new CompiledAssembly
2029+
{
2030+
AssemblyName = "AsyncGenericInlinerConsumer",
2031+
SourceResourceNames = ["CrossModuleInlining/AsyncGenericInlinerConsumer.cs"],
2032+
References = [asyncCrossModuleGenericLib],
2033+
Features = { RuntimeAsyncFeature },
2034+
};
2035+
2036+
new R2RTestRunner(_output).Run(new R2RTestCase(
2037+
nameof(AsyncCrossModuleGenericInliner),
2038+
[
2039+
new(consumer.AssemblyName,
2040+
[
2041+
new CrossgenAssembly(asyncCrossModuleGenericLib)
2042+
{
2043+
Kind = Crossgen2InputKind.Reference,
2044+
Options = [Crossgen2AssemblyOption.CrossModuleOptimization],
2045+
},
2046+
new CrossgenAssembly(consumer),
2047+
])
2048+
{
2049+
Validate = Validate,
2050+
},
2051+
]));
2052+
2053+
static void Validate(ReadyToRunReader reader)
2054+
{
2055+
string diag;
2056+
Assert.True(R2RAssert.HasManifestRef(reader, "AsyncCrossModuleGenericLib", out diag), diag);
2057+
Assert.True(R2RAssert.HasCrossModuleInliningInfo(reader, out diag), diag);
2058+
Assert.True(R2RAssert.HasCrossModuleInliners(reader, "GetAsyncGenericValue", ["InvokeGetValueAsync"], out diag), diag);
2059+
Assert.True(R2RAssert.HasAsyncVariant(reader, "GetValueTask", out diag), diag);
2060+
Assert.True(R2RAssert.HasCrossModuleInlinerCount(reader, "GetSharedInlineeValue", "GetValueTask", 1, out diag), diag);
2061+
}
2062+
}
2063+
20142064
[ConditionalFact(typeof(TestPaths), nameof(TestPaths.IsNotWasmTarget))]
20152065
public void VirtualMethodGenericsNonGVM()
20162066
{

‎src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCasesRunner/R2RResultChecker.cs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -637,6 +637,48 @@ public static bool HasCrossModuleInliners(
637637
return false;
638638
}
639639

640+
/// <summary>
641+
/// Returns true if the CrossModuleInlineInfo entry for an inlinee matching <paramref name="inlineeMethodName"/>
642+
/// has exactly <paramref name="expectedCount"/> cross-module inliners whose resolved names contain
643+
/// <paramref name="inlinerMethodName"/>.
644+
/// </summary>
645+
public static bool HasCrossModuleInlinerCount(
646+
ReadyToRunReader reader,
647+
string inlineeMethodName,
648+
string inlinerMethodName,
649+
int expectedCount,
650+
out string diagnostic)
651+
{
652+
if (!TryGetCrossModuleInliningInfoSection(reader, out var inliningInfo, out diagnostic))
653+
return false;
654+
655+
foreach (var entry in inliningInfo.GetEntries())
656+
{
657+
string inlineeName = inliningInfo.ResolveMethodName(entry.Inlinee);
658+
if (!inlineeName.Contains(inlineeMethodName, StringComparison.OrdinalIgnoreCase))
659+
continue;
660+
661+
var matchingInliners = new List<string>();
662+
foreach (var inliner in entry.Inliners)
663+
{
664+
if (!inliner.IsCrossModule)
665+
continue;
666+
667+
string inlinerName = inliningInfo.ResolveMethodName(inliner);
668+
if (inlinerName.Contains(inlinerMethodName, StringComparison.OrdinalIgnoreCase))
669+
matchingInliners.Add(inlinerName);
670+
}
671+
672+
diagnostic =
673+
$"Inlinee '{inlineeName}': expected {expectedCount} cross-module inliner(s) matching '{inlinerMethodName}', " +
674+
$"found {matchingInliners.Count}:\n {string.Join("\n ", matchingInliners)}";
675+
return matchingInliners.Count == expectedCount;
676+
}
677+
678+
diagnostic = $"No CrossModuleInlineInfo entry found for inlinee matching '{inlineeMethodName}'.";
679+
return false;
680+
}
681+
640682
/// <summary>
641683
/// Returns true if any inlining info section (CrossModuleInlineInfo or InliningInfo2) records
642684
/// that <paramref name="inlinerMethodName"/> inlined <paramref name="inlineeMethodName"/>.

‎src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ILBodyFixupSignature.cs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,15 @@ public ILBodyFixupSignature(ReadyToRunFixupKind fixupKind, MethodDesc signatureM
5151
_signatureMethod = signatureMethod;
5252
}
5353

54+
/// <summary>
55+
/// Returns the method a compiled method's own IL body fixup is created for, or null if the compiled method cannot have one.
56+
/// </summary>
57+
public static MethodDesc GetSignatureMethodForCompiledMethod(MethodDesc compiledMethod)
58+
{
59+
MethodDesc typicalDef = compiledMethod.GetTypicalMethodDefinition();
60+
return typicalDef is EcmaMethod or AsyncMethodVariant ? typicalDef : null;
61+
}
62+
5463
public override int ClassCode => 308579267;
5564

5665
protected override void OnMarked(NodeFactory context)

‎src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/InliningInfoNode.cs‎

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
6060
if (relocsOnly)
6161
return new ObjectData(Array.Empty<byte>(), Array.Empty<Relocation>(), 1, new ISymbolDefinitionNode[] { this });
6262

63-
Dictionary<MethodDesc, HashSet<MethodDesc>> inlineeToInliners = new Dictionary<MethodDesc, HashSet<MethodDesc>>();
63+
// Inliners are keyed by metadata definition; the value is the identity whose Check_IL_Body fixup was recorded when compiling it.
64+
Dictionary<MethodDesc, Dictionary<EcmaMethod, MethodDesc>> inlineeToInliners = new Dictionary<MethodDesc, Dictionary<EcmaMethod, MethodDesc>>();
6465

6566
// Build a map from inlinee to the list of inliners
6667
// We are only interested in the generic definitions of these.
@@ -83,6 +84,21 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
8384
// Only encode inlining info for inliners within the active module, or if cross module inline format is in use
8485
Debug.Assert(AllowCrossModuleInlines || (inlinerDefinition.Module == _module));
8586

87+
MethodDesc inlinerIdentity;
88+
if (AllowCrossModuleInlines && !factory.CompilationModuleGroup.VersionsWithMethodBody(inlinerDefinition))
89+
{
90+
inlinerIdentity = ILBodyFixupSignature.GetSignatureMethodForCompiledMethod(inliner);
91+
92+
// Cross-module inliners are encoded by their own Check_IL_Body import. Thunks and stubs don't have one.
93+
if (inlinerIdentity is null || inlinerIdentity.IsCompilerGeneratedILBodyForAsync())
94+
continue;
95+
}
96+
else
97+
{
98+
// Inliners in the version bubble are encoded by metadata RID.
99+
inlinerIdentity = inlinerDefinition;
100+
}
101+
86102
bool inlinerReportAllVersionsWithInlinee = !AllowCrossModuleInlines || factory.CompilationModuleGroup.CrossModuleCompileable(inlinerDefinition);
87103

88104
foreach (MethodDesc inlinee in inlinees)
@@ -123,12 +139,17 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
123139
}
124140
}
125141

126-
if (!inlineeToInliners.TryGetValue(inlineeDefinition, out HashSet<MethodDesc> inliners))
142+
if (!inlineeToInliners.TryGetValue(inlineeDefinition, out Dictionary<EcmaMethod, MethodDesc> inliners))
127143
{
128-
inliners = new HashSet<MethodDesc>();
144+
inliners = new Dictionary<EcmaMethod, MethodDesc>();
129145
inlineeToInliners.Add(inlineeDefinition, inliners);
130146
}
131-
inliners.Add(inlinerDefinition);
147+
148+
// Both variants of a method may inline the same inlinee; report it once, independent of enumeration order.
149+
if (!inliners.TryGetValue(inlinerDefinition, out MethodDesc existingInliner) || (inlinerIdentity is EcmaMethod && existingInliner is not EcmaMethod))
150+
{
151+
inliners[inlinerDefinition] = inlinerIdentity;
152+
}
132153
}
133154
}
134155

@@ -176,12 +197,8 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
176197
sig.Append(new UnsignedConstant((uint)factory.ManifestMetadataTable.ModuleToIndex(ecmaInlinee.Module)));
177198
}
178199

179-
// We're only concerned with metadata here, so we can convert all to EcmaMethod and lose info about AsyncVariant vs Task-Returning
180-
List<EcmaMethod> sortedInliners = new List<EcmaMethod>(inlineeWithInliners.Value.Count);
181-
foreach (var inliner in inlineeWithInliners.Value)
182-
{
183-
sortedInliners.Add((EcmaMethod)inliner.GetPrimaryMethodDesc());
184-
}
200+
// We're only concerned with metadata here, so we can use the EcmaMethod keys and lose info about AsyncVariant vs Task-Returning
201+
List<EcmaMethod> sortedInliners = new List<EcmaMethod>(inlineeWithInliners.Value.Keys);
185202
sortedInliners.MergeSort((a, b) =>
186203
{
187204
if (a == b)
@@ -242,8 +259,8 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
242259
bool isCrossModuleInlinee = !factory.CompilationModuleGroup.VersionsWithMethodBody(inlinee);
243260
Debug.Assert(!isCrossModuleInlinee || factory.CompilationModuleGroup.CrossModuleInlineable(inlinee));
244261

245-
EcmaMethod[] sortedInliners = new EcmaMethod[inlineeWithInliners.Value.Count];
246-
inlineeWithInliners.Value.CopyTo(sortedInliners);
262+
MethodDesc[] sortedInliners = new MethodDesc[inlineeWithInliners.Value.Count];
263+
inlineeWithInliners.Value.Values.CopyTo(sortedInliners, 0);
247264

248265
sortedInliners.MergeSort((a, b) =>
249266
{
@@ -270,14 +287,16 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
270287
}
271288
else
272289
{
273-
int aRid = MetadataTokens.GetRowNumber(a.Handle);
274-
int bRid = MetadataTokens.GetRowNumber(b.Handle);
290+
EcmaMethod ecmaA = (EcmaMethod)a.GetPrimaryMethodDesc();
291+
EcmaMethod ecmaB = (EcmaMethod)b.GetPrimaryMethodDesc();
292+
int aRid = MetadataTokens.GetRowNumber(ecmaA.Handle);
293+
int bRid = MetadataTokens.GetRowNumber(ecmaB.Handle);
275294
if (aRid < bRid)
276295
return -1;
277296
else if (aRid > bRid)
278297
return 1;
279298

280-
result = a.Module.CompareTo(b.Module);
299+
result = ecmaA.Module.CompareTo(ecmaB.Module);
281300
}
282301
Debug.Assert(result != 0);
283302
return result;
@@ -336,7 +355,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
336355
uint baseRid = 0;
337356
for (; inlinerIndex < sortedInliners.Length; inlinerIndex++)
338357
{
339-
var inliner = sortedInliners[inlinerIndex];
358+
var inliner = (EcmaMethod)sortedInliners[inlinerIndex].GetPrimaryMethodDesc();
340359
uint inlinerRid = (uint)MetadataTokens.GetRowNumber(inliner.Handle);
341360
uint ridDelta = inlinerRid - baseRid;
342361
baseRid = inlinerRid;

‎src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunStandaloneMethodMetadata.cs‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System;
55
using System.Collections.Generic;
66
using System.Diagnostics;
7+
using System.Reflection;
78
using System.Reflection.Metadata;
89
using System.Reflection.Metadata.Ecma335;
910

@@ -19,6 +20,13 @@ namespace ILCompiler
1920
// That code can be found in src\coreclr\vm\readytorunstandalonemethodmetadata.cpp
2021
public class ReadyToRunStandaloneMethodMetadata
2122
{
23+
// Values of the byte that follows the EH clauses. Must match the VM.
24+
private const byte LocalsNotInitialized = 0;
25+
private const byte LocalsInitialized = 1;
26+
private const byte NoLocals = 2;
27+
private const byte AsyncImplFlag = 4;
28+
private const byte SynchronizedImplFlag = 8;
29+
2230
public byte[] ConstantData;
2331
public TypeDesc[] TypeRefs;
2432

@@ -92,14 +100,17 @@ public static ReadyToRunStandaloneMethodMetadata Compute(EcmaMethod wrappedMetho
92100
}
93101
}
94102

95-
if (localsBlob.Length == 0)
96-
{
97-
// No locals. Encode a 2 to indicate this
98-
_nonCodeAlternateBlob.WriteByte(2);
99-
}
100-
else
103+
// Impl flags that change how the same IL executes are part of the IL body identity.
104+
byte localsAndImplFlags = localsBlob.Length == 0 ? NoLocals : (_methodBody.LocalVariablesInitialized ? LocalsInitialized : LocalsNotInitialized);
105+
MethodImplAttributes implAttributes = metadataReader.GetMethodDefinition(wrappedMethod.Handle).ImplAttributes;
106+
if ((implAttributes & MethodImplAttributes.Async) != 0)
107+
localsAndImplFlags |= AsyncImplFlag;
108+
if ((implAttributes & MethodImplAttributes.Synchronized) != 0)
109+
localsAndImplFlags |= SynchronizedImplFlag;
110+
_nonCodeAlternateBlob.WriteByte(localsAndImplFlags);
111+
112+
if (localsBlob.Length != 0)
101113
{
102-
_nonCodeAlternateBlob.WriteByte(_methodBody.LocalVariablesInitialized ? (byte)1 : (byte)0);
103114
EcmaSignatureTranslator sigTranslator = new EcmaSignatureTranslator(localsBlob, _nonCodeAlternateBlob, GetAlternateStreamToken);
104115
sigTranslator.ParseLocalsSignature();
105116
}

0 commit comments

Comments
 (0)