repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/installer/tests/HostActivation.Tests/NativeHosting/ComhostSideBySide.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Reflection.Metadata; using System.Runtime.InteropServices; using Microsoft.DotNet.Cli.Build.Framework; using Microsoft.NET.HostModel.ComHost; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.NativeHosting { public class ComhostSideBySide : IClassFixture<ComhostSideBySide.SharedTestState> { private readonly SharedTestState sharedState; public ComhostSideBySide(SharedTestState sharedTestState) { sharedState = sharedTestState; } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // COM activation is only supported on Windows public void ActivateClass() { string [] args = { "activation", sharedState.ClsidString }; CommandResult result = Command.Create(sharedState.ComSxsPath, args) .EnableTracingAndCaptureOutputs() .DotNetRoot(sharedState.ComLibraryFixture.BuiltDotnet.BinPath) .MultilevelLookup(false) .Execute(); result.Should().Pass() .And.HaveStdOutContaining("New instance of Server created"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // COM activation is only supported on Windows public void LocateEmbeddedTlb() { string [] args = { "typelib_lookup", sharedState.TypeLibId }; CommandResult result = Command.Create(sharedState.ComSxsPath, args) .EnableTracingAndCaptureOutputs() .DotNetRoot(sharedState.ComLibraryFixture.BuiltDotnet.BinPath) .MultilevelLookup(false) .Execute(); result.Should().Pass() .And.HaveStdOutContaining("Located type library by typeid."); } public class SharedTestState : Comhost.SharedTestState { public string TypeLibId { get; } = "{20151109-a0e8-46ae-b28e-8ff2c0e72166}"; public string ComSxsPath { get; } public SharedTestState() { if (!OperatingSystem.IsWindows()) { // COM activation is only supported on Windows return; } using (var assemblyStream = new FileStream(ComLibraryFixture.TestProject.AppDll, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read)) using (var peReader = new System.Reflection.PortableExecutable.PEReader(assemblyStream)) { if (peReader.HasMetadata) { string regFreeManifestPath = Path.Combine(BaseDirectory, $"{ ComLibraryFixture.TestProject.AssemblyName }.X.manifest"); MetadataReader reader = peReader.GetMetadataReader(); RegFreeComManifest.CreateManifestFromClsidmap( ComLibraryFixture.TestProject.AssemblyName, Path.GetFileName(ComHostPath), reader.GetAssemblyDefinition().Version.ToString(), ClsidMapPath, regFreeManifestPath, TypeLibraries ); } } string testDirectoryPath = Path.GetDirectoryName(NativeHostPath); string comsxsName = RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform("comsxs"); ComSxsPath = Path.Combine(testDirectoryPath, comsxsName); File.Copy( Path.Combine(RepoDirectories.Artifacts, "corehost_test", comsxsName), ComSxsPath); File.Copy( ComHostPath, Path.Combine(testDirectoryPath, Path.GetFileName(ComHostPath))); File.Copy( ComLibraryFixture.TestProject.AppDll, Path.Combine(testDirectoryPath, Path.GetFileName(ComLibraryFixture.TestProject.AppDll))); File.Copy( ComLibraryFixture.TestProject.DepsJson, Path.Combine(testDirectoryPath, Path.GetFileName(ComLibraryFixture.TestProject.DepsJson))); File.Copy( ComLibraryFixture.TestProject.RuntimeConfigJson, Path.Combine(testDirectoryPath, Path.GetFileName(ComLibraryFixture.TestProject.RuntimeConfigJson))); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Reflection.Metadata; using System.Runtime.InteropServices; using Microsoft.DotNet.Cli.Build.Framework; using Microsoft.NET.HostModel.ComHost; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.NativeHosting { [PlatformSpecific(TestPlatforms.Windows)] // COM activation is only supported on Windows public class ComhostSideBySide : IClassFixture<ComhostSideBySide.SharedTestState> { private readonly SharedTestState sharedState; public ComhostSideBySide(SharedTestState sharedTestState) { sharedState = sharedTestState; } [Fact] public void ActivateClass() { string [] args = { "activation", sharedState.ClsidString }; CommandResult result = Command.Create(sharedState.ComSxsPath, args) .EnableTracingAndCaptureOutputs() .DotNetRoot(sharedState.ComLibraryFixture.BuiltDotnet.BinPath) .MultilevelLookup(false) .Execute(); result.Should().Pass() .And.HaveStdOutContaining("New instance of Server created"); } [Fact] public void LocateEmbeddedTlb() { string [] args = { "typelib_lookup", sharedState.TypeLibId }; CommandResult result = Command.Create(sharedState.ComSxsPath, args) .EnableTracingAndCaptureOutputs() .DotNetRoot(sharedState.ComLibraryFixture.BuiltDotnet.BinPath) .MultilevelLookup(false) .Execute(); result.Should().Pass() .And.HaveStdOutContaining("Located type library by typeid."); } [Theory] [InlineData(true)] [InlineData(false)] public void ManagedHost(bool selfContained) { string [] args = { "comhost", sharedState.ClsidString }; TestProjectFixture fixture = selfContained ? sharedState.ManagedHostFixture_SelfContained : sharedState.ManagedHostFixture_FrameworkDependent; CommandResult result = Command.Create(fixture.TestProject.AppExe, args) .EnableTracingAndCaptureOutputs() .DotNetRoot(fixture.BuiltDotnet.BinPath) .MultilevelLookup(false) .Execute(); result.Should().Pass() .And.HaveStdOutContaining("New instance of Server created") .And.HaveStdOutContaining($"Activation of {sharedState.ClsidString} succeeded.") .And.HaveStdErrContaining($"Executing as a {(selfContained ? "self-contained" : "framework-dependent")} app"); } public class SharedTestState : Comhost.SharedTestState { public string TypeLibId { get; } = "{20151109-a0e8-46ae-b28e-8ff2c0e72166}"; public string ComSxsPath { get; } public TestProjectFixture ManagedHostFixture_FrameworkDependent { get; } public TestProjectFixture ManagedHostFixture_SelfContained { get; } public SharedTestState() { if (!OperatingSystem.IsWindows()) { // COM activation is only supported on Windows return; } string comsxsDirectory = BaseDirectory; string regFreeManifestName = $"{ ComLibraryFixture.TestProject.AssemblyName }.X.manifest"; string regFreeManifestPath = Path.Combine(comsxsDirectory, regFreeManifestName); using (var assemblyStream = new FileStream(ComLibraryFixture.TestProject.AppDll, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read)) using (var peReader = new System.Reflection.PortableExecutable.PEReader(assemblyStream)) { if (peReader.HasMetadata) { MetadataReader reader = peReader.GetMetadataReader(); RegFreeComManifest.CreateManifestFromClsidmap( ComLibraryFixture.TestProject.AssemblyName, Path.GetFileName(ComHostPath), reader.GetAssemblyDefinition().Version.ToString(), ClsidMapPath, regFreeManifestPath, TypeLibraries ); } } string comsxsName = RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform("comsxs"); ComSxsPath = Path.Combine(comsxsDirectory, comsxsName); File.Copy( Path.Combine(RepoDirectories.Artifacts, "corehost_test", comsxsName), ComSxsPath); ManagedHostFixture_FrameworkDependent = new TestProjectFixture("ManagedHost", RepoDirectories) .EnsureRestored() .PublishProject(selfContained: false, extraArgs: "/p:RegFreeCom=true"); File.Copy(regFreeManifestPath, Path.Combine(ManagedHostFixture_FrameworkDependent.TestProject.BuiltApp.Location, regFreeManifestName)); ManagedHostFixture_SelfContained = new TestProjectFixture("ManagedHost", RepoDirectories) .EnsureRestored() .PublishProject(selfContained: true, extraArgs: "/p:RegFreeCom=true"); File.Copy(regFreeManifestPath, Path.Combine(ManagedHostFixture_SelfContained.TestProject.BuiltApp.Location, regFreeManifestName)); // Copy the ComLibrary output and comhost to the ComSxS and ManagedHost directories string[] toCopy = { ComLibraryFixture.TestProject.AppDll, ComLibraryFixture.TestProject.DepsJson, ComLibraryFixture.TestProject.RuntimeConfigJson, ComHostPath, }; foreach (string filePath in toCopy) { File.Copy(filePath, Path.Combine(comsxsDirectory, Path.GetFileName(filePath))); File.Copy(filePath, Path.Combine(ManagedHostFixture_FrameworkDependent.TestProject.BuiltApp.Location, Path.GetFileName(filePath))); File.Copy(filePath, Path.Combine(ManagedHostFixture_SelfContained.TestProject.BuiltApp.Location, Path.GetFileName(filePath))); } } protected override void Dispose(bool disposing) { ManagedHostFixture_FrameworkDependent.Dispose(); ManagedHostFixture_SelfContained.Dispose(); base.Dispose(disposing); } } } }
1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Net.Quic/src/System/Net/Quic/QuicListener.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Quic.Implementations; using System.Net.Security; using System.Threading; using System.Threading.Tasks; namespace System.Net.Quic { public sealed class QuicListener : IDisposable { private readonly QuicListenerProvider _provider; /// <summary> /// Create a QUIC listener. /// </summary> /// <param name="listenEndPoint">The local endpoint to listen on.</param> /// <param name="sslServerAuthenticationOptions">TLS options for the listener.</param> public QuicListener(IPEndPoint listenEndPoint, SslServerAuthenticationOptions sslServerAuthenticationOptions) : this(QuicImplementationProviders.Default, listenEndPoint, sslServerAuthenticationOptions) { } /// <summary> /// Create a QUIC listener. /// </summary> /// <param name="options">The listener options.</param> public QuicListener(QuicListenerOptions options) : this(QuicImplementationProviders.Default, options) { } // !!! TEMPORARY: Remove or make internal before shipping public QuicListener(QuicImplementationProvider implementationProvider, IPEndPoint listenEndPoint, SslServerAuthenticationOptions sslServerAuthenticationOptions) : this(implementationProvider, new QuicListenerOptions() { ListenEndPoint = listenEndPoint, ServerAuthenticationOptions = sslServerAuthenticationOptions }) { } // !!! TEMPORARY: Remove or make internal before shipping public QuicListener(QuicImplementationProvider implementationProvider, QuicListenerOptions options) { _provider = implementationProvider.CreateListener(options); } public IPEndPoint ListenEndPoint => _provider.ListenEndPoint; /// <summary> /// Accept a connection. /// </summary> /// <returns></returns> public async ValueTask<QuicConnection> AcceptConnectionAsync(CancellationToken cancellationToken = default) => new QuicConnection(await _provider.AcceptConnectionAsync(cancellationToken).ConfigureAwait(false)); public void Dispose() => _provider.Dispose(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Quic.Implementations; using System.Net.Security; using System.Threading; using System.Threading.Tasks; namespace System.Net.Quic { public sealed class QuicListener : IDisposable { private readonly QuicListenerProvider _provider; /// <summary> /// Create a QUIC listener. /// </summary> /// <param name="listenEndPoint">The local endpoint to listen on.</param> /// <param name="sslServerAuthenticationOptions">TLS options for the listener.</param> public QuicListener(IPEndPoint listenEndPoint, SslServerAuthenticationOptions sslServerAuthenticationOptions) : this(QuicImplementationProviders.Default, listenEndPoint, sslServerAuthenticationOptions) { } /// <summary> /// Create a QUIC listener. /// </summary> /// <param name="options">The listener options.</param> public QuicListener(QuicListenerOptions options) : this(QuicImplementationProviders.Default, options) { } // !!! TEMPORARY: Remove or make internal before shipping public QuicListener(QuicImplementationProvider implementationProvider, IPEndPoint listenEndPoint, SslServerAuthenticationOptions sslServerAuthenticationOptions) : this(implementationProvider, new QuicListenerOptions() { ListenEndPoint = listenEndPoint, ServerAuthenticationOptions = sslServerAuthenticationOptions }) { } // !!! TEMPORARY: Remove or make internal before shipping public QuicListener(QuicImplementationProvider implementationProvider, QuicListenerOptions options) { _provider = implementationProvider.CreateListener(options); } public IPEndPoint ListenEndPoint => _provider.ListenEndPoint; /// <summary> /// Accept a connection. /// </summary> /// <returns></returns> public async ValueTask<QuicConnection> AcceptConnectionAsync(CancellationToken cancellationToken = default) => new QuicConnection(await _provider.AcceptConnectionAsync(cancellationToken).ConfigureAwait(false)); public void Dispose() => _provider.Dispose(); } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics; namespace System.StubHelpers { internal static class AnsiCharMarshaler { // The length of the returned array is an approximation based on the length of the input string and the system // character set. It is only guaranteed to be larger or equal to cbLength, don't depend on the exact value. internal static unsafe byte[] DoAnsiConversion(string str, bool fBestFit, bool fThrowOnUnmappableChar, out int cbLength) { byte[] buffer = new byte[checked((str.Length + 1) * Marshal.SystemMaxDBCSCharSize)]; fixed (byte* bufferPtr = &buffer[0]) { cbLength = Marshal.StringToAnsiString(str, bufferPtr, buffer.Length, fBestFit, fThrowOnUnmappableChar); } return buffer; } internal static unsafe byte ConvertToNative(char managedChar, bool fBestFit, bool fThrowOnUnmappableChar) { int cbAllocLength = (1 + 1) * Marshal.SystemMaxDBCSCharSize; byte* bufferPtr = stackalloc byte[cbAllocLength]; int cbLength = Marshal.StringToAnsiString(managedChar.ToString(), bufferPtr, cbAllocLength, fBestFit, fThrowOnUnmappableChar); Debug.Assert(cbLength > 0, "Zero bytes returned from DoAnsiConversion in AnsiCharMarshaler.ConvertToNative"); return bufferPtr[0]; } internal static char ConvertToManaged(byte nativeChar) { var bytes = new ReadOnlySpan<byte>(ref nativeChar, 1); string str = Encoding.Default.GetString(bytes); return str[0]; } } // class AnsiCharMarshaler internal static class CSTRMarshaler { internal static unsafe IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer) { if (null == strManaged) { return IntPtr.Zero; } int nb; byte* pbNativeBuffer = (byte*)pNativeBuffer; if (pbNativeBuffer != null || Marshal.SystemMaxDBCSCharSize == 1) { // If we are marshaling into a stack buffer or we can accurately estimate the size of the required heap // space, we will use a "1-pass" mode where we convert the string directly into the unmanaged buffer. // + 1 for the null character from the user. + 1 for the null character we put in. nb = checked((strManaged.Length + 1) * Marshal.SystemMaxDBCSCharSize + 1); bool didAlloc = false; // Use the pre-allocated buffer (allocated by localloc IL instruction) if not NULL, // otherwise fallback to AllocCoTaskMem if (pbNativeBuffer == null) { pbNativeBuffer = (byte*)Marshal.AllocCoTaskMem(nb); didAlloc = true; } try { nb = Marshal.StringToAnsiString(strManaged, pbNativeBuffer, nb, bestFit: 0 != (flags & 0xFF), throwOnUnmappableChar: 0 != (flags >> 8)); } catch (Exception) when (didAlloc) { Marshal.FreeCoTaskMem((IntPtr)pbNativeBuffer); throw; } } else { if (strManaged.Length == 0) { nb = 0; pbNativeBuffer = (byte*)Marshal.AllocCoTaskMem(2); } else { // Otherwise we use a slower "2-pass" mode where we first marshal the string into an intermediate buffer // (managed byte array) and then allocate exactly the right amount of unmanaged memory. This is to avoid // wasting memory on systems with multibyte character sets where the buffer we end up with is often much // smaller than the upper bound for the given managed string. byte[] bytes = AnsiCharMarshaler.DoAnsiConversion(strManaged, fBestFit: 0 != (flags & 0xFF), fThrowOnUnmappableChar: 0 != (flags >> 8), out nb); // + 1 for the null character from the user. + 1 for the null character we put in. pbNativeBuffer = (byte*)Marshal.AllocCoTaskMem(nb + 2); Buffer.Memmove(ref *pbNativeBuffer, ref MemoryMarshal.GetArrayDataReference(bytes), (nuint)nb); } } pbNativeBuffer[nb] = 0x00; pbNativeBuffer[nb + 1] = 0x00; return (IntPtr)pbNativeBuffer; } internal static unsafe string? ConvertToManaged(IntPtr cstr) { if (IntPtr.Zero == cstr) return null; else return new string((sbyte*)cstr); } internal static void ClearNative(IntPtr pNative) { Marshal.FreeCoTaskMem(pNative); } internal static unsafe void ConvertFixedToNative(int flags, string strManaged, IntPtr pNativeBuffer, int length) { if (strManaged == null) { if (length > 0) *(byte*)pNativeBuffer = 0; return; } int numChars = strManaged.Length; if (numChars >= length) { numChars = length - 1; } byte* buffer = (byte*)pNativeBuffer; // Flags defined in ILFixedCSTRMarshaler::EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit). bool throwOnUnmappableChar = 0 != (flags >> 8); bool bestFit = 0 != (flags & 0xFF); uint defaultCharUsed = 0; int cbWritten; fixed (char* pwzChar = strManaged) { #if TARGET_WINDOWS cbWritten = Interop.Kernel32.WideCharToMultiByte( Interop.Kernel32.CP_ACP, bestFit ? 0 : Interop.Kernel32.WC_NO_BEST_FIT_CHARS, pwzChar, numChars, buffer, length, IntPtr.Zero, throwOnUnmappableChar ? new IntPtr(&defaultCharUsed) : IntPtr.Zero); #else cbWritten = Encoding.UTF8.GetBytes(pwzChar, numChars, buffer, length); #endif } if (defaultCharUsed != 0) { throw new ArgumentException(SR.Interop_Marshal_Unmappable_Char); } if (cbWritten == (int)length) { cbWritten--; } buffer[cbWritten] = 0; } internal static unsafe string ConvertFixedToManaged(IntPtr cstr, int length) { int end = SpanHelpers.IndexOf(ref *(byte*)cstr, 0, length); if (end >= 0) { length = end; } return new string((sbyte*)cstr, 0, length); } } // class CSTRMarshaler internal static class UTF8Marshaler { private const int MAX_UTF8_CHAR_SIZE = 3; internal static unsafe IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer) { if (null == strManaged) { return IntPtr.Zero; } int nb; byte* pbNativeBuffer = (byte*)pNativeBuffer; // If we are marshaling into a stack buffer allocated by the ILStub // we will use a "1-pass" mode where we convert the string directly into the unmanaged buffer. // else we will allocate the precise native heap memory. if (pbNativeBuffer != null) { // this is the number of bytes allocated by the ILStub. nb = (strManaged.Length + 1) * MAX_UTF8_CHAR_SIZE; // nb is the actual number of bytes written by Encoding.GetBytes. // use nb to de-limit the string since we are allocating more than // required on stack nb = strManaged.GetBytesFromEncoding(pbNativeBuffer, nb, Encoding.UTF8); } // required bytes > 260 , allocate required bytes on heap else { nb = Encoding.UTF8.GetByteCount(strManaged); // + 1 for the null character. pbNativeBuffer = (byte*)Marshal.AllocCoTaskMem(nb + 1); strManaged.GetBytesFromEncoding(pbNativeBuffer, nb, Encoding.UTF8); } pbNativeBuffer[nb] = 0x0; return (IntPtr)pbNativeBuffer; } internal static unsafe string? ConvertToManaged(IntPtr cstr) { if (IntPtr.Zero == cstr) return null; byte* pBytes = (byte*)cstr; int nbBytes = string.strlen(pBytes); return string.CreateStringFromEncoding(pBytes, nbBytes, Encoding.UTF8); } internal static void ClearNative(IntPtr pNative) { Marshal.FreeCoTaskMem(pNative); } } internal static class UTF8BufferMarshaler { internal static unsafe IntPtr ConvertToNative(StringBuilder sb, IntPtr pNativeBuffer, int flags) { if (null == sb) { return IntPtr.Zero; } // Convert to string first string strManaged = sb.ToString(); // Get byte count int nb = Encoding.UTF8.GetByteCount(strManaged); // EmitConvertSpaceCLRToNative allocates memory byte* pbNativeBuffer = (byte*)pNativeBuffer; nb = strManaged.GetBytesFromEncoding(pbNativeBuffer, nb, Encoding.UTF8); pbNativeBuffer[nb] = 0x0; return (IntPtr)pbNativeBuffer; } internal static unsafe void ConvertToManaged(StringBuilder sb, IntPtr pNative) { if (pNative == IntPtr.Zero) return; byte* pBytes = (byte*)pNative; int nbBytes = string.strlen(pBytes); sb.ReplaceBufferUtf8Internal(new ReadOnlySpan<byte>(pBytes, nbBytes)); } } internal static class BSTRMarshaler { internal static unsafe IntPtr ConvertToNative(string strManaged, IntPtr pNativeBuffer) { if (null == strManaged) { return IntPtr.Zero; } else { bool hasTrailByte = strManaged.TryGetTrailByte(out byte trailByte); uint lengthInBytes = (uint)strManaged.Length * 2; if (hasTrailByte) { // this is an odd-sized string with a trailing byte stored in its sync block lengthInBytes++; } byte* ptrToFirstChar; if (pNativeBuffer != IntPtr.Zero) { // If caller provided a buffer, construct the BSTR manually. The size // of the buffer must be at least (lengthInBytes + 6) bytes. #if DEBUG uint length = *((uint*)pNativeBuffer); Debug.Assert(length >= lengthInBytes + 6, "BSTR localloc'ed buffer is too small"); #endif // set length *((uint*)pNativeBuffer) = lengthInBytes; ptrToFirstChar = (byte*)pNativeBuffer + 4; } else { // If not provided, allocate the buffer using Marshal.AllocBSTRByteLen so // that odd-sized strings will be handled as well. ptrToFirstChar = (byte*)Marshal.AllocBSTRByteLen(lengthInBytes); } // copy characters from the managed string Buffer.Memmove(ref *(char*)ptrToFirstChar, ref strManaged.GetRawStringData(), (nuint)strManaged.Length + 1); // copy the trail byte if present if (hasTrailByte) { ptrToFirstChar[lengthInBytes - 1] = trailByte; } // return ptr to first character return (IntPtr)ptrToFirstChar; } } internal static unsafe string? ConvertToManaged(IntPtr bstr) { if (IntPtr.Zero == bstr) { return null; } else { uint length = Marshal.SysStringByteLen(bstr); // Intentionally checking the number of bytes not characters to match the behavior // of ML marshalers. This prevents roundtripping of very large strings as the check // in the managed->native direction is done on String length but considering that // it's completely moot on 32-bit and not expected to be important on 64-bit either, // the ability to catch random garbage in the BSTR's length field outweighs this // restriction. If an ordinary null-terminated string is passed instead of a BSTR, // chances are that the length field - possibly being unallocated memory - contains // a heap fill pattern that will have the highest bit set, caught by the check. StubHelpers.CheckStringLength(length); string ret; if (length == 1) { // In the empty string case, we need to use FastAllocateString rather than the // String .ctor, since newing up a 0 sized string will always return String.Emtpy. // When we marshal that out as a bstr, it can wind up getting modified which // corrupts string.Empty. ret = string.FastAllocateString(0); } else { ret = new string((char*)bstr, 0, (int)(length / 2)); } if ((length & 1) == 1) { // odd-sized strings need to have the trailing byte saved in their sync block ret.SetTrailByte(((byte*)bstr)[length - 1]); } return ret; } } internal static void ClearNative(IntPtr pNative) { Marshal.FreeBSTR(pNative); } } // class BSTRMarshaler internal static class VBByValStrMarshaler { internal static unsafe IntPtr ConvertToNative(string strManaged, bool fBestFit, bool fThrowOnUnmappableChar, ref int cch) { if (null == strManaged) { return IntPtr.Zero; } byte* pNative; cch = strManaged.Length; // length field at negative offset + (# of characters incl. the terminator) * max ANSI char size int nbytes = checked(sizeof(uint) + ((cch + 1) * Marshal.SystemMaxDBCSCharSize)); pNative = (byte*)Marshal.AllocCoTaskMem(nbytes); int* pLength = (int*)pNative; pNative += sizeof(uint); if (0 == cch) { *pNative = 0; *pLength = 0; } else { byte[] bytes = AnsiCharMarshaler.DoAnsiConversion(strManaged, fBestFit, fThrowOnUnmappableChar, out int nbytesused); Debug.Assert(nbytesused >= 0 && nbytesused < nbytes, "Insufficient buffer allocated in VBByValStrMarshaler.ConvertToNative"); Buffer.Memmove(ref *pNative, ref MemoryMarshal.GetArrayDataReference(bytes), (nuint)nbytesused); pNative[nbytesused] = 0; *pLength = nbytesused; } return new IntPtr(pNative); } internal static unsafe string? ConvertToManaged(IntPtr pNative, int cch) { if (IntPtr.Zero == pNative) { return null; } return new string((sbyte*)pNative, 0, cch); } internal static void ClearNative(IntPtr pNative) { if (IntPtr.Zero != pNative) { Marshal.FreeCoTaskMem((IntPtr)(((long)pNative) - sizeof(uint))); } } } // class VBByValStrMarshaler internal static class AnsiBSTRMarshaler { internal static unsafe IntPtr ConvertToNative(int flags, string strManaged) { if (null == strManaged) { return IntPtr.Zero; } byte[]? bytes = null; int nb = 0; if (strManaged.Length > 0) { bytes = AnsiCharMarshaler.DoAnsiConversion(strManaged, 0 != (flags & 0xFF), 0 != (flags >> 8), out nb); } uint length = (uint)nb; IntPtr bstr = Marshal.AllocBSTRByteLen(length); if (bytes != null) { Buffer.Memmove(ref *(byte*)bstr, ref MemoryMarshal.GetArrayDataReference(bytes), length); } return bstr; } internal static unsafe string? ConvertToManaged(IntPtr bstr) { if (IntPtr.Zero == bstr) { return null; } else { // We intentionally ignore the length field of the BSTR for back compat reasons. // Unfortunately VB.NET uses Ansi BSTR marshaling when a string is passed ByRef // and we cannot afford to break this common scenario. return new string((sbyte*)bstr); } } internal static void ClearNative(IntPtr pNative) { Marshal.FreeBSTR(pNative); } } // class AnsiBSTRMarshaler internal static class FixedWSTRMarshaler { internal static unsafe void ConvertToNative(string? strManaged, IntPtr nativeHome, int length) { ReadOnlySpan<char> managed = strManaged; Span<char> native = new Span<char>((char*)nativeHome, length); int numChars = Math.Min(managed.Length, length - 1); managed.Slice(0, numChars).CopyTo(native); native[numChars] = '\0'; } internal static unsafe string ConvertToManaged(IntPtr nativeHome, int length) { int end = SpanHelpers.IndexOf(ref *(char*)nativeHome, '\0', length); if (end >= 0) { length = end; } return new string((char*)nativeHome, 0, length); } } // class WSTRBufferMarshaler #if FEATURE_COMINTEROP internal static class ObjectMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertToNative(object objSrc, IntPtr pDstVariant); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern object ConvertToManaged(IntPtr pSrcVariant); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNative(IntPtr pVariant); } // class ObjectMarshaler #endif // FEATURE_COMINTEROP internal sealed class HandleMarshaler { internal static unsafe IntPtr ConvertSafeHandleToNative(SafeHandle? handle, ref CleanupWorkListElement? cleanupWorkList) { if (Unsafe.IsNullRef(ref cleanupWorkList)) { throw new InvalidOperationException(SR.Interop_Marshal_SafeHandle_InvalidOperation); } ArgumentNullException.ThrowIfNull(handle); return StubHelpers.AddToCleanupList(ref cleanupWorkList, handle); } internal static unsafe void ThrowSafeHandleFieldChanged() { throw new NotSupportedException(SR.Interop_Marshal_CannotCreateSafeHandleField); } internal static unsafe void ThrowCriticalHandleFieldChanged() { throw new NotSupportedException(SR.Interop_Marshal_CannotCreateCriticalHandleField); } } internal static class DateMarshaler { internal static double ConvertToNative(DateTime managedDate) { return managedDate.ToOADate(); } internal static long ConvertToManaged(double nativeDate) { return DateTime.DoubleDateToTicks(nativeDate); } } // class DateMarshaler #if FEATURE_COMINTEROP internal static partial class InterfaceMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr ConvertToNative(object objSrc, IntPtr itfMT, IntPtr classMT, int flags); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern object ConvertToManaged(ref IntPtr ppUnk, IntPtr itfMT, IntPtr classMT, int flags); [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "InterfaceMarshaler__ClearNative")] internal static partial void ClearNative(IntPtr pUnk); } // class InterfaceMarshaler #endif // FEATURE_COMINTEROP internal static class MngdNativeArrayMarshaler { // Needs to match exactly with MngdNativeArrayMarshaler in ilmarshalers.h internal struct MarshalerState { #pragma warning disable CA1823 // not used by managed code private IntPtr m_pElementMT; private IntPtr m_Array; private IntPtr m_pManagedNativeArrayMarshaler; private int m_NativeDataValid; private int m_BestFitMap; private int m_ThrowOnUnmappableChar; private short m_vt; #pragma warning restore CA1823 } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int dwFlags, IntPtr pManagedMarshaler); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int cElements); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int cElements); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNativeContents(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int cElements); } // class MngdNativeArrayMarshaler internal static class MngdFixedArrayMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int dwFlags, int cElements, IntPtr pManagedMarshaler); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNativeContents(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); } // class MngdFixedArrayMarshaler #if FEATURE_COMINTEROP internal static class MngdSafeArrayMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int iRank, int dwFlags, IntPtr pManagedMarshaler); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, object pOriginalManaged); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); } // class MngdSafeArrayMarshaler #endif // FEATURE_COMINTEROP internal static class MngdRefCustomMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pCMHelper); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); } // class MngdRefCustomMarshaler internal struct AsAnyMarshaler { private const ushort VTHACK_ANSICHAR = 253; private const ushort VTHACK_WINBOOL = 254; private enum BackPropAction { None, Array, Layout, StringBuilderAnsi, StringBuilderUnicode } // Pointer to MngdNativeArrayMarshaler, ownership not assumed. private IntPtr pvArrayMarshaler; // Type of action to perform after the CLR-to-unmanaged call. private BackPropAction backPropAction; // The managed layout type for BackPropAction.Layout. private Type? layoutType; // Cleanup list to be destroyed when clearing the native view (for layouts with SafeHandles). private CleanupWorkListElement? cleanupWorkList; [Flags] internal enum AsAnyFlags { In = 0x10000000, Out = 0x20000000, IsAnsi = 0x00FF0000, IsThrowOn = 0x0000FF00, IsBestFit = 0x000000FF } private static bool IsIn(int dwFlags) => (dwFlags & (int)AsAnyFlags.In) != 0; private static bool IsOut(int dwFlags) => (dwFlags & (int)AsAnyFlags.Out) != 0; private static bool IsAnsi(int dwFlags) => (dwFlags & (int)AsAnyFlags.IsAnsi) != 0; private static bool IsThrowOn(int dwFlags) => (dwFlags & (int)AsAnyFlags.IsThrowOn) != 0; private static bool IsBestFit(int dwFlags) => (dwFlags & (int)AsAnyFlags.IsBestFit) != 0; internal AsAnyMarshaler(IntPtr pvArrayMarshaler) { // we need this in case the value being marshaled turns out to be array Debug.Assert(pvArrayMarshaler != IntPtr.Zero, "pvArrayMarshaler must not be null"); this.pvArrayMarshaler = pvArrayMarshaler; backPropAction = BackPropAction.None; layoutType = null; cleanupWorkList = null; } #region ConvertToNative helpers private unsafe IntPtr ConvertArrayToNative(object pManagedHome, int dwFlags) { Type elementType = pManagedHome.GetType().GetElementType()!; VarEnum vt; switch (Type.GetTypeCode(elementType)) { case TypeCode.SByte: vt = VarEnum.VT_I1; break; case TypeCode.Byte: vt = VarEnum.VT_UI1; break; case TypeCode.Int16: vt = VarEnum.VT_I2; break; case TypeCode.UInt16: vt = VarEnum.VT_UI2; break; case TypeCode.Int32: vt = VarEnum.VT_I4; break; case TypeCode.UInt32: vt = VarEnum.VT_UI4; break; case TypeCode.Int64: vt = VarEnum.VT_I8; break; case TypeCode.UInt64: vt = VarEnum.VT_UI8; break; case TypeCode.Single: vt = VarEnum.VT_R4; break; case TypeCode.Double: vt = VarEnum.VT_R8; break; case TypeCode.Char: vt = (IsAnsi(dwFlags) ? (VarEnum)VTHACK_ANSICHAR : VarEnum.VT_UI2); break; case TypeCode.Boolean: vt = (VarEnum)VTHACK_WINBOOL; break; case TypeCode.Object: { if (elementType == typeof(IntPtr)) { vt = (IntPtr.Size == 4 ? VarEnum.VT_I4 : VarEnum.VT_I8); } else if (elementType == typeof(UIntPtr)) { vt = (IntPtr.Size == 4 ? VarEnum.VT_UI4 : VarEnum.VT_UI8); } else goto default; break; } default: throw new ArgumentException(SR.Arg_NDirectBadObject); } // marshal the object as C-style array (UnmanagedType.LPArray) int dwArrayMarshalerFlags = (int)vt; if (IsBestFit(dwFlags)) dwArrayMarshalerFlags |= (1 << 16); if (IsThrowOn(dwFlags)) dwArrayMarshalerFlags |= (1 << 24); MngdNativeArrayMarshaler.CreateMarshaler( pvArrayMarshaler, IntPtr.Zero, // not needed as we marshal primitive VTs only dwArrayMarshalerFlags, IntPtr.Zero); // not needed as we marshal primitive VTs only IntPtr pNativeHome; IntPtr pNativeHomeAddr = new IntPtr(&pNativeHome); MngdNativeArrayMarshaler.ConvertSpaceToNative( pvArrayMarshaler, ref pManagedHome, pNativeHomeAddr); if (IsIn(dwFlags)) { MngdNativeArrayMarshaler.ConvertContentsToNative( pvArrayMarshaler, ref pManagedHome, pNativeHomeAddr); } if (IsOut(dwFlags)) { backPropAction = BackPropAction.Array; } return pNativeHome; } private static IntPtr ConvertStringToNative(string pManagedHome, int dwFlags) { IntPtr pNativeHome; // IsIn, IsOut are ignored for strings - they're always in-only if (IsAnsi(dwFlags)) { // marshal the object as Ansi string (UnmanagedType.LPStr) pNativeHome = CSTRMarshaler.ConvertToNative( dwFlags & 0xFFFF, // (throw on unmappable char << 8 | best fit) pManagedHome, // IntPtr.Zero); // unmanaged buffer will be allocated } else { // marshal the object as Unicode string (UnmanagedType.LPWStr) int allocSize = (pManagedHome.Length + 1) * 2; pNativeHome = Marshal.AllocCoTaskMem(allocSize); unsafe { Buffer.Memmove(ref *(char*)pNativeHome, ref pManagedHome.GetRawStringData(), (nuint)pManagedHome.Length + 1); } } return pNativeHome; } private unsafe IntPtr ConvertStringBuilderToNative(StringBuilder pManagedHome, int dwFlags) { IntPtr pNativeHome; // P/Invoke can be used to call Win32 apis that don't strictly follow CLR in/out semantics and thus may // leave garbage in the buffer in circumstances that we can't detect. To prevent us from crashing when // converting the contents back to managed, put a hidden NULL terminator past the end of the official buffer. // Unmanaged layout: // +====================================+ // | Extra hidden NULL | // +====================================+ \ // | | | // | [Converted] NULL-terminated string | |- buffer that the target may change // | | | // +====================================+ / <-- native home // Cache StringBuilder capacity and length to ensure we don't allocate a certain amount of // native memory and then walk beyond its end if the StringBuilder concurrently grows erroneously. int pManagedHomeCapacity = pManagedHome.Capacity; int pManagedHomeLength = pManagedHome.Length; if (pManagedHomeLength > pManagedHomeCapacity) { ThrowHelper.ThrowInvalidOperationException(); } // Note that StringBuilder.Capacity is the number of characters NOT including any terminators. if (IsAnsi(dwFlags)) { StubHelpers.CheckStringLength(pManagedHomeCapacity); // marshal the object as Ansi string (UnmanagedType.LPStr) int allocSize = checked((pManagedHomeCapacity * Marshal.SystemMaxDBCSCharSize) + 4); pNativeHome = Marshal.AllocCoTaskMem(allocSize); byte* ptr = (byte*)pNativeHome; *(ptr + allocSize - 3) = 0; *(ptr + allocSize - 2) = 0; *(ptr + allocSize - 1) = 0; if (IsIn(dwFlags)) { int length = Marshal.StringToAnsiString(pManagedHome.ToString(), ptr, allocSize, IsBestFit(dwFlags), IsThrowOn(dwFlags)); Debug.Assert(length < allocSize, "Expected a length less than the allocated size"); } if (IsOut(dwFlags)) { backPropAction = BackPropAction.StringBuilderAnsi; } } else { // marshal the object as Unicode string (UnmanagedType.LPWStr) int allocSize = checked((pManagedHomeCapacity * 2) + 4); pNativeHome = Marshal.AllocCoTaskMem(allocSize); byte* ptr = (byte*)pNativeHome; *(ptr + allocSize - 1) = 0; *(ptr + allocSize - 2) = 0; if (IsIn(dwFlags)) { pManagedHome.InternalCopy(pNativeHome, pManagedHomeLength); // null-terminate the native string int length = pManagedHomeLength * 2; *(ptr + length + 0) = 0; *(ptr + length + 1) = 0; } if (IsOut(dwFlags)) { backPropAction = BackPropAction.StringBuilderUnicode; } } return pNativeHome; } private unsafe IntPtr ConvertLayoutToNative(object pManagedHome, int dwFlags) { // Note that the following call will not throw exception if the type // of pManagedHome is not marshalable. That's intentional because we // want to maintain the original behavior where this was indicated // by TypeLoadException during the actual field marshaling. int allocSize = Marshal.SizeOfHelper(pManagedHome.GetType(), false); IntPtr pNativeHome = Marshal.AllocCoTaskMem(allocSize); // marshal the object as class with layout (UnmanagedType.LPStruct) if (IsIn(dwFlags)) { StubHelpers.FmtClassUpdateNativeInternal(pManagedHome, (byte*)pNativeHome, ref cleanupWorkList); } if (IsOut(dwFlags)) { backPropAction = BackPropAction.Layout; } layoutType = pManagedHome.GetType(); return pNativeHome; } #endregion internal IntPtr ConvertToNative(object pManagedHome, int dwFlags) { if (pManagedHome == null) return IntPtr.Zero; if (pManagedHome is ArrayWithOffset) throw new ArgumentException(SR.Arg_MarshalAsAnyRestriction); IntPtr pNativeHome; if (pManagedHome.GetType().IsArray) { // array (LPArray) pNativeHome = ConvertArrayToNative(pManagedHome, dwFlags); } else { if (pManagedHome is string strValue) { // string (LPStr or LPWStr) pNativeHome = ConvertStringToNative(strValue, dwFlags); } else if (pManagedHome is StringBuilder sbValue) { // StringBuilder (LPStr or LPWStr) pNativeHome = ConvertStringBuilderToNative(sbValue, dwFlags); } else if (pManagedHome.GetType().IsLayoutSequential || pManagedHome.GetType().IsExplicitLayout) { // layout (LPStruct) pNativeHome = ConvertLayoutToNative(pManagedHome, dwFlags); } else { // this type is not supported for AsAny marshaling throw new ArgumentException(SR.Arg_NDirectBadObject); } } return pNativeHome; } internal unsafe void ConvertToManaged(object pManagedHome, IntPtr pNativeHome) { switch (backPropAction) { case BackPropAction.Array: { MngdNativeArrayMarshaler.ConvertContentsToManaged( pvArrayMarshaler, ref pManagedHome, new IntPtr(&pNativeHome)); break; } case BackPropAction.Layout: { StubHelpers.FmtClassUpdateCLRInternal(pManagedHome, (byte*)pNativeHome); break; } case BackPropAction.StringBuilderAnsi: { int length; if (pNativeHome == IntPtr.Zero) { length = 0; } else { length = string.strlen((byte*)pNativeHome); } ((StringBuilder)pManagedHome).ReplaceBufferAnsiInternal((sbyte*)pNativeHome, length); break; } case BackPropAction.StringBuilderUnicode: { int length; if (pNativeHome == IntPtr.Zero) { length = 0; } else { length = string.wcslen((char*)pNativeHome); } ((StringBuilder)pManagedHome).ReplaceBufferInternal((char*)pNativeHome, length); break; } // nothing to do for BackPropAction.None } } internal void ClearNative(IntPtr pNativeHome) { if (pNativeHome != IntPtr.Zero) { if (layoutType != null) { // this must happen regardless of BackPropAction Marshal.DestroyStructure(pNativeHome, layoutType); } Marshal.FreeCoTaskMem(pNativeHome); } StubHelpers.DestroyCleanupList(ref cleanupWorkList); } } // struct AsAnyMarshaler [StructLayout(LayoutKind.Sequential)] internal struct NativeVariant { private ushort vt; private ushort wReserved1; private ushort wReserved2; private ushort wReserved3; // The union portion of the structure contains at least one 64-bit type that on some 32-bit platforms // (notably ARM) requires 64-bit alignment. So on 32-bit platforms we'll actually size the variant // portion of the struct with an Int64 so the type loader notices this requirement (a no-op on x86, // but on ARM it will allow us to correctly determine the layout of native argument lists containing // VARIANTs). Note that the field names here don't matter: none of the code refers to these fields, // the structure just exists to provide size information to the IL marshaler. #if TARGET_64BIT private IntPtr data1; private IntPtr data2; #else private long data1; #endif } // struct NativeVariant // This NativeDecimal type is very similar to the System.Decimal type, except it requires an 8-byte alignment // like the native DECIMAL type instead of the 4-byte requirement of the System.Decimal type. [StructLayout(LayoutKind.Sequential)] internal struct NativeDecimal { private ushort reserved; private ushort signScale; private uint hi32; private ulong lo64; } internal abstract class CleanupWorkListElement { private CleanupWorkListElement? m_Next; protected abstract void DestroyCore(); public void Destroy() { DestroyCore(); CleanupWorkListElement? next = m_Next; while (next != null) { next.DestroyCore(); next = next.m_Next; } } public static void AddToCleanupList(ref CleanupWorkListElement? list, CleanupWorkListElement newElement) { if (list == null) { list = newElement; } else { newElement.m_Next = list; list = newElement; } } } // Keeps an object instance alive across the full Managed->Native call. // This ensures that users don't have to call GC.KeepAlive after passing a struct or class // that has a delegate field to native code. internal sealed class KeepAliveCleanupWorkListElement : CleanupWorkListElement { public KeepAliveCleanupWorkListElement(object obj) { m_obj = obj; } private object m_obj; protected override void DestroyCore() { GC.KeepAlive(m_obj); } } // Aggregates SafeHandle and the "owned" bit which indicates whether the SafeHandle // has been successfully AddRef'ed. This allows us to do realiable cleanup (Release) // if and only if it is needed. internal sealed class SafeHandleCleanupWorkListElement : CleanupWorkListElement { public SafeHandleCleanupWorkListElement(SafeHandle handle) { m_handle = handle; } private SafeHandle m_handle; // This field is passed by-ref to SafeHandle.DangerousAddRef. // DestroyCore ignores this element if m_owned is not set to true. private bool m_owned; protected override void DestroyCore() { if (m_owned) StubHelpers.SafeHandleRelease(m_handle); } public IntPtr AddRef() { // element.m_owned will be true iff the AddRef succeeded return StubHelpers.SafeHandleAddRef(m_handle, ref m_owned); } } // class CleanupWorkListElement internal static class StubHelpers { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetNDirectTarget(IntPtr pMD); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetDelegateTarget(Delegate pThis); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearLastError(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void SetLastError(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ThrowInteropParamException(int resID, int paramIdx); internal static IntPtr AddToCleanupList(ref CleanupWorkListElement? pCleanupWorkList, SafeHandle handle) { SafeHandleCleanupWorkListElement element = new SafeHandleCleanupWorkListElement(handle); CleanupWorkListElement.AddToCleanupList(ref pCleanupWorkList, element); return element.AddRef(); } internal static void KeepAliveViaCleanupList(ref CleanupWorkListElement? pCleanupWorkList, object obj) { KeepAliveCleanupWorkListElement element = new KeepAliveCleanupWorkListElement(obj); CleanupWorkListElement.AddToCleanupList(ref pCleanupWorkList, element); } internal static void DestroyCleanupList(ref CleanupWorkListElement? pCleanupWorkList) { if (pCleanupWorkList != null) { pCleanupWorkList.Destroy(); pCleanupWorkList = null; } } internal static Exception GetHRExceptionObject(int hr) { Exception ex = InternalGetHRExceptionObject(hr); ex.InternalPreserveStackTrace(); return ex; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Exception InternalGetHRExceptionObject(int hr); #if FEATURE_COMINTEROP internal static Exception GetCOMHRExceptionObject(int hr, IntPtr pCPCMD, object pThis) { Exception ex = InternalGetCOMHRExceptionObject(hr, pCPCMD, pThis); ex.InternalPreserveStackTrace(); return ex; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Exception InternalGetCOMHRExceptionObject(int hr, IntPtr pCPCMD, object? pThis); #endif // FEATURE_COMINTEROP [ThreadStatic] private static Exception? s_pendingExceptionObject; internal static Exception? GetPendingExceptionObject() { Exception? ex = s_pendingExceptionObject; if (ex != null) ex.InternalPreserveStackTrace(); s_pendingExceptionObject = null; return ex; } internal static void SetPendingExceptionObject(Exception? exception) { s_pendingExceptionObject = exception; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr CreateCustomMarshalerHelper(IntPtr pMD, int paramToken, IntPtr hndManagedType); //------------------------------------------------------- // SafeHandle Helpers //------------------------------------------------------- // AddRefs the SH and returns the underlying unmanaged handle. internal static IntPtr SafeHandleAddRef(SafeHandle pHandle, ref bool success) { if (pHandle == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pHandle, ExceptionResource.ArgumentNull_SafeHandle); } pHandle.DangerousAddRef(ref success); return pHandle.DangerousGetHandle(); } // Releases the SH (to be called from finally block). internal static void SafeHandleRelease(SafeHandle pHandle) { if (pHandle == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pHandle, ExceptionResource.ArgumentNull_SafeHandle); } pHandle.DangerousRelease(); } #if FEATURE_COMINTEROP [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetCOMIPFromRCW(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget, out bool pfNeedsRelease); #endif // FEATURE_COMINTEROP //------------------------------------------------------- // Profiler helpers //------------------------------------------------------- #if PROFILING_SUPPORTED [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr ProfilerBeginTransitionCallback(IntPtr pSecretParam, IntPtr pThread, object pThis); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ProfilerEndTransitionCallback(IntPtr pMD, IntPtr pThread); #endif // PROFILING_SUPPORTED //------------------------------------------------------ // misc //------------------------------------------------------ internal static void CheckStringLength(int length) { CheckStringLength((uint)length); } internal static void CheckStringLength(uint length) { if (length > 0x7ffffff0) { throw new MarshalDirectiveException(SR.Marshaler_StringTooLong); } } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern unsafe void FmtClassUpdateNativeInternal(object obj, byte* pNative, ref CleanupWorkListElement? pCleanupWorkList); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern unsafe void FmtClassUpdateCLRInternal(object obj, byte* pNative); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern unsafe void LayoutDestroyNativeInternal(object obj, byte* pNative); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern object AllocateInternal(IntPtr typeHandle); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void MarshalToUnmanagedVaListInternal(IntPtr va_list, uint vaListSize, IntPtr pArgIterator); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void MarshalToManagedVaListInternal(IntPtr va_list, IntPtr pArgIterator); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern uint CalcVaListSize(IntPtr va_list); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ValidateObject(object obj, IntPtr pMD, object pThis); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void LogPinnedArgument(IntPtr localDesc, IntPtr nativeArg); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ValidateByref(IntPtr byref, IntPtr pMD, object pThis); // the byref is pinned so we can safely "cast" it to IntPtr [Intrinsic] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetStubContext(); #if FEATURE_ARRAYSTUB_AS_IL [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ArrayTypeCheck(object o, object[] arr); #endif #if FEATURE_MULTICASTSTUB_AS_IL [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void MulticastDebuggerTraceHelper(object o, int count); #endif [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern IntPtr NextCallReturnAddress(); } // class StubHelpers }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics; namespace System.StubHelpers { internal static class AnsiCharMarshaler { // The length of the returned array is an approximation based on the length of the input string and the system // character set. It is only guaranteed to be larger or equal to cbLength, don't depend on the exact value. internal static unsafe byte[] DoAnsiConversion(string str, bool fBestFit, bool fThrowOnUnmappableChar, out int cbLength) { byte[] buffer = new byte[checked((str.Length + 1) * Marshal.SystemMaxDBCSCharSize)]; fixed (byte* bufferPtr = &buffer[0]) { cbLength = Marshal.StringToAnsiString(str, bufferPtr, buffer.Length, fBestFit, fThrowOnUnmappableChar); } return buffer; } internal static unsafe byte ConvertToNative(char managedChar, bool fBestFit, bool fThrowOnUnmappableChar) { int cbAllocLength = (1 + 1) * Marshal.SystemMaxDBCSCharSize; byte* bufferPtr = stackalloc byte[cbAllocLength]; int cbLength = Marshal.StringToAnsiString(managedChar.ToString(), bufferPtr, cbAllocLength, fBestFit, fThrowOnUnmappableChar); Debug.Assert(cbLength > 0, "Zero bytes returned from DoAnsiConversion in AnsiCharMarshaler.ConvertToNative"); return bufferPtr[0]; } internal static char ConvertToManaged(byte nativeChar) { var bytes = new ReadOnlySpan<byte>(ref nativeChar, 1); string str = Encoding.Default.GetString(bytes); return str[0]; } } // class AnsiCharMarshaler internal static class CSTRMarshaler { internal static unsafe IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer) { if (null == strManaged) { return IntPtr.Zero; } int nb; byte* pbNativeBuffer = (byte*)pNativeBuffer; if (pbNativeBuffer != null || Marshal.SystemMaxDBCSCharSize == 1) { // If we are marshaling into a stack buffer or we can accurately estimate the size of the required heap // space, we will use a "1-pass" mode where we convert the string directly into the unmanaged buffer. // + 1 for the null character from the user. + 1 for the null character we put in. nb = checked((strManaged.Length + 1) * Marshal.SystemMaxDBCSCharSize + 1); bool didAlloc = false; // Use the pre-allocated buffer (allocated by localloc IL instruction) if not NULL, // otherwise fallback to AllocCoTaskMem if (pbNativeBuffer == null) { pbNativeBuffer = (byte*)Marshal.AllocCoTaskMem(nb); didAlloc = true; } try { nb = Marshal.StringToAnsiString(strManaged, pbNativeBuffer, nb, bestFit: 0 != (flags & 0xFF), throwOnUnmappableChar: 0 != (flags >> 8)); } catch (Exception) when (didAlloc) { Marshal.FreeCoTaskMem((IntPtr)pbNativeBuffer); throw; } } else { if (strManaged.Length == 0) { nb = 0; pbNativeBuffer = (byte*)Marshal.AllocCoTaskMem(2); } else { // Otherwise we use a slower "2-pass" mode where we first marshal the string into an intermediate buffer // (managed byte array) and then allocate exactly the right amount of unmanaged memory. This is to avoid // wasting memory on systems with multibyte character sets where the buffer we end up with is often much // smaller than the upper bound for the given managed string. byte[] bytes = AnsiCharMarshaler.DoAnsiConversion(strManaged, fBestFit: 0 != (flags & 0xFF), fThrowOnUnmappableChar: 0 != (flags >> 8), out nb); // + 1 for the null character from the user. + 1 for the null character we put in. pbNativeBuffer = (byte*)Marshal.AllocCoTaskMem(nb + 2); Buffer.Memmove(ref *pbNativeBuffer, ref MemoryMarshal.GetArrayDataReference(bytes), (nuint)nb); } } pbNativeBuffer[nb] = 0x00; pbNativeBuffer[nb + 1] = 0x00; return (IntPtr)pbNativeBuffer; } internal static unsafe string? ConvertToManaged(IntPtr cstr) { if (IntPtr.Zero == cstr) return null; else return new string((sbyte*)cstr); } internal static void ClearNative(IntPtr pNative) { Marshal.FreeCoTaskMem(pNative); } internal static unsafe void ConvertFixedToNative(int flags, string strManaged, IntPtr pNativeBuffer, int length) { if (strManaged == null) { if (length > 0) *(byte*)pNativeBuffer = 0; return; } int numChars = strManaged.Length; if (numChars >= length) { numChars = length - 1; } byte* buffer = (byte*)pNativeBuffer; // Flags defined in ILFixedCSTRMarshaler::EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit). bool throwOnUnmappableChar = 0 != (flags >> 8); bool bestFit = 0 != (flags & 0xFF); uint defaultCharUsed = 0; int cbWritten; fixed (char* pwzChar = strManaged) { #if TARGET_WINDOWS cbWritten = Interop.Kernel32.WideCharToMultiByte( Interop.Kernel32.CP_ACP, bestFit ? 0 : Interop.Kernel32.WC_NO_BEST_FIT_CHARS, pwzChar, numChars, buffer, length, IntPtr.Zero, throwOnUnmappableChar ? new IntPtr(&defaultCharUsed) : IntPtr.Zero); #else cbWritten = Encoding.UTF8.GetBytes(pwzChar, numChars, buffer, length); #endif } if (defaultCharUsed != 0) { throw new ArgumentException(SR.Interop_Marshal_Unmappable_Char); } if (cbWritten == (int)length) { cbWritten--; } buffer[cbWritten] = 0; } internal static unsafe string ConvertFixedToManaged(IntPtr cstr, int length) { int end = SpanHelpers.IndexOf(ref *(byte*)cstr, 0, length); if (end >= 0) { length = end; } return new string((sbyte*)cstr, 0, length); } } // class CSTRMarshaler internal static class UTF8Marshaler { private const int MAX_UTF8_CHAR_SIZE = 3; internal static unsafe IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer) { if (null == strManaged) { return IntPtr.Zero; } int nb; byte* pbNativeBuffer = (byte*)pNativeBuffer; // If we are marshaling into a stack buffer allocated by the ILStub // we will use a "1-pass" mode where we convert the string directly into the unmanaged buffer. // else we will allocate the precise native heap memory. if (pbNativeBuffer != null) { // this is the number of bytes allocated by the ILStub. nb = (strManaged.Length + 1) * MAX_UTF8_CHAR_SIZE; // nb is the actual number of bytes written by Encoding.GetBytes. // use nb to de-limit the string since we are allocating more than // required on stack nb = strManaged.GetBytesFromEncoding(pbNativeBuffer, nb, Encoding.UTF8); } // required bytes > 260 , allocate required bytes on heap else { nb = Encoding.UTF8.GetByteCount(strManaged); // + 1 for the null character. pbNativeBuffer = (byte*)Marshal.AllocCoTaskMem(nb + 1); strManaged.GetBytesFromEncoding(pbNativeBuffer, nb, Encoding.UTF8); } pbNativeBuffer[nb] = 0x0; return (IntPtr)pbNativeBuffer; } internal static unsafe string? ConvertToManaged(IntPtr cstr) { if (IntPtr.Zero == cstr) return null; byte* pBytes = (byte*)cstr; int nbBytes = string.strlen(pBytes); return string.CreateStringFromEncoding(pBytes, nbBytes, Encoding.UTF8); } internal static void ClearNative(IntPtr pNative) { Marshal.FreeCoTaskMem(pNative); } } internal static class UTF8BufferMarshaler { internal static unsafe IntPtr ConvertToNative(StringBuilder sb, IntPtr pNativeBuffer, int flags) { if (null == sb) { return IntPtr.Zero; } // Convert to string first string strManaged = sb.ToString(); // Get byte count int nb = Encoding.UTF8.GetByteCount(strManaged); // EmitConvertSpaceCLRToNative allocates memory byte* pbNativeBuffer = (byte*)pNativeBuffer; nb = strManaged.GetBytesFromEncoding(pbNativeBuffer, nb, Encoding.UTF8); pbNativeBuffer[nb] = 0x0; return (IntPtr)pbNativeBuffer; } internal static unsafe void ConvertToManaged(StringBuilder sb, IntPtr pNative) { if (pNative == IntPtr.Zero) return; byte* pBytes = (byte*)pNative; int nbBytes = string.strlen(pBytes); sb.ReplaceBufferUtf8Internal(new ReadOnlySpan<byte>(pBytes, nbBytes)); } } internal static class BSTRMarshaler { internal static unsafe IntPtr ConvertToNative(string strManaged, IntPtr pNativeBuffer) { if (null == strManaged) { return IntPtr.Zero; } else { bool hasTrailByte = strManaged.TryGetTrailByte(out byte trailByte); uint lengthInBytes = (uint)strManaged.Length * 2; if (hasTrailByte) { // this is an odd-sized string with a trailing byte stored in its sync block lengthInBytes++; } byte* ptrToFirstChar; if (pNativeBuffer != IntPtr.Zero) { // If caller provided a buffer, construct the BSTR manually. The size // of the buffer must be at least (lengthInBytes + 6) bytes. #if DEBUG uint length = *((uint*)pNativeBuffer); Debug.Assert(length >= lengthInBytes + 6, "BSTR localloc'ed buffer is too small"); #endif // set length *((uint*)pNativeBuffer) = lengthInBytes; ptrToFirstChar = (byte*)pNativeBuffer + 4; } else { // If not provided, allocate the buffer using Marshal.AllocBSTRByteLen so // that odd-sized strings will be handled as well. ptrToFirstChar = (byte*)Marshal.AllocBSTRByteLen(lengthInBytes); } // copy characters from the managed string Buffer.Memmove(ref *(char*)ptrToFirstChar, ref strManaged.GetRawStringData(), (nuint)strManaged.Length + 1); // copy the trail byte if present if (hasTrailByte) { ptrToFirstChar[lengthInBytes - 1] = trailByte; } // return ptr to first character return (IntPtr)ptrToFirstChar; } } internal static unsafe string? ConvertToManaged(IntPtr bstr) { if (IntPtr.Zero == bstr) { return null; } else { uint length = Marshal.SysStringByteLen(bstr); // Intentionally checking the number of bytes not characters to match the behavior // of ML marshalers. This prevents roundtripping of very large strings as the check // in the managed->native direction is done on String length but considering that // it's completely moot on 32-bit and not expected to be important on 64-bit either, // the ability to catch random garbage in the BSTR's length field outweighs this // restriction. If an ordinary null-terminated string is passed instead of a BSTR, // chances are that the length field - possibly being unallocated memory - contains // a heap fill pattern that will have the highest bit set, caught by the check. StubHelpers.CheckStringLength(length); string ret; if (length == 1) { // In the empty string case, we need to use FastAllocateString rather than the // String .ctor, since newing up a 0 sized string will always return String.Emtpy. // When we marshal that out as a bstr, it can wind up getting modified which // corrupts string.Empty. ret = string.FastAllocateString(0); } else { ret = new string((char*)bstr, 0, (int)(length / 2)); } if ((length & 1) == 1) { // odd-sized strings need to have the trailing byte saved in their sync block ret.SetTrailByte(((byte*)bstr)[length - 1]); } return ret; } } internal static void ClearNative(IntPtr pNative) { Marshal.FreeBSTR(pNative); } } // class BSTRMarshaler internal static class VBByValStrMarshaler { internal static unsafe IntPtr ConvertToNative(string strManaged, bool fBestFit, bool fThrowOnUnmappableChar, ref int cch) { if (null == strManaged) { return IntPtr.Zero; } byte* pNative; cch = strManaged.Length; // length field at negative offset + (# of characters incl. the terminator) * max ANSI char size int nbytes = checked(sizeof(uint) + ((cch + 1) * Marshal.SystemMaxDBCSCharSize)); pNative = (byte*)Marshal.AllocCoTaskMem(nbytes); int* pLength = (int*)pNative; pNative += sizeof(uint); if (0 == cch) { *pNative = 0; *pLength = 0; } else { byte[] bytes = AnsiCharMarshaler.DoAnsiConversion(strManaged, fBestFit, fThrowOnUnmappableChar, out int nbytesused); Debug.Assert(nbytesused >= 0 && nbytesused < nbytes, "Insufficient buffer allocated in VBByValStrMarshaler.ConvertToNative"); Buffer.Memmove(ref *pNative, ref MemoryMarshal.GetArrayDataReference(bytes), (nuint)nbytesused); pNative[nbytesused] = 0; *pLength = nbytesused; } return new IntPtr(pNative); } internal static unsafe string? ConvertToManaged(IntPtr pNative, int cch) { if (IntPtr.Zero == pNative) { return null; } return new string((sbyte*)pNative, 0, cch); } internal static void ClearNative(IntPtr pNative) { if (IntPtr.Zero != pNative) { Marshal.FreeCoTaskMem((IntPtr)(((long)pNative) - sizeof(uint))); } } } // class VBByValStrMarshaler internal static class AnsiBSTRMarshaler { internal static unsafe IntPtr ConvertToNative(int flags, string strManaged) { if (null == strManaged) { return IntPtr.Zero; } byte[]? bytes = null; int nb = 0; if (strManaged.Length > 0) { bytes = AnsiCharMarshaler.DoAnsiConversion(strManaged, 0 != (flags & 0xFF), 0 != (flags >> 8), out nb); } uint length = (uint)nb; IntPtr bstr = Marshal.AllocBSTRByteLen(length); if (bytes != null) { Buffer.Memmove(ref *(byte*)bstr, ref MemoryMarshal.GetArrayDataReference(bytes), length); } return bstr; } internal static unsafe string? ConvertToManaged(IntPtr bstr) { if (IntPtr.Zero == bstr) { return null; } else { // We intentionally ignore the length field of the BSTR for back compat reasons. // Unfortunately VB.NET uses Ansi BSTR marshaling when a string is passed ByRef // and we cannot afford to break this common scenario. return new string((sbyte*)bstr); } } internal static void ClearNative(IntPtr pNative) { Marshal.FreeBSTR(pNative); } } // class AnsiBSTRMarshaler internal static class FixedWSTRMarshaler { internal static unsafe void ConvertToNative(string? strManaged, IntPtr nativeHome, int length) { ReadOnlySpan<char> managed = strManaged; Span<char> native = new Span<char>((char*)nativeHome, length); int numChars = Math.Min(managed.Length, length - 1); managed.Slice(0, numChars).CopyTo(native); native[numChars] = '\0'; } internal static unsafe string ConvertToManaged(IntPtr nativeHome, int length) { int end = SpanHelpers.IndexOf(ref *(char*)nativeHome, '\0', length); if (end >= 0) { length = end; } return new string((char*)nativeHome, 0, length); } } // class WSTRBufferMarshaler #if FEATURE_COMINTEROP internal static class ObjectMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertToNative(object objSrc, IntPtr pDstVariant); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern object ConvertToManaged(IntPtr pSrcVariant); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNative(IntPtr pVariant); } // class ObjectMarshaler #endif // FEATURE_COMINTEROP internal sealed class HandleMarshaler { internal static unsafe IntPtr ConvertSafeHandleToNative(SafeHandle? handle, ref CleanupWorkListElement? cleanupWorkList) { if (Unsafe.IsNullRef(ref cleanupWorkList)) { throw new InvalidOperationException(SR.Interop_Marshal_SafeHandle_InvalidOperation); } ArgumentNullException.ThrowIfNull(handle); return StubHelpers.AddToCleanupList(ref cleanupWorkList, handle); } internal static unsafe void ThrowSafeHandleFieldChanged() { throw new NotSupportedException(SR.Interop_Marshal_CannotCreateSafeHandleField); } internal static unsafe void ThrowCriticalHandleFieldChanged() { throw new NotSupportedException(SR.Interop_Marshal_CannotCreateCriticalHandleField); } } internal static class DateMarshaler { internal static double ConvertToNative(DateTime managedDate) { return managedDate.ToOADate(); } internal static long ConvertToManaged(double nativeDate) { return DateTime.DoubleDateToTicks(nativeDate); } } // class DateMarshaler #if FEATURE_COMINTEROP internal static partial class InterfaceMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr ConvertToNative(object objSrc, IntPtr itfMT, IntPtr classMT, int flags); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern object ConvertToManaged(ref IntPtr ppUnk, IntPtr itfMT, IntPtr classMT, int flags); [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "InterfaceMarshaler__ClearNative")] internal static partial void ClearNative(IntPtr pUnk); } // class InterfaceMarshaler #endif // FEATURE_COMINTEROP internal static class MngdNativeArrayMarshaler { // Needs to match exactly with MngdNativeArrayMarshaler in ilmarshalers.h internal struct MarshalerState { #pragma warning disable CA1823 // not used by managed code private IntPtr m_pElementMT; private IntPtr m_Array; private IntPtr m_pManagedNativeArrayMarshaler; private int m_NativeDataValid; private int m_BestFitMap; private int m_ThrowOnUnmappableChar; private short m_vt; #pragma warning restore CA1823 } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int dwFlags, IntPtr pManagedMarshaler); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int cElements); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int cElements); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNativeContents(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int cElements); } // class MngdNativeArrayMarshaler internal static class MngdFixedArrayMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int dwFlags, int cElements, IntPtr pManagedMarshaler); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNativeContents(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); } // class MngdFixedArrayMarshaler #if FEATURE_COMINTEROP internal static class MngdSafeArrayMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int iRank, int dwFlags, IntPtr pManagedMarshaler); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, object pOriginalManaged); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); } // class MngdSafeArrayMarshaler #endif // FEATURE_COMINTEROP internal static class MngdRefCustomMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pCMHelper); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); } // class MngdRefCustomMarshaler internal struct AsAnyMarshaler { private const ushort VTHACK_ANSICHAR = 253; private const ushort VTHACK_WINBOOL = 254; private enum BackPropAction { None, Array, Layout, StringBuilderAnsi, StringBuilderUnicode } // Pointer to MngdNativeArrayMarshaler, ownership not assumed. private IntPtr pvArrayMarshaler; // Type of action to perform after the CLR-to-unmanaged call. private BackPropAction backPropAction; // The managed layout type for BackPropAction.Layout. private Type? layoutType; // Cleanup list to be destroyed when clearing the native view (for layouts with SafeHandles). private CleanupWorkListElement? cleanupWorkList; [Flags] internal enum AsAnyFlags { In = 0x10000000, Out = 0x20000000, IsAnsi = 0x00FF0000, IsThrowOn = 0x0000FF00, IsBestFit = 0x000000FF } private static bool IsIn(int dwFlags) => (dwFlags & (int)AsAnyFlags.In) != 0; private static bool IsOut(int dwFlags) => (dwFlags & (int)AsAnyFlags.Out) != 0; private static bool IsAnsi(int dwFlags) => (dwFlags & (int)AsAnyFlags.IsAnsi) != 0; private static bool IsThrowOn(int dwFlags) => (dwFlags & (int)AsAnyFlags.IsThrowOn) != 0; private static bool IsBestFit(int dwFlags) => (dwFlags & (int)AsAnyFlags.IsBestFit) != 0; internal AsAnyMarshaler(IntPtr pvArrayMarshaler) { // we need this in case the value being marshaled turns out to be array Debug.Assert(pvArrayMarshaler != IntPtr.Zero, "pvArrayMarshaler must not be null"); this.pvArrayMarshaler = pvArrayMarshaler; backPropAction = BackPropAction.None; layoutType = null; cleanupWorkList = null; } #region ConvertToNative helpers private unsafe IntPtr ConvertArrayToNative(object pManagedHome, int dwFlags) { Type elementType = pManagedHome.GetType().GetElementType()!; VarEnum vt; switch (Type.GetTypeCode(elementType)) { case TypeCode.SByte: vt = VarEnum.VT_I1; break; case TypeCode.Byte: vt = VarEnum.VT_UI1; break; case TypeCode.Int16: vt = VarEnum.VT_I2; break; case TypeCode.UInt16: vt = VarEnum.VT_UI2; break; case TypeCode.Int32: vt = VarEnum.VT_I4; break; case TypeCode.UInt32: vt = VarEnum.VT_UI4; break; case TypeCode.Int64: vt = VarEnum.VT_I8; break; case TypeCode.UInt64: vt = VarEnum.VT_UI8; break; case TypeCode.Single: vt = VarEnum.VT_R4; break; case TypeCode.Double: vt = VarEnum.VT_R8; break; case TypeCode.Char: vt = (IsAnsi(dwFlags) ? (VarEnum)VTHACK_ANSICHAR : VarEnum.VT_UI2); break; case TypeCode.Boolean: vt = (VarEnum)VTHACK_WINBOOL; break; case TypeCode.Object: { if (elementType == typeof(IntPtr)) { vt = (IntPtr.Size == 4 ? VarEnum.VT_I4 : VarEnum.VT_I8); } else if (elementType == typeof(UIntPtr)) { vt = (IntPtr.Size == 4 ? VarEnum.VT_UI4 : VarEnum.VT_UI8); } else goto default; break; } default: throw new ArgumentException(SR.Arg_NDirectBadObject); } // marshal the object as C-style array (UnmanagedType.LPArray) int dwArrayMarshalerFlags = (int)vt; if (IsBestFit(dwFlags)) dwArrayMarshalerFlags |= (1 << 16); if (IsThrowOn(dwFlags)) dwArrayMarshalerFlags |= (1 << 24); MngdNativeArrayMarshaler.CreateMarshaler( pvArrayMarshaler, IntPtr.Zero, // not needed as we marshal primitive VTs only dwArrayMarshalerFlags, IntPtr.Zero); // not needed as we marshal primitive VTs only IntPtr pNativeHome; IntPtr pNativeHomeAddr = new IntPtr(&pNativeHome); MngdNativeArrayMarshaler.ConvertSpaceToNative( pvArrayMarshaler, ref pManagedHome, pNativeHomeAddr); if (IsIn(dwFlags)) { MngdNativeArrayMarshaler.ConvertContentsToNative( pvArrayMarshaler, ref pManagedHome, pNativeHomeAddr); } if (IsOut(dwFlags)) { backPropAction = BackPropAction.Array; } return pNativeHome; } private static IntPtr ConvertStringToNative(string pManagedHome, int dwFlags) { IntPtr pNativeHome; // IsIn, IsOut are ignored for strings - they're always in-only if (IsAnsi(dwFlags)) { // marshal the object as Ansi string (UnmanagedType.LPStr) pNativeHome = CSTRMarshaler.ConvertToNative( dwFlags & 0xFFFF, // (throw on unmappable char << 8 | best fit) pManagedHome, // IntPtr.Zero); // unmanaged buffer will be allocated } else { // marshal the object as Unicode string (UnmanagedType.LPWStr) int allocSize = (pManagedHome.Length + 1) * 2; pNativeHome = Marshal.AllocCoTaskMem(allocSize); unsafe { Buffer.Memmove(ref *(char*)pNativeHome, ref pManagedHome.GetRawStringData(), (nuint)pManagedHome.Length + 1); } } return pNativeHome; } private unsafe IntPtr ConvertStringBuilderToNative(StringBuilder pManagedHome, int dwFlags) { IntPtr pNativeHome; // P/Invoke can be used to call Win32 apis that don't strictly follow CLR in/out semantics and thus may // leave garbage in the buffer in circumstances that we can't detect. To prevent us from crashing when // converting the contents back to managed, put a hidden NULL terminator past the end of the official buffer. // Unmanaged layout: // +====================================+ // | Extra hidden NULL | // +====================================+ \ // | | | // | [Converted] NULL-terminated string | |- buffer that the target may change // | | | // +====================================+ / <-- native home // Cache StringBuilder capacity and length to ensure we don't allocate a certain amount of // native memory and then walk beyond its end if the StringBuilder concurrently grows erroneously. int pManagedHomeCapacity = pManagedHome.Capacity; int pManagedHomeLength = pManagedHome.Length; if (pManagedHomeLength > pManagedHomeCapacity) { ThrowHelper.ThrowInvalidOperationException(); } // Note that StringBuilder.Capacity is the number of characters NOT including any terminators. if (IsAnsi(dwFlags)) { StubHelpers.CheckStringLength(pManagedHomeCapacity); // marshal the object as Ansi string (UnmanagedType.LPStr) int allocSize = checked((pManagedHomeCapacity * Marshal.SystemMaxDBCSCharSize) + 4); pNativeHome = Marshal.AllocCoTaskMem(allocSize); byte* ptr = (byte*)pNativeHome; *(ptr + allocSize - 3) = 0; *(ptr + allocSize - 2) = 0; *(ptr + allocSize - 1) = 0; if (IsIn(dwFlags)) { int length = Marshal.StringToAnsiString(pManagedHome.ToString(), ptr, allocSize, IsBestFit(dwFlags), IsThrowOn(dwFlags)); Debug.Assert(length < allocSize, "Expected a length less than the allocated size"); } if (IsOut(dwFlags)) { backPropAction = BackPropAction.StringBuilderAnsi; } } else { // marshal the object as Unicode string (UnmanagedType.LPWStr) int allocSize = checked((pManagedHomeCapacity * 2) + 4); pNativeHome = Marshal.AllocCoTaskMem(allocSize); byte* ptr = (byte*)pNativeHome; *(ptr + allocSize - 1) = 0; *(ptr + allocSize - 2) = 0; if (IsIn(dwFlags)) { pManagedHome.InternalCopy(pNativeHome, pManagedHomeLength); // null-terminate the native string int length = pManagedHomeLength * 2; *(ptr + length + 0) = 0; *(ptr + length + 1) = 0; } if (IsOut(dwFlags)) { backPropAction = BackPropAction.StringBuilderUnicode; } } return pNativeHome; } private unsafe IntPtr ConvertLayoutToNative(object pManagedHome, int dwFlags) { // Note that the following call will not throw exception if the type // of pManagedHome is not marshalable. That's intentional because we // want to maintain the original behavior where this was indicated // by TypeLoadException during the actual field marshaling. int allocSize = Marshal.SizeOfHelper(pManagedHome.GetType(), false); IntPtr pNativeHome = Marshal.AllocCoTaskMem(allocSize); // marshal the object as class with layout (UnmanagedType.LPStruct) if (IsIn(dwFlags)) { StubHelpers.FmtClassUpdateNativeInternal(pManagedHome, (byte*)pNativeHome, ref cleanupWorkList); } if (IsOut(dwFlags)) { backPropAction = BackPropAction.Layout; } layoutType = pManagedHome.GetType(); return pNativeHome; } #endregion internal IntPtr ConvertToNative(object pManagedHome, int dwFlags) { if (pManagedHome == null) return IntPtr.Zero; if (pManagedHome is ArrayWithOffset) throw new ArgumentException(SR.Arg_MarshalAsAnyRestriction); IntPtr pNativeHome; if (pManagedHome.GetType().IsArray) { // array (LPArray) pNativeHome = ConvertArrayToNative(pManagedHome, dwFlags); } else { if (pManagedHome is string strValue) { // string (LPStr or LPWStr) pNativeHome = ConvertStringToNative(strValue, dwFlags); } else if (pManagedHome is StringBuilder sbValue) { // StringBuilder (LPStr or LPWStr) pNativeHome = ConvertStringBuilderToNative(sbValue, dwFlags); } else if (pManagedHome.GetType().IsLayoutSequential || pManagedHome.GetType().IsExplicitLayout) { // layout (LPStruct) pNativeHome = ConvertLayoutToNative(pManagedHome, dwFlags); } else { // this type is not supported for AsAny marshaling throw new ArgumentException(SR.Arg_NDirectBadObject); } } return pNativeHome; } internal unsafe void ConvertToManaged(object pManagedHome, IntPtr pNativeHome) { switch (backPropAction) { case BackPropAction.Array: { MngdNativeArrayMarshaler.ConvertContentsToManaged( pvArrayMarshaler, ref pManagedHome, new IntPtr(&pNativeHome)); break; } case BackPropAction.Layout: { StubHelpers.FmtClassUpdateCLRInternal(pManagedHome, (byte*)pNativeHome); break; } case BackPropAction.StringBuilderAnsi: { int length; if (pNativeHome == IntPtr.Zero) { length = 0; } else { length = string.strlen((byte*)pNativeHome); } ((StringBuilder)pManagedHome).ReplaceBufferAnsiInternal((sbyte*)pNativeHome, length); break; } case BackPropAction.StringBuilderUnicode: { int length; if (pNativeHome == IntPtr.Zero) { length = 0; } else { length = string.wcslen((char*)pNativeHome); } ((StringBuilder)pManagedHome).ReplaceBufferInternal((char*)pNativeHome, length); break; } // nothing to do for BackPropAction.None } } internal void ClearNative(IntPtr pNativeHome) { if (pNativeHome != IntPtr.Zero) { if (layoutType != null) { // this must happen regardless of BackPropAction Marshal.DestroyStructure(pNativeHome, layoutType); } Marshal.FreeCoTaskMem(pNativeHome); } StubHelpers.DestroyCleanupList(ref cleanupWorkList); } } // struct AsAnyMarshaler [StructLayout(LayoutKind.Sequential)] internal struct NativeVariant { private ushort vt; private ushort wReserved1; private ushort wReserved2; private ushort wReserved3; // The union portion of the structure contains at least one 64-bit type that on some 32-bit platforms // (notably ARM) requires 64-bit alignment. So on 32-bit platforms we'll actually size the variant // portion of the struct with an Int64 so the type loader notices this requirement (a no-op on x86, // but on ARM it will allow us to correctly determine the layout of native argument lists containing // VARIANTs). Note that the field names here don't matter: none of the code refers to these fields, // the structure just exists to provide size information to the IL marshaler. #if TARGET_64BIT private IntPtr data1; private IntPtr data2; #else private long data1; #endif } // struct NativeVariant // This NativeDecimal type is very similar to the System.Decimal type, except it requires an 8-byte alignment // like the native DECIMAL type instead of the 4-byte requirement of the System.Decimal type. [StructLayout(LayoutKind.Sequential)] internal struct NativeDecimal { private ushort reserved; private ushort signScale; private uint hi32; private ulong lo64; } internal abstract class CleanupWorkListElement { private CleanupWorkListElement? m_Next; protected abstract void DestroyCore(); public void Destroy() { DestroyCore(); CleanupWorkListElement? next = m_Next; while (next != null) { next.DestroyCore(); next = next.m_Next; } } public static void AddToCleanupList(ref CleanupWorkListElement? list, CleanupWorkListElement newElement) { if (list == null) { list = newElement; } else { newElement.m_Next = list; list = newElement; } } } // Keeps an object instance alive across the full Managed->Native call. // This ensures that users don't have to call GC.KeepAlive after passing a struct or class // that has a delegate field to native code. internal sealed class KeepAliveCleanupWorkListElement : CleanupWorkListElement { public KeepAliveCleanupWorkListElement(object obj) { m_obj = obj; } private object m_obj; protected override void DestroyCore() { GC.KeepAlive(m_obj); } } // Aggregates SafeHandle and the "owned" bit which indicates whether the SafeHandle // has been successfully AddRef'ed. This allows us to do realiable cleanup (Release) // if and only if it is needed. internal sealed class SafeHandleCleanupWorkListElement : CleanupWorkListElement { public SafeHandleCleanupWorkListElement(SafeHandle handle) { m_handle = handle; } private SafeHandle m_handle; // This field is passed by-ref to SafeHandle.DangerousAddRef. // DestroyCore ignores this element if m_owned is not set to true. private bool m_owned; protected override void DestroyCore() { if (m_owned) StubHelpers.SafeHandleRelease(m_handle); } public IntPtr AddRef() { // element.m_owned will be true iff the AddRef succeeded return StubHelpers.SafeHandleAddRef(m_handle, ref m_owned); } } // class CleanupWorkListElement internal static class StubHelpers { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetNDirectTarget(IntPtr pMD); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetDelegateTarget(Delegate pThis); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearLastError(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void SetLastError(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ThrowInteropParamException(int resID, int paramIdx); internal static IntPtr AddToCleanupList(ref CleanupWorkListElement? pCleanupWorkList, SafeHandle handle) { SafeHandleCleanupWorkListElement element = new SafeHandleCleanupWorkListElement(handle); CleanupWorkListElement.AddToCleanupList(ref pCleanupWorkList, element); return element.AddRef(); } internal static void KeepAliveViaCleanupList(ref CleanupWorkListElement? pCleanupWorkList, object obj) { KeepAliveCleanupWorkListElement element = new KeepAliveCleanupWorkListElement(obj); CleanupWorkListElement.AddToCleanupList(ref pCleanupWorkList, element); } internal static void DestroyCleanupList(ref CleanupWorkListElement? pCleanupWorkList) { if (pCleanupWorkList != null) { pCleanupWorkList.Destroy(); pCleanupWorkList = null; } } internal static Exception GetHRExceptionObject(int hr) { Exception ex = InternalGetHRExceptionObject(hr); ex.InternalPreserveStackTrace(); return ex; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Exception InternalGetHRExceptionObject(int hr); #if FEATURE_COMINTEROP internal static Exception GetCOMHRExceptionObject(int hr, IntPtr pCPCMD, object pThis) { Exception ex = InternalGetCOMHRExceptionObject(hr, pCPCMD, pThis); ex.InternalPreserveStackTrace(); return ex; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Exception InternalGetCOMHRExceptionObject(int hr, IntPtr pCPCMD, object? pThis); #endif // FEATURE_COMINTEROP [ThreadStatic] private static Exception? s_pendingExceptionObject; internal static Exception? GetPendingExceptionObject() { Exception? ex = s_pendingExceptionObject; if (ex != null) ex.InternalPreserveStackTrace(); s_pendingExceptionObject = null; return ex; } internal static void SetPendingExceptionObject(Exception? exception) { s_pendingExceptionObject = exception; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr CreateCustomMarshalerHelper(IntPtr pMD, int paramToken, IntPtr hndManagedType); //------------------------------------------------------- // SafeHandle Helpers //------------------------------------------------------- // AddRefs the SH and returns the underlying unmanaged handle. internal static IntPtr SafeHandleAddRef(SafeHandle pHandle, ref bool success) { if (pHandle == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pHandle, ExceptionResource.ArgumentNull_SafeHandle); } pHandle.DangerousAddRef(ref success); return pHandle.DangerousGetHandle(); } // Releases the SH (to be called from finally block). internal static void SafeHandleRelease(SafeHandle pHandle) { if (pHandle == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pHandle, ExceptionResource.ArgumentNull_SafeHandle); } pHandle.DangerousRelease(); } #if FEATURE_COMINTEROP [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetCOMIPFromRCW(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget, out bool pfNeedsRelease); #endif // FEATURE_COMINTEROP //------------------------------------------------------- // Profiler helpers //------------------------------------------------------- #if PROFILING_SUPPORTED [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr ProfilerBeginTransitionCallback(IntPtr pSecretParam, IntPtr pThread, object pThis); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ProfilerEndTransitionCallback(IntPtr pMD, IntPtr pThread); #endif // PROFILING_SUPPORTED //------------------------------------------------------ // misc //------------------------------------------------------ internal static void CheckStringLength(int length) { CheckStringLength((uint)length); } internal static void CheckStringLength(uint length) { if (length > 0x7ffffff0) { throw new MarshalDirectiveException(SR.Marshaler_StringTooLong); } } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern unsafe void FmtClassUpdateNativeInternal(object obj, byte* pNative, ref CleanupWorkListElement? pCleanupWorkList); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern unsafe void FmtClassUpdateCLRInternal(object obj, byte* pNative); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern unsafe void LayoutDestroyNativeInternal(object obj, byte* pNative); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern object AllocateInternal(IntPtr typeHandle); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void MarshalToUnmanagedVaListInternal(IntPtr va_list, uint vaListSize, IntPtr pArgIterator); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void MarshalToManagedVaListInternal(IntPtr va_list, IntPtr pArgIterator); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern uint CalcVaListSize(IntPtr va_list); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ValidateObject(object obj, IntPtr pMD, object pThis); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void LogPinnedArgument(IntPtr localDesc, IntPtr nativeArg); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ValidateByref(IntPtr byref, IntPtr pMD, object pThis); // the byref is pinned so we can safely "cast" it to IntPtr [Intrinsic] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetStubContext(); #if FEATURE_ARRAYSTUB_AS_IL [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ArrayTypeCheck(object o, object[] arr); #endif #if FEATURE_MULTICASTSTUB_AS_IL [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void MulticastDebuggerTraceHelper(object o, int count); #endif [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern IntPtr NextCallReturnAddress(); } // class StubHelpers }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Net.Mail/tests/Unit/ByteEncodingTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text; using Xunit; namespace System.Net.Mime.Tests { public class ByteEncodingTest { [Theory] [InlineData("some test header")] [InlineData("some test header that is really long some test header that is really long some test header that is really long some test header that is really long some test header")] public void EncodeHeader_WithNoUnicode_ShouldNotEncode(string testHeader) { string result = MimeBasePart.EncodeHeaderValue(testHeader, Encoding.UTF8, true); Assert.StartsWith("some test", result, StringComparison.Ordinal); Assert.EndsWith("header", result, StringComparison.Ordinal); foreach (char c in result) { Assert.InRange((byte)c, 0, 128); } Assert.Equal(testHeader, MimeBasePart.DecodeHeaderValue(result)); } [Theory] [InlineData("some test h\xE9ader to base64asdf\xE9\xE5", 1)] [InlineData("some test header to base64 \xE5 \xF8\xEE asdf\xE9encode that contains some unicodeasdf\xE9\xE5 and is really really long and stuff ", 3)] public void EncoderAndDecoder_ShouldEncodeAndDecode(string testHeader, int expectedFoldedCount) { string result = MimeBasePart.EncodeHeaderValue(testHeader, Encoding.UTF8, true); Assert.StartsWith("=?utf-8?B?", result, StringComparison.Ordinal); Assert.EndsWith("?=", result, StringComparison.Ordinal); string[] foldedHeaders = result.Split('\r'); Assert.Equal(expectedFoldedCount, foldedHeaders.Length); foreach (string foldedHeader in foldedHeaders) { Assert.InRange(foldedHeader.Length, 0, 76); } Assert.Equal(testHeader, MimeBasePart.DecodeHeaderValue(result)); } [Theory] [InlineData("some test header to base64", 1)] [InlineData("some test header to base64asdf \xE9\xE5 encode that contains some unicode \xE5 \xF8\xEE asdf\xE9\xE5 and is really really long and stuff ", 3)] public void EncoderAndDecoder_WithQEncodedString_AndNoUnicode_AndShortHeader_ShouldEncodeAndDecode( string testHeader, int expectedFoldedCount) { string result = MimeBasePart.EncodeHeaderValue(testHeader, Encoding.UTF8, false); string[] foldedHeaders = result.Split(new string[] { "\r\n " }, StringSplitOptions.RemoveEmptyEntries); Assert.Equal(expectedFoldedCount, foldedHeaders.Length); foreach (string foldedHeader in foldedHeaders) { Assert.InRange(foldedHeader.Length, 0, 76); } Assert.Equal(testHeader, MimeBasePart.DecodeHeaderValue(result)); } [Fact] public void EncodeHeader_Base64Encoding_ShouldSplitBetweenCodepoints() { // header parts split by max line length in base64 encoding = 70 with respect to codepoints string headerPart1 = "Emoji subject : 🕐🕑🕒🕓🕔🕕"; string headerPart2 = "🕖🕗🕘🕙🕚"; string longEmojiHeader = headerPart1 + headerPart2; string encodedHeader = MimeBasePart.EncodeHeaderValue(longEmojiHeader, Encoding.UTF8, true); string encodedPart1 = MimeBasePart.EncodeHeaderValue(headerPart1, Encoding.UTF8, true); string encodedPart2 = MimeBasePart.EncodeHeaderValue(headerPart2, Encoding.UTF8, true); Assert.Equal("=?utf-8?B?RW1vamkgc3ViamVjdCA6IPCflZDwn5WR8J+VkvCflZPwn5WU8J+VlQ==?=", encodedPart1); Assert.Equal("=?utf-8?B?8J+VlvCflZfwn5WY8J+VmfCflZo=?=", encodedPart2); string expectedEncodedHeader = encodedPart1 + "\r\n " + encodedPart2; Assert.Equal(expectedEncodedHeader, encodedHeader); } [Fact] public void EncodeHeader_QEncoding_ShouldSplitBetweenCodepoints() { // header parts split by max line length in q-encoding = 70 with respect to codepoints string headerPart1 = "Emoji subject : 🕐🕑🕒"; string headerPart2 = "🕓🕔🕕🕖"; string headerPart3 = "🕗🕘🕙🕚"; string longEmojiHeader = headerPart1 + headerPart2 + headerPart3; string encodedHeader = MimeBasePart.EncodeHeaderValue(longEmojiHeader, Encoding.UTF8, false); string encodedPart1 = MimeBasePart.EncodeHeaderValue(headerPart1, Encoding.UTF8, false); string encodedPart2 = MimeBasePart.EncodeHeaderValue(headerPart2, Encoding.UTF8, false); string encodedPart3 = MimeBasePart.EncodeHeaderValue(headerPart3, Encoding.UTF8, false); Assert.Equal("=?utf-8?Q?Emoji_subject_=3A_=F0=9F=95=90=F0=9F=95=91=F0=9F=95=92?=", encodedPart1); Assert.Equal("=?utf-8?Q?=F0=9F=95=93=F0=9F=95=94=F0=9F=95=95=F0=9F=95=96?=", encodedPart2); Assert.Equal("=?utf-8?Q?=F0=9F=95=97=F0=9F=95=98=F0=9F=95=99=F0=9F=95=9A?=", encodedPart3); string expectedEncodedHeader = encodedPart1 + "\r\n " + encodedPart2 + "\r\n " + encodedPart3; Assert.Equal(expectedEncodedHeader, encodedHeader); } [Theory] [InlineData(false, "🕐11111111111111111111111111111111111111111111:1111")] [InlineData(false, "🕐111111111111111111111111111111111111111111111:111")] [InlineData(false, "🕐1111111111111111111111111111111111111111111111:11")] [InlineData(false, "🕐11111111111111111111111111111111111111111\r\n1111")] [InlineData(false, "🕐111111111111111111111111111111111111111111\r\n111")] [InlineData(false, "🕐1111111111111111111111111111111111111111111\r\n11")] [InlineData(true, "Emoji subject : 🕐🕑🕒🕓🕔🕕:11111")] [InlineData(true, "Emoji subject : 🕐🕑🕒🕓🕔🕕\r\n11")] public void EncodeString_IsSameAsEncodeBytes_IfOneByteCodepointOnLineWrap(bool useBase64Encoding, string value) { var factory = new EncodedStreamFactory(); IEncodableStream streamForEncodeString = factory.GetEncoderForHeader(Encoding.UTF8, useBase64Encoding, 0); IEncodableStream streamForEncodeBytes = factory.GetEncoderForHeader(Encoding.UTF8, useBase64Encoding, 0); streamForEncodeString.EncodeString(value, Encoding.UTF8); string encodeStringResult = streamForEncodeString.GetEncodedString(); byte[] bytes = Encoding.UTF8.GetBytes(value); streamForEncodeBytes.EncodeBytes(bytes, 0, bytes.Length); string encodeBytesResult = streamForEncodeBytes.GetEncodedString(); Assert.Equal(encodeBytesResult, encodeStringResult); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text; using Xunit; namespace System.Net.Mime.Tests { public class ByteEncodingTest { [Theory] [InlineData("some test header")] [InlineData("some test header that is really long some test header that is really long some test header that is really long some test header that is really long some test header")] public void EncodeHeader_WithNoUnicode_ShouldNotEncode(string testHeader) { string result = MimeBasePart.EncodeHeaderValue(testHeader, Encoding.UTF8, true); Assert.StartsWith("some test", result, StringComparison.Ordinal); Assert.EndsWith("header", result, StringComparison.Ordinal); foreach (char c in result) { Assert.InRange((byte)c, 0, 128); } Assert.Equal(testHeader, MimeBasePart.DecodeHeaderValue(result)); } [Theory] [InlineData("some test h\xE9ader to base64asdf\xE9\xE5", 1)] [InlineData("some test header to base64 \xE5 \xF8\xEE asdf\xE9encode that contains some unicodeasdf\xE9\xE5 and is really really long and stuff ", 3)] public void EncoderAndDecoder_ShouldEncodeAndDecode(string testHeader, int expectedFoldedCount) { string result = MimeBasePart.EncodeHeaderValue(testHeader, Encoding.UTF8, true); Assert.StartsWith("=?utf-8?B?", result, StringComparison.Ordinal); Assert.EndsWith("?=", result, StringComparison.Ordinal); string[] foldedHeaders = result.Split('\r'); Assert.Equal(expectedFoldedCount, foldedHeaders.Length); foreach (string foldedHeader in foldedHeaders) { Assert.InRange(foldedHeader.Length, 0, 76); } Assert.Equal(testHeader, MimeBasePart.DecodeHeaderValue(result)); } [Theory] [InlineData("some test header to base64", 1)] [InlineData("some test header to base64asdf \xE9\xE5 encode that contains some unicode \xE5 \xF8\xEE asdf\xE9\xE5 and is really really long and stuff ", 3)] public void EncoderAndDecoder_WithQEncodedString_AndNoUnicode_AndShortHeader_ShouldEncodeAndDecode( string testHeader, int expectedFoldedCount) { string result = MimeBasePart.EncodeHeaderValue(testHeader, Encoding.UTF8, false); string[] foldedHeaders = result.Split(new string[] { "\r\n " }, StringSplitOptions.RemoveEmptyEntries); Assert.Equal(expectedFoldedCount, foldedHeaders.Length); foreach (string foldedHeader in foldedHeaders) { Assert.InRange(foldedHeader.Length, 0, 76); } Assert.Equal(testHeader, MimeBasePart.DecodeHeaderValue(result)); } [Fact] public void EncodeHeader_Base64Encoding_ShouldSplitBetweenCodepoints() { // header parts split by max line length in base64 encoding = 70 with respect to codepoints string headerPart1 = "Emoji subject : 🕐🕑🕒🕓🕔🕕"; string headerPart2 = "🕖🕗🕘🕙🕚"; string longEmojiHeader = headerPart1 + headerPart2; string encodedHeader = MimeBasePart.EncodeHeaderValue(longEmojiHeader, Encoding.UTF8, true); string encodedPart1 = MimeBasePart.EncodeHeaderValue(headerPart1, Encoding.UTF8, true); string encodedPart2 = MimeBasePart.EncodeHeaderValue(headerPart2, Encoding.UTF8, true); Assert.Equal("=?utf-8?B?RW1vamkgc3ViamVjdCA6IPCflZDwn5WR8J+VkvCflZPwn5WU8J+VlQ==?=", encodedPart1); Assert.Equal("=?utf-8?B?8J+VlvCflZfwn5WY8J+VmfCflZo=?=", encodedPart2); string expectedEncodedHeader = encodedPart1 + "\r\n " + encodedPart2; Assert.Equal(expectedEncodedHeader, encodedHeader); } [Fact] public void EncodeHeader_QEncoding_ShouldSplitBetweenCodepoints() { // header parts split by max line length in q-encoding = 70 with respect to codepoints string headerPart1 = "Emoji subject : 🕐🕑🕒"; string headerPart2 = "🕓🕔🕕🕖"; string headerPart3 = "🕗🕘🕙🕚"; string longEmojiHeader = headerPart1 + headerPart2 + headerPart3; string encodedHeader = MimeBasePart.EncodeHeaderValue(longEmojiHeader, Encoding.UTF8, false); string encodedPart1 = MimeBasePart.EncodeHeaderValue(headerPart1, Encoding.UTF8, false); string encodedPart2 = MimeBasePart.EncodeHeaderValue(headerPart2, Encoding.UTF8, false); string encodedPart3 = MimeBasePart.EncodeHeaderValue(headerPart3, Encoding.UTF8, false); Assert.Equal("=?utf-8?Q?Emoji_subject_=3A_=F0=9F=95=90=F0=9F=95=91=F0=9F=95=92?=", encodedPart1); Assert.Equal("=?utf-8?Q?=F0=9F=95=93=F0=9F=95=94=F0=9F=95=95=F0=9F=95=96?=", encodedPart2); Assert.Equal("=?utf-8?Q?=F0=9F=95=97=F0=9F=95=98=F0=9F=95=99=F0=9F=95=9A?=", encodedPart3); string expectedEncodedHeader = encodedPart1 + "\r\n " + encodedPart2 + "\r\n " + encodedPart3; Assert.Equal(expectedEncodedHeader, encodedHeader); } [Theory] [InlineData(false, "🕐11111111111111111111111111111111111111111111:1111")] [InlineData(false, "🕐111111111111111111111111111111111111111111111:111")] [InlineData(false, "🕐1111111111111111111111111111111111111111111111:11")] [InlineData(false, "🕐11111111111111111111111111111111111111111\r\n1111")] [InlineData(false, "🕐111111111111111111111111111111111111111111\r\n111")] [InlineData(false, "🕐1111111111111111111111111111111111111111111\r\n11")] [InlineData(true, "Emoji subject : 🕐🕑🕒🕓🕔🕕:11111")] [InlineData(true, "Emoji subject : 🕐🕑🕒🕓🕔🕕\r\n11")] public void EncodeString_IsSameAsEncodeBytes_IfOneByteCodepointOnLineWrap(bool useBase64Encoding, string value) { var factory = new EncodedStreamFactory(); IEncodableStream streamForEncodeString = factory.GetEncoderForHeader(Encoding.UTF8, useBase64Encoding, 0); IEncodableStream streamForEncodeBytes = factory.GetEncoderForHeader(Encoding.UTF8, useBase64Encoding, 0); streamForEncodeString.EncodeString(value, Encoding.UTF8); string encodeStringResult = streamForEncodeString.GetEncodedString(); byte[] bytes = Encoding.UTF8.GetBytes(value); streamForEncodeBytes.EncodeBytes(bytes, 0, bytes.Length); string encodeBytesResult = streamForEncodeBytes.GetEncodedString(); Assert.Equal(encodeBytesResult, encodeStringResult); } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/opt/CSE/GitHub_16065b.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace GitHub_16065b { struct Array2D { public int Offset; public int LeadingDimension; public Array2D(int offset, int leadingDimension) { Offset = offset; LeadingDimension = leadingDimension; } public int GetIndex(int row, int column) { return this.Offset + row + this.LeadingDimension * column; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public ArraySlice Diagonal(int index) { int offset = (index > 0) ? GetIndex(0, index) : GetIndex(-index, 0); // The problem is with this line: int stride = this.LeadingDimension + 1; return new ArraySlice(offset, stride); } public ArraySlice GetStride(int index) { int offset = (index > 0) ? GetIndex(0, index) : GetIndex(-index, 0); // The problem is with this line, when inlined: int stride = this.LeadingDimension + 1; return new ArraySlice(offset, stride); } } struct ArraySlice { public int Offset; public int Stride; public ArraySlice(int offset, int stride) { Offset = offset; Stride = stride; } } class Vector { public ArraySlice Storage; public Vector(ArraySlice storage) { Storage = storage; } } class Matrix { public Array2D Storage; public Matrix(Array2D storage) { Storage = storage; } public Vector GetDiagonal(int index) { ArraySlice storage = this.Storage.Diagonal(index); return new Vector(storage); } } class Program { static int Main(string[] args) { int result = 0; var A = new Matrix(new Array2D(0, 4)); var d = A.GetDiagonal(0); Console.WriteLine("Expected: 0:5"); Console.WriteLine("Actual: {0}:{1}", d.Storage.Offset, d.Storage.Stride); if ((d.Storage.Offset == 0) && (d.Storage.Stride == 5)) { Console.WriteLine("PASSED"); result = 100; } else { Console.WriteLine("FAILED"); result = 101; } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace GitHub_16065b { struct Array2D { public int Offset; public int LeadingDimension; public Array2D(int offset, int leadingDimension) { Offset = offset; LeadingDimension = leadingDimension; } public int GetIndex(int row, int column) { return this.Offset + row + this.LeadingDimension * column; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public ArraySlice Diagonal(int index) { int offset = (index > 0) ? GetIndex(0, index) : GetIndex(-index, 0); // The problem is with this line: int stride = this.LeadingDimension + 1; return new ArraySlice(offset, stride); } public ArraySlice GetStride(int index) { int offset = (index > 0) ? GetIndex(0, index) : GetIndex(-index, 0); // The problem is with this line, when inlined: int stride = this.LeadingDimension + 1; return new ArraySlice(offset, stride); } } struct ArraySlice { public int Offset; public int Stride; public ArraySlice(int offset, int stride) { Offset = offset; Stride = stride; } } class Vector { public ArraySlice Storage; public Vector(ArraySlice storage) { Storage = storage; } } class Matrix { public Array2D Storage; public Matrix(Array2D storage) { Storage = storage; } public Vector GetDiagonal(int index) { ArraySlice storage = this.Storage.Diagonal(index); return new Vector(storage); } } class Program { static int Main(string[] args) { int result = 0; var A = new Matrix(new Array2D(0, 4)); var d = A.GetDiagonal(0); Console.WriteLine("Expected: 0:5"); Console.WriteLine("Actual: {0}:{1}", d.Storage.Offset, d.Storage.Stride); if ((d.Storage.Offset == 0) && (d.Storage.Stride == 5)) { Console.WriteLine("PASSED"); result = 100; } else { Console.WriteLine("FAILED"); result = 101; } return result; } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Threading.Tasks/tests/Task/TaskCompletionSourceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Linq; using Xunit; namespace System.Threading.Tasks.Tests.Status { public sealed class TaskCompletionSourceTests { [Fact] public void Ctor_ArgumentsRoundtrip() { TaskCompletionSource tcs; object stateObj = new object(); tcs = new TaskCompletionSource(); Assert.NotNull(tcs.Task); Assert.Same(tcs.Task, tcs.Task); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); Assert.Null(tcs.Task.AsyncState); tcs = new TaskCompletionSource(stateObj); Assert.NotNull(tcs.Task); Assert.Same(tcs.Task, tcs.Task); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); Assert.Same(stateObj, tcs.Task.AsyncState); tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); Assert.NotNull(tcs.Task); Assert.Same(tcs.Task, tcs.Task); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); Assert.Equal(TaskCreationOptions.RunContinuationsAsynchronously, tcs.Task.CreationOptions); Assert.Null(tcs.Task.AsyncState); tcs = new TaskCompletionSource(stateObj, TaskCreationOptions.RunContinuationsAsynchronously); Assert.NotNull(tcs.Task); Assert.Same(tcs.Task, tcs.Task); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); Assert.Equal(TaskCreationOptions.RunContinuationsAsynchronously, tcs.Task.CreationOptions); Assert.Same(stateObj, tcs.Task.AsyncState); } [Fact] public void Ctor_InvalidArguments_Throws() { // These shouldn't throw. new TaskCompletionSource(TaskCreationOptions.AttachedToParent); new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); new TaskCompletionSource(TaskCreationOptions.AttachedToParent | TaskCreationOptions.RunContinuationsAsynchronously); new TaskCompletionSource(new object(), TaskCreationOptions.AttachedToParent); new TaskCompletionSource(new object(), TaskCreationOptions.RunContinuationsAsynchronously); new TaskCompletionSource(new object(), TaskCreationOptions.AttachedToParent | TaskCreationOptions.RunContinuationsAsynchronously); // These should throw. foreach (TaskCreationOptions options in Enum.GetValues(typeof(TaskCreationOptions))) { if ((options & TaskCreationOptions.AttachedToParent) != 0 && (options & TaskCreationOptions.RunContinuationsAsynchronously) != 0) { AssertExtensions.Throws<ArgumentOutOfRangeException>("creationOptions", () => new TaskCompletionSource(options)); AssertExtensions.Throws<ArgumentOutOfRangeException>("creationOptions", () => new TaskCompletionSource(options | TaskCreationOptions.RunContinuationsAsynchronously)); AssertExtensions.Throws<ArgumentOutOfRangeException>("creationOptions", () => new TaskCompletionSource(new object(), options)); AssertExtensions.Throws<ArgumentOutOfRangeException>("creationOptions", () => new TaskCompletionSource(new object(), options | TaskCreationOptions.RunContinuationsAsynchronously)); } } } [Theory] [InlineData(false)] [InlineData(true)] public void SetResult_CompletesSuccessfully(bool tryMethod) { var tcs = new TaskCompletionSource(); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); if (tryMethod) { Assert.True(tcs.TrySetResult()); } else { tcs.SetResult(); } Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status); AssertCompletedTcsFailsToCompleteAgain(tcs); } [Theory] [InlineData(false)] [InlineData(true)] public void SetCanceled_CompletesSuccessfully(bool tryMethod) { var tcs = new TaskCompletionSource(); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); if (tryMethod) { Assert.True(tcs.TrySetCanceled()); } else { tcs.SetCanceled(); } Assert.Equal(TaskStatus.Canceled, tcs.Task.Status); Assert.Null(tcs.Task.Exception); TaskCanceledException tce = Assert.Throws<TaskCanceledException>(() => tcs.Task.GetAwaiter().GetResult()); Assert.Equal(default, tce.CancellationToken); AssertCompletedTcsFailsToCompleteAgain(tcs); } [Theory] [InlineData(false)] [InlineData(true)] public void SetCanceled_Token_CompletesSuccessfully(bool tryMethod) { var tcs = new TaskCompletionSource(); var cts = new CancellationTokenSource(); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); if (tryMethod) { Assert.True(tcs.TrySetCanceled(cts.Token)); } else { tcs.SetCanceled(cts.Token); } Assert.Equal(TaskStatus.Canceled, tcs.Task.Status); Assert.Null(tcs.Task.Exception); TaskCanceledException tce = Assert.Throws<TaskCanceledException>(() => tcs.Task.GetAwaiter().GetResult()); Assert.Equal(cts.Token, tce.CancellationToken); AssertCompletedTcsFailsToCompleteAgain(tcs); } [Theory] [InlineData(false)] [InlineData(true)] public void SetException_Exception_CompletesSuccessfully(bool tryMethod) { var e = new Exception(); var tcs = new TaskCompletionSource(); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); if (tryMethod) { Assert.True(tcs.TrySetException(e)); } else { tcs.SetException(e); } Assert.Equal(TaskStatus.Faulted, tcs.Task.Status); Assert.NotNull(tcs.Task.Exception); Assert.Same(e, tcs.Task.Exception.InnerException); Assert.Equal(1, tcs.Task.Exception.InnerExceptions.Count); AssertCompletedTcsFailsToCompleteAgain(tcs); } [Theory] [InlineData(false)] [InlineData(true)] public void SetException_Enumerable_CompletesSuccessfully(bool tryMethod) { var e = new Exception[] { new FormatException(), new InvalidOperationException(), new ArgumentException() }; var tcs = new TaskCompletionSource(); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); if (tryMethod) { Assert.True(tcs.TrySetException(e)); } else { tcs.SetException(e); } Assert.Equal(TaskStatus.Faulted, tcs.Task.Status); Assert.NotNull(tcs.Task.Exception); Assert.Equal(e, tcs.Task.Exception.InnerExceptions); AssertCompletedTcsFailsToCompleteAgain(tcs); } private static void AssertCompletedTcsFailsToCompleteAgain(TaskCompletionSource tcs) { Assert.Throws<InvalidOperationException>(() => tcs.SetResult()); Assert.False(tcs.TrySetResult()); Assert.Throws<InvalidOperationException>(() => tcs.SetException(new Exception())); Assert.Throws<InvalidOperationException>(() => tcs.SetException(Enumerable.Repeat(new Exception(), 1))); Assert.False(tcs.TrySetException(new Exception())); Assert.False(tcs.TrySetException(Enumerable.Repeat(new Exception(), 1))); Assert.Throws<InvalidOperationException>(() => tcs.SetCanceled()); Assert.Throws<InvalidOperationException>(() => tcs.SetCanceled(default)); Assert.False(tcs.TrySetCanceled()); Assert.False(tcs.TrySetCanceled(default)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Linq; using Xunit; namespace System.Threading.Tasks.Tests.Status { public sealed class TaskCompletionSourceTests { [Fact] public void Ctor_ArgumentsRoundtrip() { TaskCompletionSource tcs; object stateObj = new object(); tcs = new TaskCompletionSource(); Assert.NotNull(tcs.Task); Assert.Same(tcs.Task, tcs.Task); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); Assert.Null(tcs.Task.AsyncState); tcs = new TaskCompletionSource(stateObj); Assert.NotNull(tcs.Task); Assert.Same(tcs.Task, tcs.Task); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); Assert.Same(stateObj, tcs.Task.AsyncState); tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); Assert.NotNull(tcs.Task); Assert.Same(tcs.Task, tcs.Task); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); Assert.Equal(TaskCreationOptions.RunContinuationsAsynchronously, tcs.Task.CreationOptions); Assert.Null(tcs.Task.AsyncState); tcs = new TaskCompletionSource(stateObj, TaskCreationOptions.RunContinuationsAsynchronously); Assert.NotNull(tcs.Task); Assert.Same(tcs.Task, tcs.Task); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); Assert.Equal(TaskCreationOptions.RunContinuationsAsynchronously, tcs.Task.CreationOptions); Assert.Same(stateObj, tcs.Task.AsyncState); } [Fact] public void Ctor_InvalidArguments_Throws() { // These shouldn't throw. new TaskCompletionSource(TaskCreationOptions.AttachedToParent); new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); new TaskCompletionSource(TaskCreationOptions.AttachedToParent | TaskCreationOptions.RunContinuationsAsynchronously); new TaskCompletionSource(new object(), TaskCreationOptions.AttachedToParent); new TaskCompletionSource(new object(), TaskCreationOptions.RunContinuationsAsynchronously); new TaskCompletionSource(new object(), TaskCreationOptions.AttachedToParent | TaskCreationOptions.RunContinuationsAsynchronously); // These should throw. foreach (TaskCreationOptions options in Enum.GetValues(typeof(TaskCreationOptions))) { if ((options & TaskCreationOptions.AttachedToParent) != 0 && (options & TaskCreationOptions.RunContinuationsAsynchronously) != 0) { AssertExtensions.Throws<ArgumentOutOfRangeException>("creationOptions", () => new TaskCompletionSource(options)); AssertExtensions.Throws<ArgumentOutOfRangeException>("creationOptions", () => new TaskCompletionSource(options | TaskCreationOptions.RunContinuationsAsynchronously)); AssertExtensions.Throws<ArgumentOutOfRangeException>("creationOptions", () => new TaskCompletionSource(new object(), options)); AssertExtensions.Throws<ArgumentOutOfRangeException>("creationOptions", () => new TaskCompletionSource(new object(), options | TaskCreationOptions.RunContinuationsAsynchronously)); } } } [Theory] [InlineData(false)] [InlineData(true)] public void SetResult_CompletesSuccessfully(bool tryMethod) { var tcs = new TaskCompletionSource(); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); if (tryMethod) { Assert.True(tcs.TrySetResult()); } else { tcs.SetResult(); } Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status); AssertCompletedTcsFailsToCompleteAgain(tcs); } [Theory] [InlineData(false)] [InlineData(true)] public void SetCanceled_CompletesSuccessfully(bool tryMethod) { var tcs = new TaskCompletionSource(); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); if (tryMethod) { Assert.True(tcs.TrySetCanceled()); } else { tcs.SetCanceled(); } Assert.Equal(TaskStatus.Canceled, tcs.Task.Status); Assert.Null(tcs.Task.Exception); TaskCanceledException tce = Assert.Throws<TaskCanceledException>(() => tcs.Task.GetAwaiter().GetResult()); Assert.Equal(default, tce.CancellationToken); AssertCompletedTcsFailsToCompleteAgain(tcs); } [Theory] [InlineData(false)] [InlineData(true)] public void SetCanceled_Token_CompletesSuccessfully(bool tryMethod) { var tcs = new TaskCompletionSource(); var cts = new CancellationTokenSource(); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); if (tryMethod) { Assert.True(tcs.TrySetCanceled(cts.Token)); } else { tcs.SetCanceled(cts.Token); } Assert.Equal(TaskStatus.Canceled, tcs.Task.Status); Assert.Null(tcs.Task.Exception); TaskCanceledException tce = Assert.Throws<TaskCanceledException>(() => tcs.Task.GetAwaiter().GetResult()); Assert.Equal(cts.Token, tce.CancellationToken); AssertCompletedTcsFailsToCompleteAgain(tcs); } [Theory] [InlineData(false)] [InlineData(true)] public void SetException_Exception_CompletesSuccessfully(bool tryMethod) { var e = new Exception(); var tcs = new TaskCompletionSource(); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); if (tryMethod) { Assert.True(tcs.TrySetException(e)); } else { tcs.SetException(e); } Assert.Equal(TaskStatus.Faulted, tcs.Task.Status); Assert.NotNull(tcs.Task.Exception); Assert.Same(e, tcs.Task.Exception.InnerException); Assert.Equal(1, tcs.Task.Exception.InnerExceptions.Count); AssertCompletedTcsFailsToCompleteAgain(tcs); } [Theory] [InlineData(false)] [InlineData(true)] public void SetException_Enumerable_CompletesSuccessfully(bool tryMethod) { var e = new Exception[] { new FormatException(), new InvalidOperationException(), new ArgumentException() }; var tcs = new TaskCompletionSource(); Assert.Equal(TaskStatus.WaitingForActivation, tcs.Task.Status); if (tryMethod) { Assert.True(tcs.TrySetException(e)); } else { tcs.SetException(e); } Assert.Equal(TaskStatus.Faulted, tcs.Task.Status); Assert.NotNull(tcs.Task.Exception); Assert.Equal(e, tcs.Task.Exception.InnerExceptions); AssertCompletedTcsFailsToCompleteAgain(tcs); } private static void AssertCompletedTcsFailsToCompleteAgain(TaskCompletionSource tcs) { Assert.Throws<InvalidOperationException>(() => tcs.SetResult()); Assert.False(tcs.TrySetResult()); Assert.Throws<InvalidOperationException>(() => tcs.SetException(new Exception())); Assert.Throws<InvalidOperationException>(() => tcs.SetException(Enumerable.Repeat(new Exception(), 1))); Assert.False(tcs.TrySetException(new Exception())); Assert.False(tcs.TrySetException(Enumerable.Repeat(new Exception(), 1))); Assert.Throws<InvalidOperationException>(() => tcs.SetCanceled()); Assert.Throws<InvalidOperationException>(() => tcs.SetCanceled(default)); Assert.False(tcs.TrySetCanceled()); Assert.False(tcs.TrySetCanceled(default)); } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/BitwiseSelect.Vector128.Int16.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void BitwiseSelect_Vector128_Int16() { var test = new SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] inArray3, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int16, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int16> _fld1; public Vector128<Int16> _fld2; public Vector128<Int16> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16 testClass) { var result = AdvSimd.BitwiseSelect(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) fixed (Vector128<Int16>* pFld3 = &_fld3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Int16[] _data3 = new Int16[Op3ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private static Vector128<Int16> _clsVar3; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private Vector128<Int16> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.BitwiseSelect( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.BitwiseSelect), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.BitwiseSelect), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.BitwiseSelect( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<Int16>* pClsVar2 = &_clsVar2) fixed (Vector128<Int16>* pClsVar3 = &_clsVar3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int16*)(pClsVar1)), AdvSimd.LoadVector128((Int16*)(pClsVar2)), AdvSimd.LoadVector128((Int16*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr); var result = AdvSimd.BitwiseSelect(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)); var result = AdvSimd.BitwiseSelect(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16(); var result = AdvSimd.BitwiseSelect(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<Int16>* pFld2 = &test._fld2) fixed (Vector128<Int16>* pFld3 = &test._fld3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.BitwiseSelect(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) fixed (Vector128<Int16>* pFld3 = &_fld3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.BitwiseSelect(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int16*)(&test._fld1)), AdvSimd.LoadVector128((Int16*)(&test._fld2)), AdvSimd.LoadVector128((Int16*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, Vector128<Int16> op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] inArray3 = new Int16[Op3ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] inArray3 = new Int16[Op3ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] secondOp, Int16[] thirdOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.BitwiseSelect(firstOp[i], secondOp[i], thirdOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.BitwiseSelect)}<Int16>(Vector128<Int16>, Vector128<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void BitwiseSelect_Vector128_Int16() { var test = new SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] inArray3, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int16, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int16> _fld1; public Vector128<Int16> _fld2; public Vector128<Int16> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16 testClass) { var result = AdvSimd.BitwiseSelect(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) fixed (Vector128<Int16>* pFld3 = &_fld3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Int16[] _data3 = new Int16[Op3ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private static Vector128<Int16> _clsVar3; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private Vector128<Int16> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.BitwiseSelect( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.BitwiseSelect), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.BitwiseSelect), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.BitwiseSelect( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<Int16>* pClsVar2 = &_clsVar2) fixed (Vector128<Int16>* pClsVar3 = &_clsVar3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int16*)(pClsVar1)), AdvSimd.LoadVector128((Int16*)(pClsVar2)), AdvSimd.LoadVector128((Int16*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr); var result = AdvSimd.BitwiseSelect(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)); var result = AdvSimd.BitwiseSelect(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16(); var result = AdvSimd.BitwiseSelect(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__BitwiseSelect_Vector128_Int16(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<Int16>* pFld2 = &test._fld2) fixed (Vector128<Int16>* pFld3 = &test._fld3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.BitwiseSelect(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) fixed (Vector128<Int16>* pFld3 = &_fld3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.BitwiseSelect(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int16*)(&test._fld1)), AdvSimd.LoadVector128((Int16*)(&test._fld2)), AdvSimd.LoadVector128((Int16*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, Vector128<Int16> op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] inArray3 = new Int16[Op3ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] inArray3 = new Int16[Op3ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] secondOp, Int16[] thirdOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.BitwiseSelect(firstOp[i], secondOp[i], thirdOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.BitwiseSelect)}<Int16>(Vector128<Int16>, Vector128<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/baseservices/exceptions/regressions/V1/SEH/VJ/HandlerException.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> <!-- The test can have threads running at exit --> <UnloadabilityIncompatible>true</UnloadabilityIncompatible> </PropertyGroup> <ItemGroup> <Compile Include="HandlerException.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> <!-- The test can have threads running at exit --> <UnloadabilityIncompatible>true</UnloadabilityIncompatible> </PropertyGroup> <ItemGroup> <Compile Include="HandlerException.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Reflection.Metadata/tests/PortableExecutable/SectionHeaderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Text; using Xunit; namespace System.Reflection.PortableExecutable.Tests { public class SectionHeaderTests { [Theory] [InlineData(".debug", 0, 0, 0x5C, 0x152, 0, 0, 0, 0, SectionCharacteristics.LinkerInfo)] [InlineData(".drectve", 0, 0, 26, 0x12C, 0, 0, 0, 0, SectionCharacteristics.Align1Bytes)] [InlineData("", 1, 1, 2, 3, 5, 8, 13, 21, SectionCharacteristics.Align16Bytes)] [InlineData("x", 1, 1, 2, 3, 5, 8, 13, 21, SectionCharacteristics.MemSysheap)] [InlineData(".\u092c\u0917", int.MaxValue, int.MinValue, int.MaxValue, int.MinValue, int.MaxValue, int.MaxValue, ushort.MaxValue, ushort.MaxValue, SectionCharacteristics.GPRel)] [InlineData("nul\u0000nul", 1, 1, 1, 1, 1, 1, 1, 1, SectionCharacteristics.ContainsInitializedData)] public void Ctor( string name, int virtualSize, int virtualAddress, int sizeOfRawData, int ptrToRawData, int ptrToRelocations, int ptrToLineNumbers, ushort numRelocations, ushort numLineNumbers, SectionCharacteristics characteristics) { var stream = new MemoryStream(); var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); writer.Write(PadSectionName(name)); writer.Write(virtualSize); writer.Write(virtualAddress); writer.Write(sizeOfRawData); writer.Write(ptrToRawData); writer.Write(ptrToRelocations); writer.Write(ptrToLineNumbers); writer.Write(numRelocations); writer.Write(numLineNumbers); writer.Write((uint) characteristics); writer.Dispose(); stream.Position = 0; var reader = new PEBinaryReader(stream, (int) stream.Length); var header = new SectionHeader(ref reader); Assert.Equal(name, header.Name); Assert.Equal(virtualSize, header.VirtualSize); Assert.Equal(virtualAddress, header.VirtualAddress); Assert.Equal(sizeOfRawData, header.SizeOfRawData); Assert.Equal(ptrToRawData, header.PointerToRawData); Assert.Equal(ptrToLineNumbers, header.PointerToLineNumbers); Assert.Equal(numRelocations, header.NumberOfRelocations); Assert.Equal(numLineNumbers, header.NumberOfLineNumbers); Assert.Equal(characteristics, header.SectionCharacteristics); } private static byte[] PadSectionName(string name) { var nameBytes = Encoding.UTF8.GetBytes(name); Assert.True(name.Length <= SectionHeader.NameSize); var bytes = new byte[SectionHeader.NameSize]; Buffer.BlockCopy(nameBytes, 0, bytes, 0, nameBytes.Length); return bytes; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Text; using Xunit; namespace System.Reflection.PortableExecutable.Tests { public class SectionHeaderTests { [Theory] [InlineData(".debug", 0, 0, 0x5C, 0x152, 0, 0, 0, 0, SectionCharacteristics.LinkerInfo)] [InlineData(".drectve", 0, 0, 26, 0x12C, 0, 0, 0, 0, SectionCharacteristics.Align1Bytes)] [InlineData("", 1, 1, 2, 3, 5, 8, 13, 21, SectionCharacteristics.Align16Bytes)] [InlineData("x", 1, 1, 2, 3, 5, 8, 13, 21, SectionCharacteristics.MemSysheap)] [InlineData(".\u092c\u0917", int.MaxValue, int.MinValue, int.MaxValue, int.MinValue, int.MaxValue, int.MaxValue, ushort.MaxValue, ushort.MaxValue, SectionCharacteristics.GPRel)] [InlineData("nul\u0000nul", 1, 1, 1, 1, 1, 1, 1, 1, SectionCharacteristics.ContainsInitializedData)] public void Ctor( string name, int virtualSize, int virtualAddress, int sizeOfRawData, int ptrToRawData, int ptrToRelocations, int ptrToLineNumbers, ushort numRelocations, ushort numLineNumbers, SectionCharacteristics characteristics) { var stream = new MemoryStream(); var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); writer.Write(PadSectionName(name)); writer.Write(virtualSize); writer.Write(virtualAddress); writer.Write(sizeOfRawData); writer.Write(ptrToRawData); writer.Write(ptrToRelocations); writer.Write(ptrToLineNumbers); writer.Write(numRelocations); writer.Write(numLineNumbers); writer.Write((uint) characteristics); writer.Dispose(); stream.Position = 0; var reader = new PEBinaryReader(stream, (int) stream.Length); var header = new SectionHeader(ref reader); Assert.Equal(name, header.Name); Assert.Equal(virtualSize, header.VirtualSize); Assert.Equal(virtualAddress, header.VirtualAddress); Assert.Equal(sizeOfRawData, header.SizeOfRawData); Assert.Equal(ptrToRawData, header.PointerToRawData); Assert.Equal(ptrToLineNumbers, header.PointerToLineNumbers); Assert.Equal(numRelocations, header.NumberOfRelocations); Assert.Equal(numLineNumbers, header.NumberOfLineNumbers); Assert.Equal(characteristics, header.SectionCharacteristics); } private static byte[] PadSectionName(string name) { var nameBytes = Encoding.UTF8.GetBytes(name); Assert.True(name.Length <= SectionHeader.NameSize); var bytes = new byte[SectionHeader.NameSize]; Buffer.BlockCopy(nameBytes, 0, bytes, 0, nameBytes.Length); return bytes; } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/HardwareIntrinsics/X86/Sse2/AndNot.Double.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AndNotDouble() { var test = new SimpleBinaryOpTest__AndNotDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndNotDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AndNotDouble testClass) { var result = Sse2.AndNot(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndNotDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AndNotDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__AndNotDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.AndNot( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.AndNot( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.AndNot( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.AndNot( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.AndNot( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndNotDouble(); var result = Sse2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AndNotDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.AndNot(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.AndNot( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((~BitConverter.DoubleToInt64Bits(left[0]) & BitConverter.DoubleToInt64Bits(right[0])) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((~BitConverter.DoubleToInt64Bits(left[i]) & BitConverter.DoubleToInt64Bits(right[i])) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.AndNot)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AndNotDouble() { var test = new SimpleBinaryOpTest__AndNotDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndNotDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AndNotDouble testClass) { var result = Sse2.AndNot(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndNotDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AndNotDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__AndNotDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.AndNot( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.AndNot( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.AndNot( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.AndNot( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.AndNot( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndNotDouble(); var result = Sse2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AndNotDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.AndNot(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.AndNot( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((~BitConverter.DoubleToInt64Bits(left[0]) & BitConverter.DoubleToInt64Bits(right[0])) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((~BitConverter.DoubleToInt64Bits(left[i]) & BitConverter.DoubleToInt64Bits(right[i])) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.AndNot)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSA.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Diagnostics.CodeAnalysis; using System.Formats.Asn1; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Cryptography.Asn1; using Internal.Cryptography; namespace System.Security.Cryptography { public abstract partial class RSA : AsymmetricAlgorithm { [UnsupportedOSPlatform("browser")] public static new partial RSA Create(); [RequiresUnreferencedCode(CryptoConfig.CreateFromNameUnreferencedCodeMessage)] public static new RSA? Create(string algName) { return (RSA?)CryptoConfig.CreateFromName(algName); } [UnsupportedOSPlatform("browser")] public static RSA Create(int keySizeInBits) { RSA rsa = Create(); try { rsa.KeySize = keySizeInBits; return rsa; } catch { rsa.Dispose(); throw; } } [UnsupportedOSPlatform("browser")] public static RSA Create(RSAParameters parameters) { RSA rsa = Create(); try { rsa.ImportParameters(parameters); return rsa; } catch { rsa.Dispose(); throw; } } public abstract RSAParameters ExportParameters(bool includePrivateParameters); public abstract void ImportParameters(RSAParameters parameters); public virtual byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) => throw DerivedClassMustOverride(); public virtual byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) => throw DerivedClassMustOverride(); public virtual byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => throw DerivedClassMustOverride(); public virtual bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => throw DerivedClassMustOverride(); protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) => throw DerivedClassMustOverride(); protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) => throw DerivedClassMustOverride(); public virtual bool TryDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { byte[] result = Decrypt(data.ToArray(), padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { byte[] result = Encrypt(data.ToArray(), padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } protected virtual bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) { byte[] result; // Use ArrayPool.Shared instead of CryptoPool because the array is passed out. byte[] array = ArrayPool<byte>.Shared.Rent(data.Length); try { data.CopyTo(array); result = HashData(array, 0, data.Length, hashAlgorithm); } finally { Array.Clear(array, 0, data.Length); ArrayPool<byte>.Shared.Return(array); } if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) { byte[] result = SignHash(hash.ToArray(), hashAlgorithm, padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => VerifyHash(hash.ToArray(), signature.ToArray(), hashAlgorithm, padding); private static Exception DerivedClassMustOverride() => new NotImplementedException(SR.NotSupported_SubclassOverride); public virtual byte[] DecryptValue(byte[] rgb) => throw new NotSupportedException(SR.NotSupported_Method); // Same as Desktop public virtual byte[] EncryptValue(byte[] rgb) => throw new NotSupportedException(SR.NotSupported_Method); // Same as Desktop public byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { return SignData(data, 0, data.Length, hashAlgorithm, padding); } public virtual byte[] SignData( byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { ArgumentNullException.ThrowIfNull(data); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); ArgumentNullException.ThrowIfNull(padding); byte[] hash = HashData(data, offset, count, hashAlgorithm); return SignHash(hash, hashAlgorithm, padding); } public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { ArgumentNullException.ThrowIfNull(data); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); ArgumentNullException.ThrowIfNull(padding); byte[] hash = HashData(data, hashAlgorithm); return SignHash(hash, hashAlgorithm, padding); } public virtual bool TrySignData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) { ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); ArgumentNullException.ThrowIfNull(padding); if (TryHashData(data, destination, hashAlgorithm, out int hashLength) && TrySignHash(destination.Slice(0, hashLength), destination, hashAlgorithm, padding, out bytesWritten)) { return true; } bytesWritten = 0; return false; } public bool VerifyData(byte[] data!!, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { return VerifyData(data, 0, data.Length, signature, hashAlgorithm, padding); } public virtual bool VerifyData( byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { ArgumentNullException.ThrowIfNull(data); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); ArgumentNullException.ThrowIfNull(signature); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); ArgumentNullException.ThrowIfNull(padding); byte[] hash = HashData(data, offset, count, hashAlgorithm); return VerifyHash(hash, signature, hashAlgorithm, padding); } public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(signature); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); ArgumentNullException.ThrowIfNull(padding); byte[] hash = HashData(data, hashAlgorithm); return VerifyHash(hash, signature, hashAlgorithm, padding); } public virtual bool VerifyData(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); ArgumentNullException.ThrowIfNull(padding); for (int i = 256; ; i = checked(i * 2)) { int hashLength = 0; byte[] hash = CryptoPool.Rent(i); try { if (TryHashData(data, hash, hashAlgorithm, out hashLength)) { return VerifyHash(new ReadOnlySpan<byte>(hash, 0, hashLength), signature, hashAlgorithm, padding); } } finally { CryptoPool.Return(hash, hashLength); } } } public virtual byte[] ExportRSAPrivateKey() { AsnWriter pkcs1PrivateKey = WritePkcs1PrivateKey(); return pkcs1PrivateKey.Encode(); } public virtual bool TryExportRSAPrivateKey(Span<byte> destination, out int bytesWritten) { AsnWriter pkcs1PrivateKey = WritePkcs1PrivateKey(); return pkcs1PrivateKey.TryEncode(destination, out bytesWritten); } public virtual byte[] ExportRSAPublicKey() { AsnWriter pkcs1PublicKey = WritePkcs1PublicKey(); return pkcs1PublicKey.Encode(); } public virtual bool TryExportRSAPublicKey(Span<byte> destination, out int bytesWritten) { AsnWriter pkcs1PublicKey = WritePkcs1PublicKey(); return pkcs1PublicKey.TryEncode(destination, out bytesWritten); } public override unsafe bool TryExportSubjectPublicKeyInfo(Span<byte> destination, out int bytesWritten) { // The PKCS1 RSAPublicKey format is just the modulus (KeySize bits) and Exponent (usually 3 bytes), // with each field having up to 7 bytes of overhead and then up to 6 extra bytes of overhead for the // SEQUENCE tag. // // So KeySize / 4 is ideally enough to start. int rentSize = KeySize / 4; while (true) { byte[] rented = CryptoPool.Rent(rentSize); rentSize = rented.Length; int pkcs1Size = 0; fixed (byte* rentPtr = rented) { try { if (!TryExportRSAPublicKey(rented, out pkcs1Size)) { rentSize = checked(rentSize * 2); continue; } AsnWriter writer = RSAKeyFormatHelper.WriteSubjectPublicKeyInfo(rented.AsSpan(0, pkcs1Size)); return writer.TryEncode(destination, out bytesWritten); } finally { CryptoPool.Return(rented, pkcs1Size); } } } } public override bool TryExportPkcs8PrivateKey(Span<byte> destination, out int bytesWritten) { AsnWriter writer = WritePkcs8PrivateKey(); return writer.TryEncode(destination, out bytesWritten); } private unsafe AsnWriter WritePkcs8PrivateKey() { // A PKCS1 RSAPrivateKey is the Modulus (KeySize bits), D (~KeySize bits) // P, Q, DP, DQ, InverseQ (all ~KeySize/2 bits) // Each field can have up to 7 bytes of overhead, and then another 9 bytes // of fixed overhead. // So it should fit in 5 * KeySizeInBytes, but Exponent is a wildcard. int rentSize = checked(5 * KeySize / 8); while (true) { byte[] rented = CryptoPool.Rent(rentSize); rentSize = rented.Length; int pkcs1Size = 0; fixed (byte* rentPtr = rented) { try { if (!TryExportRSAPrivateKey(rented, out pkcs1Size)) { rentSize = checked(rentSize * 2); continue; } return RSAKeyFormatHelper.WritePkcs8PrivateKey(new ReadOnlySpan<byte>(rented, 0, pkcs1Size)); } finally { CryptoPool.Return(rented, pkcs1Size); } } } } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, PbeParameters pbeParameters!!, Span<byte> destination, out int bytesWritten) { PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, ReadOnlySpan<byte>.Empty); AsnWriter pkcs8PrivateKey = WritePkcs8PrivateKey(); AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8( password, pkcs8PrivateKey, pbeParameters); return writer.TryEncode(destination, out bytesWritten); } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters!!, Span<byte> destination, out int bytesWritten) { PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan<char>.Empty, passwordBytes); AsnWriter pkcs8PrivateKey = WritePkcs8PrivateKey(); AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8( passwordBytes, pkcs8PrivateKey, pbeParameters); return writer.TryEncode(destination, out bytesWritten); } private AsnWriter WritePkcs1PublicKey() { RSAParameters rsaParameters = ExportParameters(false); return RSAKeyFormatHelper.WritePkcs1PublicKey(rsaParameters); } private unsafe AsnWriter WritePkcs1PrivateKey() { RSAParameters rsaParameters = ExportParameters(true); fixed (byte* dPin = rsaParameters.D) fixed (byte* pPin = rsaParameters.P) fixed (byte* qPin = rsaParameters.Q) fixed (byte* dpPin = rsaParameters.DP) fixed (byte* dqPin = rsaParameters.DQ) fixed (byte* qInvPin = rsaParameters.InverseQ) { try { return RSAKeyFormatHelper.WritePkcs1PrivateKey(rsaParameters); } finally { ClearPrivateParameters(rsaParameters); } } } public override unsafe void ImportSubjectPublicKeyInfo(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { ReadOnlyMemory<byte> pkcs1 = RSAKeyFormatHelper.ReadSubjectPublicKeyInfo( manager.Memory, out int localRead); ImportRSAPublicKey(pkcs1.Span, out _); bytesRead = localRead; } } } public virtual unsafe void ImportRSAPublicKey(ReadOnlySpan<byte> source, out int bytesRead) { try { AsnDecoder.ReadEncodedValue( source, AsnEncodingRules.BER, out _, out _, out int localRead); fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, localRead)) { AlgorithmIdentifierAsn ignored = default; RSAKeyFormatHelper.ReadRsaPublicKey(manager.Memory, ignored, out RSAParameters rsaParameters); ImportParameters(rsaParameters); bytesRead = localRead; } } } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } public virtual unsafe void ImportRSAPrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { try { AsnDecoder.ReadEncodedValue( source, AsnEncodingRules.BER, out _, out _, out int firstValueLength); fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, firstValueLength)) { ReadOnlyMemory<byte> firstValue = manager.Memory; int localRead = firstValue.Length; AlgorithmIdentifierAsn ignored = default; RSAKeyFormatHelper.FromPkcs1PrivateKey(firstValue, ignored, out RSAParameters rsaParameters); fixed (byte* dPin = rsaParameters.D) fixed (byte* pPin = rsaParameters.P) fixed (byte* qPin = rsaParameters.Q) fixed (byte* dpPin = rsaParameters.DP) fixed (byte* dqPin = rsaParameters.DQ) fixed (byte* qInvPin = rsaParameters.InverseQ) { try { ImportParameters(rsaParameters); } finally { ClearPrivateParameters(rsaParameters); } } bytesRead = localRead; } } } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } public override unsafe void ImportPkcs8PrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { ReadOnlyMemory<byte> pkcs1 = RSAKeyFormatHelper.ReadPkcs8( manager.Memory, out int localRead); ImportRSAPrivateKey(pkcs1.Span, out _); bytesRead = localRead; } } } public override unsafe void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, ReadOnlySpan<byte> source, out int bytesRead) { RSAKeyFormatHelper.ReadEncryptedPkcs8( source, passwordBytes, out int localRead, out RSAParameters ret); fixed (byte* dPin = ret.D) fixed (byte* pPin = ret.P) fixed (byte* qPin = ret.Q) fixed (byte* dpPin = ret.DP) fixed (byte* dqPin = ret.DQ) fixed (byte* qInvPin = ret.InverseQ) { try { ImportParameters(ret); } finally { ClearPrivateParameters(ret); } } bytesRead = localRead; } public override unsafe void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, ReadOnlySpan<byte> source, out int bytesRead) { RSAKeyFormatHelper.ReadEncryptedPkcs8( source, password, out int localRead, out RSAParameters ret); fixed (byte* dPin = ret.D) fixed (byte* pPin = ret.P) fixed (byte* qPin = ret.Q) fixed (byte* dpPin = ret.DP) fixed (byte* dqPin = ret.DQ) fixed (byte* qInvPin = ret.InverseQ) { try { ImportParameters(ret); } finally { ClearPrivateParameters(ret); } } bytesRead = localRead; } /// <summary> /// Imports an RFC 7468 PEM-encoded key, replacing the keys for this object. /// </summary> /// <param name="input">The PEM text of the key to import.</param> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="input"/> does not contain a PEM-encoded key with a recognized label. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="input"/> contains multiple PEM-encoded keys with a recognized label. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="input"/> contains an encrypted PEM-encoded key. /// </para> /// </exception> /// <remarks> /// <para> /// Unsupported or malformed PEM-encoded objects will be ignored. If multiple supported PEM labels /// are found, an exception is raised to prevent importing a key when /// the key is ambiguous. /// </para> /// <para> /// This method supports the following PEM labels: /// <list type="bullet"> /// <item><description>PUBLIC KEY</description></item> /// <item><description>PRIVATE KEY</description></item> /// <item><description>RSA PRIVATE KEY</description></item> /// <item><description>RSA PUBLIC KEY</description></item> /// </list> /// </para> /// </remarks> public override void ImportFromPem(ReadOnlySpan<char> input) { PemKeyHelpers.ImportPem(input, label => { if (label.SequenceEqual(PemLabels.RsaPrivateKey)) { return ImportRSAPrivateKey; } else if (label.SequenceEqual(PemLabels.Pkcs8PrivateKey)) { return ImportPkcs8PrivateKey; } else if (label.SequenceEqual(PemLabels.RsaPublicKey)) { return ImportRSAPublicKey; } else if (label.SequenceEqual(PemLabels.SpkiPublicKey)) { return ImportSubjectPublicKeyInfo; } else { return null; } }); } /// <summary> /// Imports an encrypted RFC 7468 PEM-encoded private key, replacing the keys for this object. /// </summary> /// <param name="input">The PEM text of the encrypted key to import.</param> /// <param name="password"> /// The password to use for decrypting the key material. /// </param> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="input"/> does not contain a PEM-encoded key with a recognized label. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="input"/> contains multiple PEM-encoded keys with a recognized label. /// </para> /// </exception> /// <exception cref="CryptographicException"> /// <para> /// The password is incorrect. /// </para> /// <para> /// -or- /// </para> /// <para> /// The base-64 decoded contents of the PEM text from <paramref name="input" /> /// do not represent an ASN.1-BER-encoded PKCS#8 EncryptedPrivateKeyInfo structure. /// </para> /// <para> /// -or- /// </para> /// <para> /// The base-64 decoded contents of the PEM text from <paramref name="input" /> /// indicate the key is for an algorithm other than the algorithm /// represented by this instance. /// </para> /// <para> /// -or- /// </para> /// <para> /// The base-64 decoded contents of the PEM text from <paramref name="input" /> /// represent the key in a format that is not supported. /// </para> /// <para> /// -or- /// </para> /// <para> /// The algorithm-specific key import failed. /// </para> /// </exception> /// <remarks> /// <para> /// When the base-64 decoded contents of <paramref name="input" /> indicate an algorithm that uses PBKDF1 /// (Password-Based Key Derivation Function 1) or PBKDF2 (Password-Based Key Derivation Function 2), /// the password is converted to bytes via the UTF-8 encoding. /// </para> /// <para> /// Unsupported or malformed PEM-encoded objects will be ignored. If multiple supported PEM labels /// are found, an exception is thrown to prevent importing a key when /// the key is ambiguous. /// </para> /// <para>This method supports the <c>ENCRYPTED PRIVATE KEY</c> PEM label.</para> /// </remarks> public override void ImportFromEncryptedPem(ReadOnlySpan<char> input, ReadOnlySpan<char> password) { // Implementation has been pushed down to AsymmetricAlgorithm. The // override remains for compatibility. base.ImportFromEncryptedPem(input, password); } /// <summary> /// Imports an encrypted RFC 7468 PEM-encoded private key, replacing the keys for this object. /// </summary> /// <param name="input">The PEM text of the encrypted key to import.</param> /// <param name="passwordBytes"> /// The bytes to use as a password when decrypting the key material. /// </param> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="input"/> does not contain a PEM-encoded key with a recognized label. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="input"/> contains multiple PEM-encoded keys with a recognized label. /// </para> /// </exception> /// <exception cref="CryptographicException"> /// <para> /// The password is incorrect. /// </para> /// <para> /// -or- /// </para> /// <para> /// The base-64 decoded contents of the PEM text from <paramref name="input" /> /// do not represent an ASN.1-BER-encoded PKCS#8 EncryptedPrivateKeyInfo structure. /// </para> /// <para> /// -or- /// </para> /// <para> /// The base-64 decoded contents of the PEM text from <paramref name="input" /> /// indicate the key is for an algorithm other than the algorithm /// represented by this instance. /// </para> /// <para> /// -or- /// </para> /// <para> /// The base-64 decoded contents of the PEM text from <paramref name="input" /> /// represent the key in a format that is not supported. /// </para> /// <para> /// -or- /// </para> /// <para> /// The algorithm-specific key import failed. /// </para> /// </exception> /// <remarks> /// <para> /// The password bytes are passed directly into the Key Derivation Function (KDF) /// used by the algorithm indicated by <c>pbeParameters</c>. This enables compatibility /// with other systems which use a text encoding other than UTF-8 when processing /// passwords with PBKDF2 (Password-Based Key Derivation Function 2). /// </para> /// <para> /// Unsupported or malformed PEM-encoded objects will be ignored. If multiple supported PEM labels /// are found, an exception is thrown to prevent importing a key when /// the key is ambiguous. /// </para> /// <para>This method supports the <c>ENCRYPTED PRIVATE KEY</c> PEM label.</para> /// </remarks> public override void ImportFromEncryptedPem(ReadOnlySpan<char> input, ReadOnlySpan<byte> passwordBytes) { // Implementation has been pushed down to AsymmetricAlgorithm. The // override remains for compatibility. base.ImportFromEncryptedPem(input, passwordBytes); } /// <summary> /// Exports the current key in the PKCS#1 RSAPrivateKey format, PEM encoded. /// </summary> /// <returns>A string containing the PEM-encoded PKCS#1 RSAPrivateKey.</returns> /// <exception cref="CryptographicException"> /// The key could not be exported. /// </exception> /// <remarks> /// <p> /// A PEM-encoded PKCS#1 RSAPrivateKey will begin with <c>-----BEGIN RSA PRIVATE KEY-----</c> /// and end with <c>-----END RSA PRIVATE KEY-----</c>, with the base64 encoded DER /// contents of the key between the PEM boundaries. /// </p> /// <p> /// The PEM is encoded according to the IETF RFC 7468 &quot;strict&quot; /// encoding rules. /// </p> /// </remarks> public unsafe string ExportRSAPrivateKeyPem() { byte[] exported = ExportRSAPrivateKey(); // Fixed to prevent GC moves. fixed (byte* pExported = exported) { try { return PemKeyHelpers.CreatePemFromData(PemLabels.RsaPrivateKey, exported); } finally { CryptographicOperations.ZeroMemory(exported); } } } /// <summary> /// Exports the public-key portion of the current key in the PKCS#1 /// RSAPublicKey format, PEM encoded. /// </summary> /// <returns>A string containing the PEM-encoded PKCS#1 RSAPublicKey.</returns> /// <exception cref="CryptographicException"> /// The key could not be exported. /// </exception> /// <remarks> /// <p> /// A PEM-encoded PKCS#1 RSAPublicKey will begin with <c>-----BEGIN RSA PUBLIC KEY-----</c> /// and end with <c>-----END RSA PUBLIC KEY-----</c>, with the base64 encoded DER /// contents of the key between the PEM boundaries. /// </p> /// <p> /// The PEM is encoded according to the IETF RFC 7468 &quot;strict&quot; /// encoding rules. /// </p> /// </remarks> public string ExportRSAPublicKeyPem() { byte[] exported = ExportRSAPublicKey(); return PemKeyHelpers.CreatePemFromData(PemLabels.RsaPublicKey, exported); } /// <summary> /// Attempts to export the current key in the PEM-encoded PKCS#1 /// RSAPrivateKey format into a provided buffer. /// </summary> /// <param name="destination"> /// The character span to receive the PEM-encoded PKCS#1 RSAPrivateKey data. /// </param> /// <param name="charsWritten"> /// When this method returns, contains a value that indicates the number /// of characters written to <paramref name="destination" />. This /// parameter is treated as uninitialized. /// </param> /// <returns> /// <see langword="true" /> if <paramref name="destination" /> is big enough /// to receive the output; otherwise, <see langword="false" />. /// </returns> /// <exception cref="CryptographicException"> /// The key could not be exported. /// </exception> /// <remarks> /// <p> /// A PEM-encoded PKCS#1 RSAPrivateKey will begin with /// <c>-----BEGIN RSA PRIVATE KEY-----</c> and end with /// <c>-----END RSA PRIVATE KEY-----</c>, with the base64 encoded DER /// contents of the key between the PEM boundaries. /// </p> /// <p> /// The PEM is encoded according to the IETF RFC 7468 &quot;strict&quot; /// encoding rules. /// </p> /// </remarks> public bool TryExportRSAPrivateKeyPem(Span<char> destination, out int charsWritten) { static bool Export(RSA alg, Span<byte> destination, out int bytesWritten) { return alg.TryExportRSAPrivateKey(destination, out bytesWritten); } return PemKeyHelpers.TryExportToPem( this, PemLabels.RsaPrivateKey, Export, destination, out charsWritten); } /// <summary> /// Attempts to export the current key in the PEM-encoded PKCS#1 /// RSAPublicKey format into a provided buffer. /// </summary> /// <param name="destination"> /// The character span to receive the PEM-encoded PKCS#1 RSAPublicKey data. /// </param> /// <param name="charsWritten"> /// When this method returns, contains a value that indicates the number /// of characters written to <paramref name="destination" />. This /// parameter is treated as uninitialized. /// </param> /// <returns> /// <see langword="true" /> if <paramref name="destination" /> is big enough /// to receive the output; otherwise, <see langword="false" />. /// </returns> /// <exception cref="CryptographicException"> /// The key could not be exported. /// </exception> /// <remarks> /// <p> /// A PEM-encoded PKCS#1 RSAPublicKey will begin with /// <c>-----BEGIN RSA PUBLIC KEY-----</c> and end with /// <c>-----END RSA PUBLIC KEY-----</c>, with the base64 encoded DER /// contents of the key between the PEM boundaries. /// </p> /// <p> /// The PEM is encoded according to the IETF RFC 7468 &quot;strict&quot; /// encoding rules. /// </p> /// </remarks> public bool TryExportRSAPublicKeyPem(Span<char> destination, out int charsWritten) { static bool Export(RSA alg, Span<byte> destination, out int bytesWritten) { return alg.TryExportRSAPublicKey(destination, out bytesWritten); } return PemKeyHelpers.TryExportToPem( this, PemLabels.RsaPublicKey, Export, destination, out charsWritten); } private static void ClearPrivateParameters(in RSAParameters rsaParameters) { CryptographicOperations.ZeroMemory(rsaParameters.D); CryptographicOperations.ZeroMemory(rsaParameters.P); CryptographicOperations.ZeroMemory(rsaParameters.Q); CryptographicOperations.ZeroMemory(rsaParameters.DP); CryptographicOperations.ZeroMemory(rsaParameters.DQ); CryptographicOperations.ZeroMemory(rsaParameters.InverseQ); } public override string? KeyExchangeAlgorithm => "RSA"; public override string SignatureAlgorithm => "RSA"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Diagnostics.CodeAnalysis; using System.Formats.Asn1; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Cryptography.Asn1; using Internal.Cryptography; namespace System.Security.Cryptography { public abstract partial class RSA : AsymmetricAlgorithm { [UnsupportedOSPlatform("browser")] public static new partial RSA Create(); [RequiresUnreferencedCode(CryptoConfig.CreateFromNameUnreferencedCodeMessage)] public static new RSA? Create(string algName) { return (RSA?)CryptoConfig.CreateFromName(algName); } [UnsupportedOSPlatform("browser")] public static RSA Create(int keySizeInBits) { RSA rsa = Create(); try { rsa.KeySize = keySizeInBits; return rsa; } catch { rsa.Dispose(); throw; } } [UnsupportedOSPlatform("browser")] public static RSA Create(RSAParameters parameters) { RSA rsa = Create(); try { rsa.ImportParameters(parameters); return rsa; } catch { rsa.Dispose(); throw; } } public abstract RSAParameters ExportParameters(bool includePrivateParameters); public abstract void ImportParameters(RSAParameters parameters); public virtual byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) => throw DerivedClassMustOverride(); public virtual byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) => throw DerivedClassMustOverride(); public virtual byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => throw DerivedClassMustOverride(); public virtual bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => throw DerivedClassMustOverride(); protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) => throw DerivedClassMustOverride(); protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) => throw DerivedClassMustOverride(); public virtual bool TryDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { byte[] result = Decrypt(data.ToArray(), padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { byte[] result = Encrypt(data.ToArray(), padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } protected virtual bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) { byte[] result; // Use ArrayPool.Shared instead of CryptoPool because the array is passed out. byte[] array = ArrayPool<byte>.Shared.Rent(data.Length); try { data.CopyTo(array); result = HashData(array, 0, data.Length, hashAlgorithm); } finally { Array.Clear(array, 0, data.Length); ArrayPool<byte>.Shared.Return(array); } if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) { byte[] result = SignHash(hash.ToArray(), hashAlgorithm, padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => VerifyHash(hash.ToArray(), signature.ToArray(), hashAlgorithm, padding); private static Exception DerivedClassMustOverride() => new NotImplementedException(SR.NotSupported_SubclassOverride); public virtual byte[] DecryptValue(byte[] rgb) => throw new NotSupportedException(SR.NotSupported_Method); // Same as Desktop public virtual byte[] EncryptValue(byte[] rgb) => throw new NotSupportedException(SR.NotSupported_Method); // Same as Desktop public byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { return SignData(data, 0, data.Length, hashAlgorithm, padding); } public virtual byte[] SignData( byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { ArgumentNullException.ThrowIfNull(data); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); ArgumentNullException.ThrowIfNull(padding); byte[] hash = HashData(data, offset, count, hashAlgorithm); return SignHash(hash, hashAlgorithm, padding); } public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { ArgumentNullException.ThrowIfNull(data); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); ArgumentNullException.ThrowIfNull(padding); byte[] hash = HashData(data, hashAlgorithm); return SignHash(hash, hashAlgorithm, padding); } public virtual bool TrySignData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) { ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); ArgumentNullException.ThrowIfNull(padding); if (TryHashData(data, destination, hashAlgorithm, out int hashLength) && TrySignHash(destination.Slice(0, hashLength), destination, hashAlgorithm, padding, out bytesWritten)) { return true; } bytesWritten = 0; return false; } public bool VerifyData(byte[] data!!, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { return VerifyData(data, 0, data.Length, signature, hashAlgorithm, padding); } public virtual bool VerifyData( byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { ArgumentNullException.ThrowIfNull(data); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); ArgumentNullException.ThrowIfNull(signature); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); ArgumentNullException.ThrowIfNull(padding); byte[] hash = HashData(data, offset, count, hashAlgorithm); return VerifyHash(hash, signature, hashAlgorithm, padding); } public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(signature); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); ArgumentNullException.ThrowIfNull(padding); byte[] hash = HashData(data, hashAlgorithm); return VerifyHash(hash, signature, hashAlgorithm, padding); } public virtual bool VerifyData(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); ArgumentNullException.ThrowIfNull(padding); for (int i = 256; ; i = checked(i * 2)) { int hashLength = 0; byte[] hash = CryptoPool.Rent(i); try { if (TryHashData(data, hash, hashAlgorithm, out hashLength)) { return VerifyHash(new ReadOnlySpan<byte>(hash, 0, hashLength), signature, hashAlgorithm, padding); } } finally { CryptoPool.Return(hash, hashLength); } } } public virtual byte[] ExportRSAPrivateKey() { AsnWriter pkcs1PrivateKey = WritePkcs1PrivateKey(); return pkcs1PrivateKey.Encode(); } public virtual bool TryExportRSAPrivateKey(Span<byte> destination, out int bytesWritten) { AsnWriter pkcs1PrivateKey = WritePkcs1PrivateKey(); return pkcs1PrivateKey.TryEncode(destination, out bytesWritten); } public virtual byte[] ExportRSAPublicKey() { AsnWriter pkcs1PublicKey = WritePkcs1PublicKey(); return pkcs1PublicKey.Encode(); } public virtual bool TryExportRSAPublicKey(Span<byte> destination, out int bytesWritten) { AsnWriter pkcs1PublicKey = WritePkcs1PublicKey(); return pkcs1PublicKey.TryEncode(destination, out bytesWritten); } public override unsafe bool TryExportSubjectPublicKeyInfo(Span<byte> destination, out int bytesWritten) { // The PKCS1 RSAPublicKey format is just the modulus (KeySize bits) and Exponent (usually 3 bytes), // with each field having up to 7 bytes of overhead and then up to 6 extra bytes of overhead for the // SEQUENCE tag. // // So KeySize / 4 is ideally enough to start. int rentSize = KeySize / 4; while (true) { byte[] rented = CryptoPool.Rent(rentSize); rentSize = rented.Length; int pkcs1Size = 0; fixed (byte* rentPtr = rented) { try { if (!TryExportRSAPublicKey(rented, out pkcs1Size)) { rentSize = checked(rentSize * 2); continue; } AsnWriter writer = RSAKeyFormatHelper.WriteSubjectPublicKeyInfo(rented.AsSpan(0, pkcs1Size)); return writer.TryEncode(destination, out bytesWritten); } finally { CryptoPool.Return(rented, pkcs1Size); } } } } public override bool TryExportPkcs8PrivateKey(Span<byte> destination, out int bytesWritten) { AsnWriter writer = WritePkcs8PrivateKey(); return writer.TryEncode(destination, out bytesWritten); } private unsafe AsnWriter WritePkcs8PrivateKey() { // A PKCS1 RSAPrivateKey is the Modulus (KeySize bits), D (~KeySize bits) // P, Q, DP, DQ, InverseQ (all ~KeySize/2 bits) // Each field can have up to 7 bytes of overhead, and then another 9 bytes // of fixed overhead. // So it should fit in 5 * KeySizeInBytes, but Exponent is a wildcard. int rentSize = checked(5 * KeySize / 8); while (true) { byte[] rented = CryptoPool.Rent(rentSize); rentSize = rented.Length; int pkcs1Size = 0; fixed (byte* rentPtr = rented) { try { if (!TryExportRSAPrivateKey(rented, out pkcs1Size)) { rentSize = checked(rentSize * 2); continue; } return RSAKeyFormatHelper.WritePkcs8PrivateKey(new ReadOnlySpan<byte>(rented, 0, pkcs1Size)); } finally { CryptoPool.Return(rented, pkcs1Size); } } } } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, PbeParameters pbeParameters!!, Span<byte> destination, out int bytesWritten) { PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, ReadOnlySpan<byte>.Empty); AsnWriter pkcs8PrivateKey = WritePkcs8PrivateKey(); AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8( password, pkcs8PrivateKey, pbeParameters); return writer.TryEncode(destination, out bytesWritten); } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters!!, Span<byte> destination, out int bytesWritten) { PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan<char>.Empty, passwordBytes); AsnWriter pkcs8PrivateKey = WritePkcs8PrivateKey(); AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8( passwordBytes, pkcs8PrivateKey, pbeParameters); return writer.TryEncode(destination, out bytesWritten); } private AsnWriter WritePkcs1PublicKey() { RSAParameters rsaParameters = ExportParameters(false); return RSAKeyFormatHelper.WritePkcs1PublicKey(rsaParameters); } private unsafe AsnWriter WritePkcs1PrivateKey() { RSAParameters rsaParameters = ExportParameters(true); fixed (byte* dPin = rsaParameters.D) fixed (byte* pPin = rsaParameters.P) fixed (byte* qPin = rsaParameters.Q) fixed (byte* dpPin = rsaParameters.DP) fixed (byte* dqPin = rsaParameters.DQ) fixed (byte* qInvPin = rsaParameters.InverseQ) { try { return RSAKeyFormatHelper.WritePkcs1PrivateKey(rsaParameters); } finally { ClearPrivateParameters(rsaParameters); } } } public override unsafe void ImportSubjectPublicKeyInfo(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { ReadOnlyMemory<byte> pkcs1 = RSAKeyFormatHelper.ReadSubjectPublicKeyInfo( manager.Memory, out int localRead); ImportRSAPublicKey(pkcs1.Span, out _); bytesRead = localRead; } } } public virtual unsafe void ImportRSAPublicKey(ReadOnlySpan<byte> source, out int bytesRead) { try { AsnDecoder.ReadEncodedValue( source, AsnEncodingRules.BER, out _, out _, out int localRead); fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, localRead)) { AlgorithmIdentifierAsn ignored = default; RSAKeyFormatHelper.ReadRsaPublicKey(manager.Memory, ignored, out RSAParameters rsaParameters); ImportParameters(rsaParameters); bytesRead = localRead; } } } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } public virtual unsafe void ImportRSAPrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { try { AsnDecoder.ReadEncodedValue( source, AsnEncodingRules.BER, out _, out _, out int firstValueLength); fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, firstValueLength)) { ReadOnlyMemory<byte> firstValue = manager.Memory; int localRead = firstValue.Length; AlgorithmIdentifierAsn ignored = default; RSAKeyFormatHelper.FromPkcs1PrivateKey(firstValue, ignored, out RSAParameters rsaParameters); fixed (byte* dPin = rsaParameters.D) fixed (byte* pPin = rsaParameters.P) fixed (byte* qPin = rsaParameters.Q) fixed (byte* dpPin = rsaParameters.DP) fixed (byte* dqPin = rsaParameters.DQ) fixed (byte* qInvPin = rsaParameters.InverseQ) { try { ImportParameters(rsaParameters); } finally { ClearPrivateParameters(rsaParameters); } } bytesRead = localRead; } } } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } public override unsafe void ImportPkcs8PrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { ReadOnlyMemory<byte> pkcs1 = RSAKeyFormatHelper.ReadPkcs8( manager.Memory, out int localRead); ImportRSAPrivateKey(pkcs1.Span, out _); bytesRead = localRead; } } } public override unsafe void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, ReadOnlySpan<byte> source, out int bytesRead) { RSAKeyFormatHelper.ReadEncryptedPkcs8( source, passwordBytes, out int localRead, out RSAParameters ret); fixed (byte* dPin = ret.D) fixed (byte* pPin = ret.P) fixed (byte* qPin = ret.Q) fixed (byte* dpPin = ret.DP) fixed (byte* dqPin = ret.DQ) fixed (byte* qInvPin = ret.InverseQ) { try { ImportParameters(ret); } finally { ClearPrivateParameters(ret); } } bytesRead = localRead; } public override unsafe void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, ReadOnlySpan<byte> source, out int bytesRead) { RSAKeyFormatHelper.ReadEncryptedPkcs8( source, password, out int localRead, out RSAParameters ret); fixed (byte* dPin = ret.D) fixed (byte* pPin = ret.P) fixed (byte* qPin = ret.Q) fixed (byte* dpPin = ret.DP) fixed (byte* dqPin = ret.DQ) fixed (byte* qInvPin = ret.InverseQ) { try { ImportParameters(ret); } finally { ClearPrivateParameters(ret); } } bytesRead = localRead; } /// <summary> /// Imports an RFC 7468 PEM-encoded key, replacing the keys for this object. /// </summary> /// <param name="input">The PEM text of the key to import.</param> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="input"/> does not contain a PEM-encoded key with a recognized label. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="input"/> contains multiple PEM-encoded keys with a recognized label. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="input"/> contains an encrypted PEM-encoded key. /// </para> /// </exception> /// <remarks> /// <para> /// Unsupported or malformed PEM-encoded objects will be ignored. If multiple supported PEM labels /// are found, an exception is raised to prevent importing a key when /// the key is ambiguous. /// </para> /// <para> /// This method supports the following PEM labels: /// <list type="bullet"> /// <item><description>PUBLIC KEY</description></item> /// <item><description>PRIVATE KEY</description></item> /// <item><description>RSA PRIVATE KEY</description></item> /// <item><description>RSA PUBLIC KEY</description></item> /// </list> /// </para> /// </remarks> public override void ImportFromPem(ReadOnlySpan<char> input) { PemKeyHelpers.ImportPem(input, label => { if (label.SequenceEqual(PemLabels.RsaPrivateKey)) { return ImportRSAPrivateKey; } else if (label.SequenceEqual(PemLabels.Pkcs8PrivateKey)) { return ImportPkcs8PrivateKey; } else if (label.SequenceEqual(PemLabels.RsaPublicKey)) { return ImportRSAPublicKey; } else if (label.SequenceEqual(PemLabels.SpkiPublicKey)) { return ImportSubjectPublicKeyInfo; } else { return null; } }); } /// <summary> /// Imports an encrypted RFC 7468 PEM-encoded private key, replacing the keys for this object. /// </summary> /// <param name="input">The PEM text of the encrypted key to import.</param> /// <param name="password"> /// The password to use for decrypting the key material. /// </param> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="input"/> does not contain a PEM-encoded key with a recognized label. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="input"/> contains multiple PEM-encoded keys with a recognized label. /// </para> /// </exception> /// <exception cref="CryptographicException"> /// <para> /// The password is incorrect. /// </para> /// <para> /// -or- /// </para> /// <para> /// The base-64 decoded contents of the PEM text from <paramref name="input" /> /// do not represent an ASN.1-BER-encoded PKCS#8 EncryptedPrivateKeyInfo structure. /// </para> /// <para> /// -or- /// </para> /// <para> /// The base-64 decoded contents of the PEM text from <paramref name="input" /> /// indicate the key is for an algorithm other than the algorithm /// represented by this instance. /// </para> /// <para> /// -or- /// </para> /// <para> /// The base-64 decoded contents of the PEM text from <paramref name="input" /> /// represent the key in a format that is not supported. /// </para> /// <para> /// -or- /// </para> /// <para> /// The algorithm-specific key import failed. /// </para> /// </exception> /// <remarks> /// <para> /// When the base-64 decoded contents of <paramref name="input" /> indicate an algorithm that uses PBKDF1 /// (Password-Based Key Derivation Function 1) or PBKDF2 (Password-Based Key Derivation Function 2), /// the password is converted to bytes via the UTF-8 encoding. /// </para> /// <para> /// Unsupported or malformed PEM-encoded objects will be ignored. If multiple supported PEM labels /// are found, an exception is thrown to prevent importing a key when /// the key is ambiguous. /// </para> /// <para>This method supports the <c>ENCRYPTED PRIVATE KEY</c> PEM label.</para> /// </remarks> public override void ImportFromEncryptedPem(ReadOnlySpan<char> input, ReadOnlySpan<char> password) { // Implementation has been pushed down to AsymmetricAlgorithm. The // override remains for compatibility. base.ImportFromEncryptedPem(input, password); } /// <summary> /// Imports an encrypted RFC 7468 PEM-encoded private key, replacing the keys for this object. /// </summary> /// <param name="input">The PEM text of the encrypted key to import.</param> /// <param name="passwordBytes"> /// The bytes to use as a password when decrypting the key material. /// </param> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="input"/> does not contain a PEM-encoded key with a recognized label. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="input"/> contains multiple PEM-encoded keys with a recognized label. /// </para> /// </exception> /// <exception cref="CryptographicException"> /// <para> /// The password is incorrect. /// </para> /// <para> /// -or- /// </para> /// <para> /// The base-64 decoded contents of the PEM text from <paramref name="input" /> /// do not represent an ASN.1-BER-encoded PKCS#8 EncryptedPrivateKeyInfo structure. /// </para> /// <para> /// -or- /// </para> /// <para> /// The base-64 decoded contents of the PEM text from <paramref name="input" /> /// indicate the key is for an algorithm other than the algorithm /// represented by this instance. /// </para> /// <para> /// -or- /// </para> /// <para> /// The base-64 decoded contents of the PEM text from <paramref name="input" /> /// represent the key in a format that is not supported. /// </para> /// <para> /// -or- /// </para> /// <para> /// The algorithm-specific key import failed. /// </para> /// </exception> /// <remarks> /// <para> /// The password bytes are passed directly into the Key Derivation Function (KDF) /// used by the algorithm indicated by <c>pbeParameters</c>. This enables compatibility /// with other systems which use a text encoding other than UTF-8 when processing /// passwords with PBKDF2 (Password-Based Key Derivation Function 2). /// </para> /// <para> /// Unsupported or malformed PEM-encoded objects will be ignored. If multiple supported PEM labels /// are found, an exception is thrown to prevent importing a key when /// the key is ambiguous. /// </para> /// <para>This method supports the <c>ENCRYPTED PRIVATE KEY</c> PEM label.</para> /// </remarks> public override void ImportFromEncryptedPem(ReadOnlySpan<char> input, ReadOnlySpan<byte> passwordBytes) { // Implementation has been pushed down to AsymmetricAlgorithm. The // override remains for compatibility. base.ImportFromEncryptedPem(input, passwordBytes); } /// <summary> /// Exports the current key in the PKCS#1 RSAPrivateKey format, PEM encoded. /// </summary> /// <returns>A string containing the PEM-encoded PKCS#1 RSAPrivateKey.</returns> /// <exception cref="CryptographicException"> /// The key could not be exported. /// </exception> /// <remarks> /// <p> /// A PEM-encoded PKCS#1 RSAPrivateKey will begin with <c>-----BEGIN RSA PRIVATE KEY-----</c> /// and end with <c>-----END RSA PRIVATE KEY-----</c>, with the base64 encoded DER /// contents of the key between the PEM boundaries. /// </p> /// <p> /// The PEM is encoded according to the IETF RFC 7468 &quot;strict&quot; /// encoding rules. /// </p> /// </remarks> public unsafe string ExportRSAPrivateKeyPem() { byte[] exported = ExportRSAPrivateKey(); // Fixed to prevent GC moves. fixed (byte* pExported = exported) { try { return PemKeyHelpers.CreatePemFromData(PemLabels.RsaPrivateKey, exported); } finally { CryptographicOperations.ZeroMemory(exported); } } } /// <summary> /// Exports the public-key portion of the current key in the PKCS#1 /// RSAPublicKey format, PEM encoded. /// </summary> /// <returns>A string containing the PEM-encoded PKCS#1 RSAPublicKey.</returns> /// <exception cref="CryptographicException"> /// The key could not be exported. /// </exception> /// <remarks> /// <p> /// A PEM-encoded PKCS#1 RSAPublicKey will begin with <c>-----BEGIN RSA PUBLIC KEY-----</c> /// and end with <c>-----END RSA PUBLIC KEY-----</c>, with the base64 encoded DER /// contents of the key between the PEM boundaries. /// </p> /// <p> /// The PEM is encoded according to the IETF RFC 7468 &quot;strict&quot; /// encoding rules. /// </p> /// </remarks> public string ExportRSAPublicKeyPem() { byte[] exported = ExportRSAPublicKey(); return PemKeyHelpers.CreatePemFromData(PemLabels.RsaPublicKey, exported); } /// <summary> /// Attempts to export the current key in the PEM-encoded PKCS#1 /// RSAPrivateKey format into a provided buffer. /// </summary> /// <param name="destination"> /// The character span to receive the PEM-encoded PKCS#1 RSAPrivateKey data. /// </param> /// <param name="charsWritten"> /// When this method returns, contains a value that indicates the number /// of characters written to <paramref name="destination" />. This /// parameter is treated as uninitialized. /// </param> /// <returns> /// <see langword="true" /> if <paramref name="destination" /> is big enough /// to receive the output; otherwise, <see langword="false" />. /// </returns> /// <exception cref="CryptographicException"> /// The key could not be exported. /// </exception> /// <remarks> /// <p> /// A PEM-encoded PKCS#1 RSAPrivateKey will begin with /// <c>-----BEGIN RSA PRIVATE KEY-----</c> and end with /// <c>-----END RSA PRIVATE KEY-----</c>, with the base64 encoded DER /// contents of the key between the PEM boundaries. /// </p> /// <p> /// The PEM is encoded according to the IETF RFC 7468 &quot;strict&quot; /// encoding rules. /// </p> /// </remarks> public bool TryExportRSAPrivateKeyPem(Span<char> destination, out int charsWritten) { static bool Export(RSA alg, Span<byte> destination, out int bytesWritten) { return alg.TryExportRSAPrivateKey(destination, out bytesWritten); } return PemKeyHelpers.TryExportToPem( this, PemLabels.RsaPrivateKey, Export, destination, out charsWritten); } /// <summary> /// Attempts to export the current key in the PEM-encoded PKCS#1 /// RSAPublicKey format into a provided buffer. /// </summary> /// <param name="destination"> /// The character span to receive the PEM-encoded PKCS#1 RSAPublicKey data. /// </param> /// <param name="charsWritten"> /// When this method returns, contains a value that indicates the number /// of characters written to <paramref name="destination" />. This /// parameter is treated as uninitialized. /// </param> /// <returns> /// <see langword="true" /> if <paramref name="destination" /> is big enough /// to receive the output; otherwise, <see langword="false" />. /// </returns> /// <exception cref="CryptographicException"> /// The key could not be exported. /// </exception> /// <remarks> /// <p> /// A PEM-encoded PKCS#1 RSAPublicKey will begin with /// <c>-----BEGIN RSA PUBLIC KEY-----</c> and end with /// <c>-----END RSA PUBLIC KEY-----</c>, with the base64 encoded DER /// contents of the key between the PEM boundaries. /// </p> /// <p> /// The PEM is encoded according to the IETF RFC 7468 &quot;strict&quot; /// encoding rules. /// </p> /// </remarks> public bool TryExportRSAPublicKeyPem(Span<char> destination, out int charsWritten) { static bool Export(RSA alg, Span<byte> destination, out int bytesWritten) { return alg.TryExportRSAPublicKey(destination, out bytesWritten); } return PemKeyHelpers.TryExportToPem( this, PemLabels.RsaPublicKey, Export, destination, out charsWritten); } private static void ClearPrivateParameters(in RSAParameters rsaParameters) { CryptographicOperations.ZeroMemory(rsaParameters.D); CryptographicOperations.ZeroMemory(rsaParameters.P); CryptographicOperations.ZeroMemory(rsaParameters.Q); CryptographicOperations.ZeroMemory(rsaParameters.DP); CryptographicOperations.ZeroMemory(rsaParameters.DQ); CryptographicOperations.ZeroMemory(rsaParameters.InverseQ); } public override string? KeyExchangeAlgorithm => "RSA"; public override string SignatureAlgorithm => "RSA"; } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/installer/tests/Assets/TestProjects/StartupHookWithReturnType/StartupHookWithReturnType.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <RuntimeFrameworkVersion>$(MNAVersion)</RuntimeFrameworkVersion> </PropertyGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <RuntimeFrameworkVersion>$(MNAVersion)</RuntimeFrameworkVersion> </PropertyGroup> </Project>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/Methodical/tailcall_v4/delegateParamCallTarget.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="delegateParamCallTarget.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="delegateParamCallTarget.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Data.Common; using System.Diagnostics.CodeAnalysis; namespace System.Data { internal abstract class ExpressionNode { private DataTable? _table; protected ExpressionNode(DataTable? table) { _table = table; } internal IFormatProvider FormatProvider { get { return ((null != _table) ? _table.FormatProvider : System.Globalization.CultureInfo.CurrentCulture); } } internal virtual bool IsSqlColumn { get { return false; } } protected DataTable? table { get { return _table; } } protected void BindTable(DataTable table) { // when the expression is created, DataColumn may not be associated with a table yet _table = table; } internal abstract void Bind(DataTable table, List<DataColumn> list); [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] internal abstract object Eval(); [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] internal abstract object Eval(DataRow? row, DataRowVersion version); [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] internal abstract object Eval(int[] recordNos); internal abstract bool IsConstant(); internal abstract bool IsTableConstant(); internal abstract bool HasLocalAggregate(); internal abstract bool HasRemoteAggregate(); internal abstract ExpressionNode Optimize(); internal virtual bool DependsOn(DataColumn column) { return false; } internal static bool IsInteger(StorageType type) { return (type == StorageType.Int16 || type == StorageType.Int32 || type == StorageType.Int64 || type == StorageType.UInt16 || type == StorageType.UInt32 || type == StorageType.UInt64 || type == StorageType.SByte || type == StorageType.Byte); } internal static bool IsIntegerSql(StorageType type) { return (type == StorageType.Int16 || type == StorageType.Int32 || type == StorageType.Int64 || type == StorageType.UInt16 || type == StorageType.UInt32 || type == StorageType.UInt64 || type == StorageType.SByte || type == StorageType.Byte || type == StorageType.SqlInt64 || type == StorageType.SqlInt32 || type == StorageType.SqlInt16 || type == StorageType.SqlByte); } internal static bool IsSigned(StorageType type) { return (type == StorageType.Int16 || type == StorageType.Int32 || type == StorageType.Int64 || type == StorageType.SByte || IsFloat(type)); } internal static bool IsSignedSql(StorageType type) { return (type == StorageType.Int16 || // IsSigned(type) type == StorageType.Int32 || type == StorageType.Int64 || type == StorageType.SByte || type == StorageType.SqlInt64 || type == StorageType.SqlInt32 || type == StorageType.SqlInt16 || IsFloatSql(type)); } internal static bool IsUnsigned(StorageType type) { return (type == StorageType.UInt16 || type == StorageType.UInt32 || type == StorageType.UInt64 || type == StorageType.Byte); } internal static bool IsUnsignedSql(StorageType type) { return (type == StorageType.UInt16 || type == StorageType.UInt32 || type == StorageType.UInt64 || type == StorageType.SqlByte ||// SqlByte represents an 8-bit unsigned integer, in the range of 0 through 255, type == StorageType.Byte); } internal static bool IsNumeric(StorageType type) { return (IsFloat(type) || IsInteger(type)); } internal static bool IsNumericSql(StorageType type) { return (IsFloatSql(type) || IsIntegerSql(type)); } internal static bool IsFloat(StorageType type) { return (type == StorageType.Single || type == StorageType.Double || type == StorageType.Decimal); } internal static bool IsFloatSql(StorageType type) { return (type == StorageType.Single || type == StorageType.Double || type == StorageType.Decimal || type == StorageType.SqlDouble || type == StorageType.SqlDecimal || // I expect decimal to be Integer! type == StorageType.SqlMoney || // if decimal is here, this should be definitely here! type == StorageType.SqlSingle); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Data.Common; using System.Diagnostics.CodeAnalysis; namespace System.Data { internal abstract class ExpressionNode { private DataTable? _table; protected ExpressionNode(DataTable? table) { _table = table; } internal IFormatProvider FormatProvider { get { return ((null != _table) ? _table.FormatProvider : System.Globalization.CultureInfo.CurrentCulture); } } internal virtual bool IsSqlColumn { get { return false; } } protected DataTable? table { get { return _table; } } protected void BindTable(DataTable table) { // when the expression is created, DataColumn may not be associated with a table yet _table = table; } internal abstract void Bind(DataTable table, List<DataColumn> list); [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] internal abstract object Eval(); [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] internal abstract object Eval(DataRow? row, DataRowVersion version); [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] internal abstract object Eval(int[] recordNos); internal abstract bool IsConstant(); internal abstract bool IsTableConstant(); internal abstract bool HasLocalAggregate(); internal abstract bool HasRemoteAggregate(); internal abstract ExpressionNode Optimize(); internal virtual bool DependsOn(DataColumn column) { return false; } internal static bool IsInteger(StorageType type) { return (type == StorageType.Int16 || type == StorageType.Int32 || type == StorageType.Int64 || type == StorageType.UInt16 || type == StorageType.UInt32 || type == StorageType.UInt64 || type == StorageType.SByte || type == StorageType.Byte); } internal static bool IsIntegerSql(StorageType type) { return (type == StorageType.Int16 || type == StorageType.Int32 || type == StorageType.Int64 || type == StorageType.UInt16 || type == StorageType.UInt32 || type == StorageType.UInt64 || type == StorageType.SByte || type == StorageType.Byte || type == StorageType.SqlInt64 || type == StorageType.SqlInt32 || type == StorageType.SqlInt16 || type == StorageType.SqlByte); } internal static bool IsSigned(StorageType type) { return (type == StorageType.Int16 || type == StorageType.Int32 || type == StorageType.Int64 || type == StorageType.SByte || IsFloat(type)); } internal static bool IsSignedSql(StorageType type) { return (type == StorageType.Int16 || // IsSigned(type) type == StorageType.Int32 || type == StorageType.Int64 || type == StorageType.SByte || type == StorageType.SqlInt64 || type == StorageType.SqlInt32 || type == StorageType.SqlInt16 || IsFloatSql(type)); } internal static bool IsUnsigned(StorageType type) { return (type == StorageType.UInt16 || type == StorageType.UInt32 || type == StorageType.UInt64 || type == StorageType.Byte); } internal static bool IsUnsignedSql(StorageType type) { return (type == StorageType.UInt16 || type == StorageType.UInt32 || type == StorageType.UInt64 || type == StorageType.SqlByte ||// SqlByte represents an 8-bit unsigned integer, in the range of 0 through 255, type == StorageType.Byte); } internal static bool IsNumeric(StorageType type) { return (IsFloat(type) || IsInteger(type)); } internal static bool IsNumericSql(StorageType type) { return (IsFloatSql(type) || IsIntegerSql(type)); } internal static bool IsFloat(StorageType type) { return (type == StorageType.Single || type == StorageType.Double || type == StorageType.Decimal); } internal static bool IsFloatSql(StorageType type) { return (type == StorageType.Single || type == StorageType.Double || type == StorageType.Decimal || type == StorageType.SqlDouble || type == StorageType.SqlDecimal || // I expect decimal to be Integer! type == StorageType.SqlMoney || // if decimal is here, this should be definitely here! type == StorageType.SqlSingle); } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/Methodical/cctor/misc/threads1_cs_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> <RequiresProcessIsolation>true</RequiresProcessIsolation> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>Full</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="threads1.cs" /> <ProjectReference Include="testlib.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> <RequiresProcessIsolation>true</RequiresProcessIsolation> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>Full</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="threads1.cs" /> <ProjectReference Include="testlib.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/Methodical/FPtrunc/convr8a_cs_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="convr8a.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="convr8a.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Transactions.Local/src/System/Transactions/ISimpleTransactionSuperior.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Transactions { public interface ISimpleTransactionSuperior : ITransactionPromoter { void Rollback(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Transactions { public interface ISimpleTransactionSuperior : ITransactionPromoter { void Rollback(); } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/HardwareIntrinsics/X86/Avx1/Permute.Double.2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void PermuteDouble2() { var test = new ImmUnaryOpTest__PermuteDouble2(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__PermuteDouble2 { private struct TestStruct { public Vector128<Double> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__PermuteDouble2 testClass) { var result = Avx.Permute(_fld, 2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data = new Double[Op1ElementCount]; private static Vector128<Double> _clsVar; private Vector128<Double> _fld; private SimpleUnaryOpTest__DataTable<Double, Double> _dataTable; static ImmUnaryOpTest__PermuteDouble2() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public ImmUnaryOpTest__PermuteDouble2() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new SimpleUnaryOpTest__DataTable<Double, Double>(_data, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.Permute( Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.Permute( Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr)), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.Permute( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr)), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.Permute), new Type[] { typeof(Vector128<Double>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.Permute), new Type[] { typeof(Vector128<Double>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr)), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.Permute), new Type[] { typeof(Vector128<Double>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr)), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.Permute( _clsVar, 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr); var result = Avx.Permute(firstOp, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr)); var result = Avx.Permute(firstOp, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr)); var result = Avx.Permute(firstOp, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__PermuteDouble2(); var result = Avx.Permute(test._fld, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.Permute(_fld, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.Permute(test._fld, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> firstOp, void* result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[1]) != BitConverter.DoubleToInt64Bits(firstOp[1])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Permute)}<Double>(Vector128<Double><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void PermuteDouble2() { var test = new ImmUnaryOpTest__PermuteDouble2(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__PermuteDouble2 { private struct TestStruct { public Vector128<Double> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__PermuteDouble2 testClass) { var result = Avx.Permute(_fld, 2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data = new Double[Op1ElementCount]; private static Vector128<Double> _clsVar; private Vector128<Double> _fld; private SimpleUnaryOpTest__DataTable<Double, Double> _dataTable; static ImmUnaryOpTest__PermuteDouble2() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public ImmUnaryOpTest__PermuteDouble2() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new SimpleUnaryOpTest__DataTable<Double, Double>(_data, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.Permute( Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.Permute( Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr)), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.Permute( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr)), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.Permute), new Type[] { typeof(Vector128<Double>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.Permute), new Type[] { typeof(Vector128<Double>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr)), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.Permute), new Type[] { typeof(Vector128<Double>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr)), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.Permute( _clsVar, 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr); var result = Avx.Permute(firstOp, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr)); var result = Avx.Permute(firstOp, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr)); var result = Avx.Permute(firstOp, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__PermuteDouble2(); var result = Avx.Permute(test._fld, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.Permute(_fld, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.Permute(test._fld, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> firstOp, void* result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[1]) != BitConverter.DoubleToInt64Bits(firstOp[1])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Permute)}<Double>(Vector128<Double><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/CadesIssuerSerial.xml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma warning disable SA1028 // ignore whitespace warnings for generated code using System; using System.Collections.Generic; using System.Formats.Asn1; using System.Runtime.InteropServices; namespace System.Security.Cryptography.Pkcs.Asn1 { [StructLayout(LayoutKind.Sequential)] internal partial struct CadesIssuerSerial { internal System.Security.Cryptography.Asn1.GeneralNameAsn[] Issuer; internal ReadOnlyMemory<byte> SerialNumber; internal void Encode(AsnWriter writer) { Encode(writer, Asn1Tag.Sequence); } internal void Encode(AsnWriter writer, Asn1Tag tag) { writer.PushSequence(tag); writer.PushSequence(); for (int i = 0; i < Issuer.Length; i++) { Issuer[i].Encode(writer); } writer.PopSequence(); writer.WriteInteger(SerialNumber.Span); writer.PopSequence(tag); } internal static CadesIssuerSerial Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet) { return Decode(Asn1Tag.Sequence, encoded, ruleSet); } internal static CadesIssuerSerial Decode(Asn1Tag expectedTag, ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet) { try { AsnValueReader reader = new AsnValueReader(encoded.Span, ruleSet); DecodeCore(ref reader, expectedTag, encoded, out CadesIssuerSerial decoded); reader.ThrowIfNotEmpty(); return decoded; } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory<byte> rebind, out CadesIssuerSerial decoded) { Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded); } internal static void Decode(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out CadesIssuerSerial decoded) { try { DecodeCore(ref reader, expectedTag, rebind, out decoded); } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } private static void DecodeCore(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out CadesIssuerSerial decoded) { decoded = default; AsnValueReader sequenceReader = reader.ReadSequence(expectedTag); AsnValueReader collectionReader; ReadOnlySpan<byte> rebindSpan = rebind.Span; int offset; ReadOnlySpan<byte> tmpSpan; // Decode SEQUENCE OF for Issuer { collectionReader = sequenceReader.ReadSequence(); var tmpList = new List<System.Security.Cryptography.Asn1.GeneralNameAsn>(); System.Security.Cryptography.Asn1.GeneralNameAsn tmpItem; while (collectionReader.HasData) { System.Security.Cryptography.Asn1.GeneralNameAsn.Decode(ref collectionReader, rebind, out tmpItem); tmpList.Add(tmpItem); } decoded.Issuer = tmpList.ToArray(); } tmpSpan = sequenceReader.ReadIntegerBytes(); decoded.SerialNumber = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray(); sequenceReader.ThrowIfNotEmpty(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma warning disable SA1028 // ignore whitespace warnings for generated code using System; using System.Collections.Generic; using System.Formats.Asn1; using System.Runtime.InteropServices; namespace System.Security.Cryptography.Pkcs.Asn1 { [StructLayout(LayoutKind.Sequential)] internal partial struct CadesIssuerSerial { internal System.Security.Cryptography.Asn1.GeneralNameAsn[] Issuer; internal ReadOnlyMemory<byte> SerialNumber; internal void Encode(AsnWriter writer) { Encode(writer, Asn1Tag.Sequence); } internal void Encode(AsnWriter writer, Asn1Tag tag) { writer.PushSequence(tag); writer.PushSequence(); for (int i = 0; i < Issuer.Length; i++) { Issuer[i].Encode(writer); } writer.PopSequence(); writer.WriteInteger(SerialNumber.Span); writer.PopSequence(tag); } internal static CadesIssuerSerial Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet) { return Decode(Asn1Tag.Sequence, encoded, ruleSet); } internal static CadesIssuerSerial Decode(Asn1Tag expectedTag, ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet) { try { AsnValueReader reader = new AsnValueReader(encoded.Span, ruleSet); DecodeCore(ref reader, expectedTag, encoded, out CadesIssuerSerial decoded); reader.ThrowIfNotEmpty(); return decoded; } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory<byte> rebind, out CadesIssuerSerial decoded) { Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded); } internal static void Decode(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out CadesIssuerSerial decoded) { try { DecodeCore(ref reader, expectedTag, rebind, out decoded); } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } private static void DecodeCore(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out CadesIssuerSerial decoded) { decoded = default; AsnValueReader sequenceReader = reader.ReadSequence(expectedTag); AsnValueReader collectionReader; ReadOnlySpan<byte> rebindSpan = rebind.Span; int offset; ReadOnlySpan<byte> tmpSpan; // Decode SEQUENCE OF for Issuer { collectionReader = sequenceReader.ReadSequence(); var tmpList = new List<System.Security.Cryptography.Asn1.GeneralNameAsn>(); System.Security.Cryptography.Asn1.GeneralNameAsn tmpItem; while (collectionReader.HasData) { System.Security.Cryptography.Asn1.GeneralNameAsn.Decode(ref collectionReader, rebind, out tmpItem); tmpList.Add(tmpItem); } decoded.Issuer = tmpList.ToArray(); } tmpSpan = sequenceReader.ReadIntegerBytes(); decoded.SerialNumber = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray(); sequenceReader.ThrowIfNotEmpty(); } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/tools/dotnet-pgo/SPGO/PreciseDebugInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Diagnostics.Tools.Pgo { internal record class PreciseDebugInfo( ulong MethodID, InlineContext InlineTree, List<PreciseIPMapping> Mappings); internal record class InlineContext( uint Ordinal, ulong MethodID, string MethodName, List<InlineContext> Inlinees); internal record class PreciseIPMapping( uint NativeOffset, uint InlineContext, uint ILOffset); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Diagnostics.Tools.Pgo { internal record class PreciseDebugInfo( ulong MethodID, InlineContext InlineTree, List<PreciseIPMapping> Mappings); internal record class InlineContext( uint Ordinal, ulong MethodID, string MethodName, List<InlineContext> Inlinees); internal record class PreciseIPMapping( uint NativeOffset, uint InlineContext, uint ILOffset); }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseException.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.ComponentModel { /// <summary> /// Represents the exception thrown when a component cannot be granted a license. /// </summary> [Serializable] [TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class LicenseException : SystemException { private const int LicenseHResult = unchecked((int)0x80131901); private readonly object? _instance; /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.LicenseException'/> class for the /// specified type. /// </summary> public LicenseException(Type? type) : this(type, null, SR.Format(SR.LicExceptionTypeOnly, type?.FullName)) { } /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.LicenseException'/> class for the /// specified type and instance. /// </summary> public LicenseException(Type? type, object? instance) : this(type, null, SR.Format(SR.LicExceptionTypeAndInstance, type?.FullName, instance?.GetType().FullName)) { } /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.LicenseException'/> class for the /// specified type and instance with the specified message. /// </summary> public LicenseException(Type? type, object? instance, string? message) : base(message) { LicensedType = type; _instance = instance; HResult = LicenseHResult; } /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.LicenseException'/> class for the /// specified innerException, type and instance with the specified message. /// </summary> public LicenseException(Type? type, object? instance, string? message, Exception? innerException) : base(message, innerException) { LicensedType = type; _instance = instance; HResult = LicenseHResult; } /// <summary> /// Need this constructor since Exception implements ISerializable. /// </summary> protected LicenseException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Gets the type of the component that was not granted a license. /// </summary> public Type? LicensedType { get; } /// <summary> /// Need this since Exception implements ISerializable. /// </summary> public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("type", null); // Type is not serializable. info.AddValue("instance", _instance); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.ComponentModel { /// <summary> /// Represents the exception thrown when a component cannot be granted a license. /// </summary> [Serializable] [TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class LicenseException : SystemException { private const int LicenseHResult = unchecked((int)0x80131901); private readonly object? _instance; /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.LicenseException'/> class for the /// specified type. /// </summary> public LicenseException(Type? type) : this(type, null, SR.Format(SR.LicExceptionTypeOnly, type?.FullName)) { } /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.LicenseException'/> class for the /// specified type and instance. /// </summary> public LicenseException(Type? type, object? instance) : this(type, null, SR.Format(SR.LicExceptionTypeAndInstance, type?.FullName, instance?.GetType().FullName)) { } /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.LicenseException'/> class for the /// specified type and instance with the specified message. /// </summary> public LicenseException(Type? type, object? instance, string? message) : base(message) { LicensedType = type; _instance = instance; HResult = LicenseHResult; } /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.LicenseException'/> class for the /// specified innerException, type and instance with the specified message. /// </summary> public LicenseException(Type? type, object? instance, string? message, Exception? innerException) : base(message, innerException) { LicensedType = type; _instance = instance; HResult = LicenseHResult; } /// <summary> /// Need this constructor since Exception implements ISerializable. /// </summary> protected LicenseException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Gets the type of the component that was not granted a license. /// </summary> public Type? LicensedType { get; } /// <summary> /// Need this since Exception implements ISerializable. /// </summary> public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("type", null); // Type is not serializable. info.AddValue("instance", _instance); } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeExceptionHandlingClause.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace System.Reflection { internal sealed class RuntimeExceptionHandlingClause : ExceptionHandlingClause { // This class can only be created from inside the EE. private RuntimeExceptionHandlingClause() { } private RuntimeMethodBody _methodBody = null!; private ExceptionHandlingClauseOptions _flags; private int _tryOffset; private int _tryLength; private int _handlerOffset; private int _handlerLength; private int _catchMetadataToken; private int _filterOffset; public override ExceptionHandlingClauseOptions Flags => _flags; public override int TryOffset => _tryOffset; public override int TryLength => _tryLength; public override int HandlerOffset => _handlerOffset; public override int HandlerLength => _handlerLength; public override int FilterOffset { get { if (_flags != ExceptionHandlingClauseOptions.Filter) throw new InvalidOperationException(SR.Arg_EHClauseNotFilter); return _filterOffset; } } public override Type? CatchType { [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Module.ResolveType is marked as RequiresUnreferencedCode because it relies on tokens" + "which are not guaranteed to be stable across trimming. So if somebody hardcodes a token it could break." + "The usage here is not like that as all these tokens come from existing metadata loaded from some IL" + "and so trimming has no effect (the tokens are read AFTER trimming occured).")] get { if (_flags != ExceptionHandlingClauseOptions.Clause) throw new InvalidOperationException(SR.Arg_EHClauseNotClause); Type? type = null; if (!MetadataToken.IsNullToken(_catchMetadataToken)) { Type? declaringType = _methodBody._methodBase.DeclaringType; Module module = (declaringType == null) ? _methodBody._methodBase.Module : declaringType.Module; type = module.ResolveType(_catchMetadataToken, declaringType?.GetGenericArguments(), _methodBody._methodBase is MethodInfo ? _methodBody._methodBase.GetGenericArguments() : null); } return type; } } public override string ToString() { if (Flags == ExceptionHandlingClauseOptions.Clause) { return string.Format(CultureInfo.CurrentUICulture, "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}, CatchType={5}", Flags, TryOffset, TryLength, HandlerOffset, HandlerLength, CatchType); } if (Flags == ExceptionHandlingClauseOptions.Filter) { return string.Format(CultureInfo.CurrentUICulture, "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}, FilterOffset={5}", Flags, TryOffset, TryLength, HandlerOffset, HandlerLength, FilterOffset); } return string.Format(CultureInfo.CurrentUICulture, "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}", Flags, TryOffset, TryLength, HandlerOffset, HandlerLength); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace System.Reflection { internal sealed class RuntimeExceptionHandlingClause : ExceptionHandlingClause { // This class can only be created from inside the EE. private RuntimeExceptionHandlingClause() { } private RuntimeMethodBody _methodBody = null!; private ExceptionHandlingClauseOptions _flags; private int _tryOffset; private int _tryLength; private int _handlerOffset; private int _handlerLength; private int _catchMetadataToken; private int _filterOffset; public override ExceptionHandlingClauseOptions Flags => _flags; public override int TryOffset => _tryOffset; public override int TryLength => _tryLength; public override int HandlerOffset => _handlerOffset; public override int HandlerLength => _handlerLength; public override int FilterOffset { get { if (_flags != ExceptionHandlingClauseOptions.Filter) throw new InvalidOperationException(SR.Arg_EHClauseNotFilter); return _filterOffset; } } public override Type? CatchType { [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Module.ResolveType is marked as RequiresUnreferencedCode because it relies on tokens" + "which are not guaranteed to be stable across trimming. So if somebody hardcodes a token it could break." + "The usage here is not like that as all these tokens come from existing metadata loaded from some IL" + "and so trimming has no effect (the tokens are read AFTER trimming occured).")] get { if (_flags != ExceptionHandlingClauseOptions.Clause) throw new InvalidOperationException(SR.Arg_EHClauseNotClause); Type? type = null; if (!MetadataToken.IsNullToken(_catchMetadataToken)) { Type? declaringType = _methodBody._methodBase.DeclaringType; Module module = (declaringType == null) ? _methodBody._methodBase.Module : declaringType.Module; type = module.ResolveType(_catchMetadataToken, declaringType?.GetGenericArguments(), _methodBody._methodBase is MethodInfo ? _methodBody._methodBase.GetGenericArguments() : null); } return type; } } public override string ToString() { if (Flags == ExceptionHandlingClauseOptions.Clause) { return string.Format(CultureInfo.CurrentUICulture, "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}, CatchType={5}", Flags, TryOffset, TryLength, HandlerOffset, HandlerLength, CatchType); } if (Flags == ExceptionHandlingClauseOptions.Filter) { return string.Format(CultureInfo.CurrentUICulture, "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}, FilterOffset={5}", Flags, TryOffset, TryLength, HandlerOffset, HandlerLength, FilterOffset); } return string.Format(CultureInfo.CurrentUICulture, "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}", Flags, TryOffset, TryLength, HandlerOffset, HandlerLength); } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/Methodical/eh/generics/throwincatch_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="throwincatch.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\common\eh_common.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="throwincatch.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\common\eh_common.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyWideningUpper.Vector128.Byte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyWideningUpper_Vector128_Byte() { var test = new SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte testClass) { var result = AdvSimd.MultiplyWideningUpper(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = AdvSimd.MultiplyWideningUpper( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyWideningUpper( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyWideningUpper( AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyWideningUpper), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyWideningUpper), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyWideningUpper( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.MultiplyWideningUpper( AdvSimd.LoadVector128((Byte*)(pClsVar1)), AdvSimd.LoadVector128((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = AdvSimd.MultiplyWideningUpper(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.MultiplyWideningUpper(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte(); var result = AdvSimd.MultiplyWideningUpper(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = AdvSimd.MultiplyWideningUpper( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyWideningUpper(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = AdvSimd.MultiplyWideningUpper( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyWideningUpper(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyWideningUpper( AdvSimd.LoadVector128((Byte*)(&test._fld1)), AdvSimd.LoadVector128((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyWideningUpper(left, right, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyWideningUpper)}<UInt16>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyWideningUpper_Vector128_Byte() { var test = new SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte testClass) { var result = AdvSimd.MultiplyWideningUpper(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = AdvSimd.MultiplyWideningUpper( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyWideningUpper( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyWideningUpper( AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyWideningUpper), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyWideningUpper), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyWideningUpper( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.MultiplyWideningUpper( AdvSimd.LoadVector128((Byte*)(pClsVar1)), AdvSimd.LoadVector128((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = AdvSimd.MultiplyWideningUpper(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.MultiplyWideningUpper(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte(); var result = AdvSimd.MultiplyWideningUpper(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__MultiplyWideningUpper_Vector128_Byte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = AdvSimd.MultiplyWideningUpper( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyWideningUpper(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = AdvSimd.MultiplyWideningUpper( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyWideningUpper(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyWideningUpper( AdvSimd.LoadVector128((Byte*)(&test._fld1)), AdvSimd.LoadVector128((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyWideningUpper(left, right, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyWideningUpper)}<UInt16>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/DelegateMarshaller.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Microsoft.Interop { public sealed class DelegateMarshaller : IMarshallingGenerator { public bool IsSupported(TargetFramework target, Version version) => true; public TypeSyntax AsNativeType(TypePositionInfo info) { return MarshallerHelpers.SystemIntPtrType; } public ParameterSyntax AsParameter(TypePositionInfo info) { TypeSyntax type = info.IsByRef ? PointerType(AsNativeType(info)) : AsNativeType(info); return Parameter(Identifier(info.InstanceIdentifier)) .WithType(type); } public ArgumentSyntax AsArgument(TypePositionInfo info, StubCodeContext context) { string identifier = context.GetIdentifiers(info).native; if (info.IsByRef) { return Argument( PrefixUnaryExpression( SyntaxKind.AddressOfExpression, IdentifierName(identifier))); } return Argument(IdentifierName(identifier)); } public IEnumerable<StatementSyntax> Generate(TypePositionInfo info, StubCodeContext context) { // [TODO] Handle byrefs in a more common place? // This pattern will become very common (arrays and strings will also use it) (string managedIdentifier, string nativeIdentifier) = context.GetIdentifiers(info); switch (context.CurrentStage) { case StubCodeContext.Stage.Setup: break; case StubCodeContext.Stage.Marshal: if (info.RefKind != RefKind.Out) { // <nativeIdentifier> = <managedIdentifier> != null ? Marshal.GetFunctionPointerForDelegate(<managedIdentifier>) : default; yield return ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName(nativeIdentifier), ConditionalExpression( BinaryExpression( SyntaxKind.NotEqualsExpression, IdentifierName(managedIdentifier), LiteralExpression(SyntaxKind.NullLiteralExpression) ), InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, ParseName(TypeNames.System_Runtime_InteropServices_Marshal), IdentifierName("GetFunctionPointerForDelegate")), ArgumentList(SingletonSeparatedList(Argument(IdentifierName(managedIdentifier))))), LiteralExpression(SyntaxKind.DefaultLiteralExpression)))); } break; case StubCodeContext.Stage.Unmarshal: if (info.IsManagedReturnPosition || (info.IsByRef && info.RefKind != RefKind.In)) { // <managedIdentifier> = <nativeIdentifier> != default : Marshal.GetDelegateForFunctionPointer<<managedType>>(<nativeIdentifier>) : null; yield return ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName(managedIdentifier), ConditionalExpression( BinaryExpression( SyntaxKind.NotEqualsExpression, IdentifierName(nativeIdentifier), LiteralExpression(SyntaxKind.DefaultLiteralExpression)), InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, ParseName(TypeNames.System_Runtime_InteropServices_Marshal), GenericName(Identifier("GetDelegateForFunctionPointer")) .WithTypeArgumentList( TypeArgumentList( SingletonSeparatedList( info.ManagedType.Syntax)))), ArgumentList(SingletonSeparatedList(Argument(IdentifierName(nativeIdentifier))))), LiteralExpression(SyntaxKind.NullLiteralExpression)))); } break; case StubCodeContext.Stage.KeepAlive: if (info.RefKind != RefKind.Out) { yield return ExpressionStatement( InvocationExpression( ParseName("global::System.GC.KeepAlive"), ArgumentList(SingletonSeparatedList(Argument(IdentifierName(managedIdentifier)))))); } break; default: break; } } public bool UsesNativeIdentifier(TypePositionInfo info, StubCodeContext context) => true; public bool SupportsByValueMarshalKind(ByValueContentsMarshalKind marshalKind, StubCodeContext context) => false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Microsoft.Interop { public sealed class DelegateMarshaller : IMarshallingGenerator { public bool IsSupported(TargetFramework target, Version version) => true; public TypeSyntax AsNativeType(TypePositionInfo info) { return MarshallerHelpers.SystemIntPtrType; } public ParameterSyntax AsParameter(TypePositionInfo info) { TypeSyntax type = info.IsByRef ? PointerType(AsNativeType(info)) : AsNativeType(info); return Parameter(Identifier(info.InstanceIdentifier)) .WithType(type); } public ArgumentSyntax AsArgument(TypePositionInfo info, StubCodeContext context) { string identifier = context.GetIdentifiers(info).native; if (info.IsByRef) { return Argument( PrefixUnaryExpression( SyntaxKind.AddressOfExpression, IdentifierName(identifier))); } return Argument(IdentifierName(identifier)); } public IEnumerable<StatementSyntax> Generate(TypePositionInfo info, StubCodeContext context) { // [TODO] Handle byrefs in a more common place? // This pattern will become very common (arrays and strings will also use it) (string managedIdentifier, string nativeIdentifier) = context.GetIdentifiers(info); switch (context.CurrentStage) { case StubCodeContext.Stage.Setup: break; case StubCodeContext.Stage.Marshal: if (info.RefKind != RefKind.Out) { // <nativeIdentifier> = <managedIdentifier> != null ? Marshal.GetFunctionPointerForDelegate(<managedIdentifier>) : default; yield return ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName(nativeIdentifier), ConditionalExpression( BinaryExpression( SyntaxKind.NotEqualsExpression, IdentifierName(managedIdentifier), LiteralExpression(SyntaxKind.NullLiteralExpression) ), InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, ParseName(TypeNames.System_Runtime_InteropServices_Marshal), IdentifierName("GetFunctionPointerForDelegate")), ArgumentList(SingletonSeparatedList(Argument(IdentifierName(managedIdentifier))))), LiteralExpression(SyntaxKind.DefaultLiteralExpression)))); } break; case StubCodeContext.Stage.Unmarshal: if (info.IsManagedReturnPosition || (info.IsByRef && info.RefKind != RefKind.In)) { // <managedIdentifier> = <nativeIdentifier> != default : Marshal.GetDelegateForFunctionPointer<<managedType>>(<nativeIdentifier>) : null; yield return ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName(managedIdentifier), ConditionalExpression( BinaryExpression( SyntaxKind.NotEqualsExpression, IdentifierName(nativeIdentifier), LiteralExpression(SyntaxKind.DefaultLiteralExpression)), InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, ParseName(TypeNames.System_Runtime_InteropServices_Marshal), GenericName(Identifier("GetDelegateForFunctionPointer")) .WithTypeArgumentList( TypeArgumentList( SingletonSeparatedList( info.ManagedType.Syntax)))), ArgumentList(SingletonSeparatedList(Argument(IdentifierName(nativeIdentifier))))), LiteralExpression(SyntaxKind.NullLiteralExpression)))); } break; case StubCodeContext.Stage.KeepAlive: if (info.RefKind != RefKind.Out) { yield return ExpressionStatement( InvocationExpression( ParseName("global::System.GC.KeepAlive"), ArgumentList(SingletonSeparatedList(Argument(IdentifierName(managedIdentifier)))))); } break; default: break; } } public bool UsesNativeIdentifier(TypePositionInfo info, StubCodeContext context) => true; public bool SupportsByValueMarshalKind(ByValueContentsMarshalKind marshalKind, StubCodeContext context) => false; } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Globalization/tests/System/Globalization/CharUnicodeInfoTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; using System.Reflection; namespace System.Globalization.Tests { public partial class CharUnicodeInfoTests { private const int HIGHEST_CODE_POINT = 0x10_FFFF; [Fact] public void GetUnicodeCategory() { MethodInfo GetBidiCategory = Type.GetType("System.Globalization.CharUnicodeInfo").GetMethod("GetBidiCategoryNoBoundsChecks", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.InvokeMethod); object [] parameters = new object [] { 0 }; foreach (CharUnicodeInfoTestCase testCase in CharUnicodeInfoTestData.TestCases) { if (testCase.Utf32CodeValue.Length == 1) { // Test the char overload for a single char GetUnicodeCategoryTest_Char(testCase.Utf32CodeValue[0], testCase.GeneralCategory); } // Test the string overload for a surrogate pair or a single char GetUnicodeCategoryTest_String(testCase.Utf32CodeValue, new UnicodeCategory[] { testCase.GeneralCategory }); Assert.Equal(testCase.GeneralCategory, CharUnicodeInfo.GetUnicodeCategory(testCase.CodePoint)); parameters[0] = (uint)testCase.CodePoint; Assert.Equal(testCase.BidiCategory, (StrongBidiCategory)GetBidiCategory.Invoke(null, parameters)); } } [Theory] [InlineData('\uFFFF', UnicodeCategory.OtherNotAssigned)] public void GetUnicodeCategoryTest_Char(char ch, UnicodeCategory expected) { UnicodeCategory actual = CharUnicodeInfo.GetUnicodeCategory(ch); Assert.True(actual == expected, ErrorMessage(ch, expected, actual)); } [Theory] [InlineData("aA1!", new UnicodeCategory[] { UnicodeCategory.LowercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.OtherPunctuation })] [InlineData("\uD808\uDF6C", new UnicodeCategory[] { UnicodeCategory.OtherLetter, UnicodeCategory.Surrogate })] [InlineData("a\uD808\uDF6Ca", new UnicodeCategory[] { UnicodeCategory.LowercaseLetter, UnicodeCategory.OtherLetter, UnicodeCategory.Surrogate, UnicodeCategory.LowercaseLetter })] public void GetUnicodeCategoryTest_String(string s, UnicodeCategory[] expected) { for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], CharUnicodeInfo.GetUnicodeCategory(s, i)); } } [Fact] public void GetUnicodeCategory_String_InvalidSurrogatePairs() { // High, high surrogate pair GetUnicodeCategoryTest_String("\uD808\uD808", new UnicodeCategory[] { UnicodeCategory.Surrogate, UnicodeCategory.Surrogate }); // Low, low surrogate pair GetUnicodeCategoryTest_String("\uDF6C\uDF6C", new UnicodeCategory[] { UnicodeCategory.Surrogate, UnicodeCategory.Surrogate }); // Low, high surrogate pair GetUnicodeCategoryTest_String("\uDF6C\uD808", new UnicodeCategory[] { UnicodeCategory.Surrogate, UnicodeCategory.Surrogate }); } [Fact] public void GetUnicodeCategory_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => CharUnicodeInfo.GetUnicodeCategory(null, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetUnicodeCategory("abc", -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetUnicodeCategory("abc", 3)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetUnicodeCategory("", 0)); } [Fact] public void GetNumericValue() { foreach (CharUnicodeInfoTestCase testCase in CharUnicodeInfoTestData.TestCases) { if (testCase.Utf32CodeValue.Length == 1) { // Test the char overload for a single char GetNumericValueTest_Char(testCase.Utf32CodeValue[0], testCase.NumericValue); } // Test the string overload for a surrogate pair GetNumericValueTest_String(testCase.Utf32CodeValue, new double[] { testCase.NumericValue }); } } [Theory] [InlineData('\uFFFF', -1)] public void GetNumericValueTest_Char(char ch, double expected) { double actual = CharUnicodeInfo.GetNumericValue(ch); Assert.True(expected == actual, ErrorMessage(ch, expected, actual)); } [Theory] [MemberData(nameof(s_GetNumericValueData))] public void GetNumericValueTest_String(string s, double[] expected) { for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], CharUnicodeInfo.GetNumericValue(s, i)); } } public static readonly object[][] s_GetNumericValueData = { new object[] {"aA1!", new double[] { -1, -1, 1, -1 }}, // Numeric supplementary plane code point (U+12455 CUNEIFORM NUMERIC SIGN FIVE BAN2 VARIANT FORM) new object[] {"\uD809\uDC55", new double[] { 5, -1 }}, new object[] {"a\uD809\uDC55a", new double[] { -1, 5, -1 , -1 }}, // Non-numeric supplementary plane code point (U+1236C CUNEIFORM SIGN ZU5 TIMES A) new object[] {"\uD808\uDF6C", new double[] { -1, -1 }}, new object[] {"a\uD808\uDF6Ca", new double[] { -1, -1, -1, -1 }}, }; [Fact] public void GetNumericValue_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => CharUnicodeInfo.GetNumericValue(null, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetNumericValue("abc", -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetNumericValue("abc", 3)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetNumericValue("", 0)); } private static string ErrorMessage(char ch, object expected, object actual) { return $"CodeValue: {(int)ch:X}; Expected: {expected}; Actual: {actual}"; } public static string s_numericsCodepoints = "\u0030\u0031\u0032\u0033\u0034\u0035\u0036\u0037\u0038\u0039" + "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669" + "\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9" + "\u07c0\u07c1\u07c2\u07c3\u07c4\u07c5\u07c6\u07c7\u07c8\u07c9" + "\u0966\u0967\u0968\u0969\u096a\u096b\u096c\u096d\u096e\u096f" + "\u09e6\u09e7\u09e8\u09e9\u09ea\u09eb\u09ec\u09ed\u09ee\u09ef" + "\u0a66\u0a67\u0a68\u0a69\u0a6a\u0a6b\u0a6c\u0a6d\u0a6e\u0a6f" + "\u0ae6\u0ae7\u0ae8\u0ae9\u0aea\u0aeb\u0aec\u0aed\u0aee\u0aef" + "\u0b66\u0b67\u0b68\u0b69\u0b6a\u0b6b\u0b6c\u0b6d\u0b6e\u0b6f" + "\u0be6\u0be7\u0be8\u0be9\u0bea\u0beb\u0bec\u0bed\u0bee\u0bef" + "\u0c66\u0c67\u0c68\u0c69\u0c6a\u0c6b\u0c6c\u0c6d\u0c6e\u0c6f" + "\u0ce6\u0ce7\u0ce8\u0ce9\u0cea\u0ceb\u0cec\u0ced\u0cee\u0cef" + "\u0d66\u0d67\u0d68\u0d69\u0d6a\u0d6b\u0d6c\u0d6d\u0d6e\u0d6f" + "\u0e50\u0e51\u0e52\u0e53\u0e54\u0e55\u0e56\u0e57\u0e58\u0e59" + "\u0ed0\u0ed1\u0ed2\u0ed3\u0ed4\u0ed5\u0ed6\u0ed7\u0ed8\u0ed9" + "\u0f20\u0f21\u0f22\u0f23\u0f24\u0f25\u0f26\u0f27\u0f28\u0f29" + "\u1040\u1041\u1042\u1043\u1044\u1045\u1046\u1047\u1048\u1049" + "\u1090\u1091\u1092\u1093\u1094\u1095\u1096\u1097\u1098\u1099" + "\u17e0\u17e1\u17e2\u17e3\u17e4\u17e5\u17e6\u17e7\u17e8\u17e9" + "\u1810\u1811\u1812\u1813\u1814\u1815\u1816\u1817\u1818\u1819" + "\u1946\u1947\u1948\u1949\u194a\u194b\u194c\u194d\u194e\u194f" + "\u19d0\u19d1\u19d2\u19d3\u19d4\u19d5\u19d6\u19d7\u19d8\u19d9" + "\u1a80\u1a81\u1a82\u1a83\u1a84\u1a85\u1a86\u1a87\u1a88\u1a89" + "\u1a90\u1a91\u1a92\u1a93\u1a94\u1a95\u1a96\u1a97\u1a98\u1a99" + "\u1b50\u1b51\u1b52\u1b53\u1b54\u1b55\u1b56\u1b57\u1b58\u1b59" + "\u1bb0\u1bb1\u1bb2\u1bb3\u1bb4\u1bb5\u1bb6\u1bb7\u1bb8\u1bb9" + "\u1c40\u1c41\u1c42\u1c43\u1c44\u1c45\u1c46\u1c47\u1c48\u1c49" + "\u1c50\u1c51\u1c52\u1c53\u1c54\u1c55\u1c56\u1c57\u1c58\u1c59" + "\ua620\ua621\ua622\ua623\ua624\ua625\ua626\ua627\ua628\ua629" + "\ua8d0\ua8d1\ua8d2\ua8d3\ua8d4\ua8d5\ua8d6\ua8d7\ua8d8\ua8d9" + "\ua900\ua901\ua902\ua903\ua904\ua905\ua906\ua907\ua908\ua909" + "\ua9d0\ua9d1\ua9d2\ua9d3\ua9d4\ua9d5\ua9d6\ua9d7\ua9d8\ua9d9" + "\uaa50\uaa51\uaa52\uaa53\uaa54\uaa55\uaa56\uaa57\uaa58\uaa59" + "\uabf0\uabf1\uabf2\uabf3\uabf4\uabf5\uabf6\uabf7\uabf8\uabf9" + "\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19"; public static string s_nonNumericsCodepoints = "abcdefghijklmnopqrstuvwxyz" + "\u1369\u136a\u136b\u136c\u136d\u136e\u136f\u1370\u1371\u1372\u1373" + "\u1374\u1375\u1376\u1377\u1378\u1379\u137a\u137b\u137c\u137d"; public static string s_numericNonDecimalCodepoints = "\u00b2\u00b3\u00b9\u1369\u136a\u136b\u136c\u136d\u136e\u136f\u1370" + "\u1371\u19da\u2070\u2074\u2075\u2076\u2077\u2078\u2079\u2080\u2081" + "\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u2460\u2461\u2462" + "\u2463\u2464\u2465\u2466\u2467\u2468\u2474\u2475\u2476\u2477\u2478" + "\u2479\u247a\u247b\u247c\u2488\u2489\u248a\u248b\u248c\u248d\u248e" + "\u248f\u2490\u24ea\u24f5\u24f6\u24f7\u24f8\u24f9\u24fa\u24fb\u24fc" + "\u24fd\u24ff\u2776\u2777\u2778\u2779\u277a\u277b\u277c\u277d\u277e" + "\u2780\u2781\u2782\u2783\u2784\u2785\u2786\u2787\u2788\u278a\u278b" + "\u278c\u278d\u278e\u278f\u2790\u2791\u2792"; public static int [] s_numericNonDecimalValues = new int [] { 2, 3, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; [Fact] public static void DigitsDecimalTest() { Assert.Equal(0, s_numericsCodepoints.Length % 10); for (int i=0; i < s_numericsCodepoints.Length; i+= 10) { for (int j=0; j < 10; j++) { Assert.Equal(j, CharUnicodeInfo.GetDecimalDigitValue(s_numericsCodepoints[i + j])); Assert.Equal(j, CharUnicodeInfo.GetDecimalDigitValue(s_numericsCodepoints, i + j)); } } } [Fact] public static void NegativeDigitsTest() { for (int i=0; i < s_nonNumericsCodepoints.Length; i++) { Assert.Equal(-1, CharUnicodeInfo.GetDecimalDigitValue(s_nonNumericsCodepoints[i])); Assert.Equal(-1, CharUnicodeInfo.GetDecimalDigitValue(s_nonNumericsCodepoints, i)); } } [Fact] public static void DigitsTest() { Assert.Equal(s_numericNonDecimalCodepoints.Length, s_numericNonDecimalValues.Length); for (int i=0; i < s_numericNonDecimalCodepoints.Length; i++) { Assert.Equal(s_numericNonDecimalValues[i], CharUnicodeInfo.GetDigitValue(s_numericNonDecimalCodepoints[i])); Assert.Equal(s_numericNonDecimalValues[i], CharUnicodeInfo.GetDigitValue(s_numericNonDecimalCodepoints, i)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; using System.Reflection; namespace System.Globalization.Tests { public partial class CharUnicodeInfoTests { private const int HIGHEST_CODE_POINT = 0x10_FFFF; [Fact] public void GetUnicodeCategory() { MethodInfo GetBidiCategory = Type.GetType("System.Globalization.CharUnicodeInfo").GetMethod("GetBidiCategoryNoBoundsChecks", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.InvokeMethod); object [] parameters = new object [] { 0 }; foreach (CharUnicodeInfoTestCase testCase in CharUnicodeInfoTestData.TestCases) { if (testCase.Utf32CodeValue.Length == 1) { // Test the char overload for a single char GetUnicodeCategoryTest_Char(testCase.Utf32CodeValue[0], testCase.GeneralCategory); } // Test the string overload for a surrogate pair or a single char GetUnicodeCategoryTest_String(testCase.Utf32CodeValue, new UnicodeCategory[] { testCase.GeneralCategory }); Assert.Equal(testCase.GeneralCategory, CharUnicodeInfo.GetUnicodeCategory(testCase.CodePoint)); parameters[0] = (uint)testCase.CodePoint; Assert.Equal(testCase.BidiCategory, (StrongBidiCategory)GetBidiCategory.Invoke(null, parameters)); } } [Theory] [InlineData('\uFFFF', UnicodeCategory.OtherNotAssigned)] public void GetUnicodeCategoryTest_Char(char ch, UnicodeCategory expected) { UnicodeCategory actual = CharUnicodeInfo.GetUnicodeCategory(ch); Assert.True(actual == expected, ErrorMessage(ch, expected, actual)); } [Theory] [InlineData("aA1!", new UnicodeCategory[] { UnicodeCategory.LowercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.OtherPunctuation })] [InlineData("\uD808\uDF6C", new UnicodeCategory[] { UnicodeCategory.OtherLetter, UnicodeCategory.Surrogate })] [InlineData("a\uD808\uDF6Ca", new UnicodeCategory[] { UnicodeCategory.LowercaseLetter, UnicodeCategory.OtherLetter, UnicodeCategory.Surrogate, UnicodeCategory.LowercaseLetter })] public void GetUnicodeCategoryTest_String(string s, UnicodeCategory[] expected) { for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], CharUnicodeInfo.GetUnicodeCategory(s, i)); } } [Fact] public void GetUnicodeCategory_String_InvalidSurrogatePairs() { // High, high surrogate pair GetUnicodeCategoryTest_String("\uD808\uD808", new UnicodeCategory[] { UnicodeCategory.Surrogate, UnicodeCategory.Surrogate }); // Low, low surrogate pair GetUnicodeCategoryTest_String("\uDF6C\uDF6C", new UnicodeCategory[] { UnicodeCategory.Surrogate, UnicodeCategory.Surrogate }); // Low, high surrogate pair GetUnicodeCategoryTest_String("\uDF6C\uD808", new UnicodeCategory[] { UnicodeCategory.Surrogate, UnicodeCategory.Surrogate }); } [Fact] public void GetUnicodeCategory_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => CharUnicodeInfo.GetUnicodeCategory(null, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetUnicodeCategory("abc", -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetUnicodeCategory("abc", 3)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetUnicodeCategory("", 0)); } [Fact] public void GetNumericValue() { foreach (CharUnicodeInfoTestCase testCase in CharUnicodeInfoTestData.TestCases) { if (testCase.Utf32CodeValue.Length == 1) { // Test the char overload for a single char GetNumericValueTest_Char(testCase.Utf32CodeValue[0], testCase.NumericValue); } // Test the string overload for a surrogate pair GetNumericValueTest_String(testCase.Utf32CodeValue, new double[] { testCase.NumericValue }); } } [Theory] [InlineData('\uFFFF', -1)] public void GetNumericValueTest_Char(char ch, double expected) { double actual = CharUnicodeInfo.GetNumericValue(ch); Assert.True(expected == actual, ErrorMessage(ch, expected, actual)); } [Theory] [MemberData(nameof(s_GetNumericValueData))] public void GetNumericValueTest_String(string s, double[] expected) { for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], CharUnicodeInfo.GetNumericValue(s, i)); } } public static readonly object[][] s_GetNumericValueData = { new object[] {"aA1!", new double[] { -1, -1, 1, -1 }}, // Numeric supplementary plane code point (U+12455 CUNEIFORM NUMERIC SIGN FIVE BAN2 VARIANT FORM) new object[] {"\uD809\uDC55", new double[] { 5, -1 }}, new object[] {"a\uD809\uDC55a", new double[] { -1, 5, -1 , -1 }}, // Non-numeric supplementary plane code point (U+1236C CUNEIFORM SIGN ZU5 TIMES A) new object[] {"\uD808\uDF6C", new double[] { -1, -1 }}, new object[] {"a\uD808\uDF6Ca", new double[] { -1, -1, -1, -1 }}, }; [Fact] public void GetNumericValue_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => CharUnicodeInfo.GetNumericValue(null, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetNumericValue("abc", -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetNumericValue("abc", 3)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => CharUnicodeInfo.GetNumericValue("", 0)); } private static string ErrorMessage(char ch, object expected, object actual) { return $"CodeValue: {(int)ch:X}; Expected: {expected}; Actual: {actual}"; } public static string s_numericsCodepoints = "\u0030\u0031\u0032\u0033\u0034\u0035\u0036\u0037\u0038\u0039" + "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669" + "\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9" + "\u07c0\u07c1\u07c2\u07c3\u07c4\u07c5\u07c6\u07c7\u07c8\u07c9" + "\u0966\u0967\u0968\u0969\u096a\u096b\u096c\u096d\u096e\u096f" + "\u09e6\u09e7\u09e8\u09e9\u09ea\u09eb\u09ec\u09ed\u09ee\u09ef" + "\u0a66\u0a67\u0a68\u0a69\u0a6a\u0a6b\u0a6c\u0a6d\u0a6e\u0a6f" + "\u0ae6\u0ae7\u0ae8\u0ae9\u0aea\u0aeb\u0aec\u0aed\u0aee\u0aef" + "\u0b66\u0b67\u0b68\u0b69\u0b6a\u0b6b\u0b6c\u0b6d\u0b6e\u0b6f" + "\u0be6\u0be7\u0be8\u0be9\u0bea\u0beb\u0bec\u0bed\u0bee\u0bef" + "\u0c66\u0c67\u0c68\u0c69\u0c6a\u0c6b\u0c6c\u0c6d\u0c6e\u0c6f" + "\u0ce6\u0ce7\u0ce8\u0ce9\u0cea\u0ceb\u0cec\u0ced\u0cee\u0cef" + "\u0d66\u0d67\u0d68\u0d69\u0d6a\u0d6b\u0d6c\u0d6d\u0d6e\u0d6f" + "\u0e50\u0e51\u0e52\u0e53\u0e54\u0e55\u0e56\u0e57\u0e58\u0e59" + "\u0ed0\u0ed1\u0ed2\u0ed3\u0ed4\u0ed5\u0ed6\u0ed7\u0ed8\u0ed9" + "\u0f20\u0f21\u0f22\u0f23\u0f24\u0f25\u0f26\u0f27\u0f28\u0f29" + "\u1040\u1041\u1042\u1043\u1044\u1045\u1046\u1047\u1048\u1049" + "\u1090\u1091\u1092\u1093\u1094\u1095\u1096\u1097\u1098\u1099" + "\u17e0\u17e1\u17e2\u17e3\u17e4\u17e5\u17e6\u17e7\u17e8\u17e9" + "\u1810\u1811\u1812\u1813\u1814\u1815\u1816\u1817\u1818\u1819" + "\u1946\u1947\u1948\u1949\u194a\u194b\u194c\u194d\u194e\u194f" + "\u19d0\u19d1\u19d2\u19d3\u19d4\u19d5\u19d6\u19d7\u19d8\u19d9" + "\u1a80\u1a81\u1a82\u1a83\u1a84\u1a85\u1a86\u1a87\u1a88\u1a89" + "\u1a90\u1a91\u1a92\u1a93\u1a94\u1a95\u1a96\u1a97\u1a98\u1a99" + "\u1b50\u1b51\u1b52\u1b53\u1b54\u1b55\u1b56\u1b57\u1b58\u1b59" + "\u1bb0\u1bb1\u1bb2\u1bb3\u1bb4\u1bb5\u1bb6\u1bb7\u1bb8\u1bb9" + "\u1c40\u1c41\u1c42\u1c43\u1c44\u1c45\u1c46\u1c47\u1c48\u1c49" + "\u1c50\u1c51\u1c52\u1c53\u1c54\u1c55\u1c56\u1c57\u1c58\u1c59" + "\ua620\ua621\ua622\ua623\ua624\ua625\ua626\ua627\ua628\ua629" + "\ua8d0\ua8d1\ua8d2\ua8d3\ua8d4\ua8d5\ua8d6\ua8d7\ua8d8\ua8d9" + "\ua900\ua901\ua902\ua903\ua904\ua905\ua906\ua907\ua908\ua909" + "\ua9d0\ua9d1\ua9d2\ua9d3\ua9d4\ua9d5\ua9d6\ua9d7\ua9d8\ua9d9" + "\uaa50\uaa51\uaa52\uaa53\uaa54\uaa55\uaa56\uaa57\uaa58\uaa59" + "\uabf0\uabf1\uabf2\uabf3\uabf4\uabf5\uabf6\uabf7\uabf8\uabf9" + "\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19"; public static string s_nonNumericsCodepoints = "abcdefghijklmnopqrstuvwxyz" + "\u1369\u136a\u136b\u136c\u136d\u136e\u136f\u1370\u1371\u1372\u1373" + "\u1374\u1375\u1376\u1377\u1378\u1379\u137a\u137b\u137c\u137d"; public static string s_numericNonDecimalCodepoints = "\u00b2\u00b3\u00b9\u1369\u136a\u136b\u136c\u136d\u136e\u136f\u1370" + "\u1371\u19da\u2070\u2074\u2075\u2076\u2077\u2078\u2079\u2080\u2081" + "\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u2460\u2461\u2462" + "\u2463\u2464\u2465\u2466\u2467\u2468\u2474\u2475\u2476\u2477\u2478" + "\u2479\u247a\u247b\u247c\u2488\u2489\u248a\u248b\u248c\u248d\u248e" + "\u248f\u2490\u24ea\u24f5\u24f6\u24f7\u24f8\u24f9\u24fa\u24fb\u24fc" + "\u24fd\u24ff\u2776\u2777\u2778\u2779\u277a\u277b\u277c\u277d\u277e" + "\u2780\u2781\u2782\u2783\u2784\u2785\u2786\u2787\u2788\u278a\u278b" + "\u278c\u278d\u278e\u278f\u2790\u2791\u2792"; public static int [] s_numericNonDecimalValues = new int [] { 2, 3, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; [Fact] public static void DigitsDecimalTest() { Assert.Equal(0, s_numericsCodepoints.Length % 10); for (int i=0; i < s_numericsCodepoints.Length; i+= 10) { for (int j=0; j < 10; j++) { Assert.Equal(j, CharUnicodeInfo.GetDecimalDigitValue(s_numericsCodepoints[i + j])); Assert.Equal(j, CharUnicodeInfo.GetDecimalDigitValue(s_numericsCodepoints, i + j)); } } } [Fact] public static void NegativeDigitsTest() { for (int i=0; i < s_nonNumericsCodepoints.Length; i++) { Assert.Equal(-1, CharUnicodeInfo.GetDecimalDigitValue(s_nonNumericsCodepoints[i])); Assert.Equal(-1, CharUnicodeInfo.GetDecimalDigitValue(s_nonNumericsCodepoints, i)); } } [Fact] public static void DigitsTest() { Assert.Equal(s_numericNonDecimalCodepoints.Length, s_numericNonDecimalValues.Length); for (int i=0; i < s_numericNonDecimalCodepoints.Length; i++) { Assert.Equal(s_numericNonDecimalValues[i], CharUnicodeInfo.GetDigitValue(s_numericNonDecimalCodepoints[i])); Assert.Equal(s_numericNonDecimalValues[i], CharUnicodeInfo.GetDigitValue(s_numericNonDecimalCodepoints, i)); } } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Diagnostics.StackTrace/src/System/Diagnostics/SymbolStore/ISymbolVariable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Diagnostics.SymbolStore { public interface ISymbolVariable { // Get the name of this variable. string Name { get; } // Get the attributes of this variable. object Attributes { get; } // Get the signature of this variable. byte[] GetSignature(); SymAddressKind AddressKind { get; } int AddressField1 { get; } int AddressField2 { get; } int AddressField3 { get; } // Get the start/end offsets of this variable within its // parent. If this is a local variable within a scope, these will // fall within the offsets defined for the scope. int StartOffset { get; } int EndOffset { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Diagnostics.SymbolStore { public interface ISymbolVariable { // Get the name of this variable. string Name { get; } // Get the attributes of this variable. object Attributes { get; } // Get the signature of this variable. byte[] GetSignature(); SymAddressKind AddressKind { get; } int AddressField1 { get; } int AddressField2 { get; } int AddressField3 { get; } // Get the start/end offsets of this variable within its // parent. If this is a local variable within a scope, these will // fall within the offsets defined for the scope. int StartOffset { get; } int EndOffset { get; } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/Common/tests/System/Collections/IListTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Xunit; namespace Tests.Collections { public static class CollectionAssert { public static void Equal( IEnumerable expected, IEnumerable actual) { Assert.Equal( expected.OfType<object>(), actual.OfType<object>()); } public static void Equal(IList expected, IList actual) { Equal((IEnumerable) expected, actual); // explicitly test Count and the indexer Assert.Equal(expected.Count, actual.Count); for (var i = 0; i < expected.Count; i++) { var expectedArray = expected as Array; var actualArray = expected as Array; int expectedLowerBound = expectedArray == null ? 0 : expectedArray .GetLowerBound(0); int actualLowerBound = actualArray == null ? 0 : actualArray.GetLowerBound( 0); Assert.Equal( expected[i + expectedLowerBound], actual[i + actualLowerBound]); } } } public static class IListExtensions { public static void AddRange(this IList list, IEnumerable items) { foreach (object item in items) { list.Add(item); } } public static void InsertRange(this IList list, object[] items) { list.InsertRange(0, items, 0, items.Length); } public static void InsertRange( this IList list, int listStartIndex, object[] items, int startIndex, int count) { int numToInsert = items.Length - startIndex; if (count < numToInsert) { numToInsert = count; } for (var i = 0; i < numToInsert; i++) { list.Insert(listStartIndex + i, items[startIndex + i]); } } public static void AddRange( this IList list, object[] items, int startIndex, int count) { int numToAdd = items.Length - startIndex; if (count < numToAdd) { numToAdd = count; } for (var i = 0; i < numToAdd; i++) { list.Add(items[startIndex + i]); } } } public abstract class IListTest<T> : ICollectionTest<T> { private readonly bool _expectedIsFixedSize; private readonly bool _expectedIsReadOnly; private bool _searchingThrowsFromInvalidValue; protected IListTest( bool isSynchronized, bool isReadOnly, bool isFixedSize) : base(isSynchronized) { _expectedIsReadOnly = isReadOnly; _expectedIsFixedSize = isFixedSize; SearchingThrowsFromInvalidValue = false; } protected bool ExpectedIsReadOnly { get { return _expectedIsReadOnly; } } protected bool ExpectedIsFixedSize { get { return _expectedIsFixedSize; } } protected bool SearchingThrowsFromInvalidValue { get { return _searchingThrowsFromInvalidValue; } set { _searchingThrowsFromInvalidValue = value; } } public static object[][] RemoveAtInvalidData { get { return new[] { new object[] {int.MinValue, 16}, new object[] {-1, 16}, new object[] {0, 0}, new object[] {1, 1}, new object[] {16, 16} }; } } [Fact] public void IsFixedSize() { Assert.Equal(ExpectedIsFixedSize, GetList(null).IsFixedSize); } [Fact] public void IsReadOnly() { Assert.Equal(ExpectedIsReadOnly, GetList(null).IsReadOnly); } [Theory] [InlineData(int.MinValue)] [InlineData(-1)] [InlineData(0)] public void GetItemArgumentOutOfRange(int index) { IList list = GetList(null); Assert.Throws<ArgumentOutOfRangeException>( () => list[index]); CollectionAssert.Equal(Array.Empty<object>(), list); } [Fact] public void GetItemArgumentOutOfRangeFilledCollection() { object[] items = GenerateItems(32); IList list = GetList(items); Assert.Throws<ArgumentOutOfRangeException>( () => list[list.Count]); CollectionAssert.Equal(items, list); } [Fact] public void GetItemEmpty() { var items = new object[0]; IList list = GetList(items); if (ExpectedIsFixedSize || ExpectedIsReadOnly) { CollectionAssert.Equal(items, list); } else { list.Clear(); items = GenerateItems(1); list.AddRange(items); CollectionAssert.Equal(items, list); list.Clear(); items = GenerateItems(1024); list.AddRange(items); CollectionAssert.Equal(items, list); } } [Fact] public void SetItemNotSupported() { if (ExpectedIsReadOnly) { object[] items = GenerateItems(10); IList list = GetList(items); Assert.Throws<NotSupportedException>( () => list[0] = GenerateItem()); CollectionAssert.Equal(items, list); Assert.Throws<NotSupportedException>( () => list[list.Count - 1] = GenerateItem()); CollectionAssert.Equal(items, list); } } [Fact] public void SetItemArgumentException() { Type[] expectedExceptions; if (ExpectedIsReadOnly) { expectedExceptions = new[] { typeof (ArgumentOutOfRangeException), typeof (NotSupportedException) }; } else { expectedExceptions = new[] { typeof (ArgumentOutOfRangeException) }; } { object[] items = GenerateItems(10); IList list = GetList(items); AssertThrows( expectedExceptions, () => list[int.MinValue] = GenerateItem()); CollectionAssert.Equal(items, list); AssertThrows( expectedExceptions, () => list[-1] = GenerateItem()); CollectionAssert.Equal(items, list); } { object[] items = GenerateItems(0); IList list = GetList(items); AssertThrows( expectedExceptions, () => list[0] = GenerateItem()); CollectionAssert.Equal(items, list); if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { items = GenerateItems(32); list.AddRange(items); AssertThrows( expectedExceptions, () => list[list.Count] = GenerateItem()); CollectionAssert.Equal(items, list); } } } [Fact] public void SetItemInvalidValue() { object[] items = GenerateItems(32); IList list = GetList(items); if (IsGenericCompatibility) { foreach (object invalid in GetInvalidValues()) { Type[] expectedExceptions; if (invalid == null) { if (ExpectedIsReadOnly) { expectedExceptions = new[] { typeof (ArgumentNullException), typeof (NotSupportedException) }; } else { expectedExceptions = new[] { typeof (ArgumentNullException) }; } } else if (ExpectedIsReadOnly) { expectedExceptions = new[] { typeof (ArgumentException), typeof (NotSupportedException) }; } else { expectedExceptions = new[] { typeof (ArgumentException) }; } object invalid1 = invalid; AssertThrows( expectedExceptions, () => list[0] = invalid1); CollectionAssert.Equal(items, list); } } } [Fact] public void SetItemNonNull() { if (!ExpectedIsReadOnly) { if (ItemsMustBeNonNull) { object[] items = GenerateItems(32); IList list = GetList(items); Assert.Throws<ArgumentNullException>( () => list[0] = null); CollectionAssert.Equal(items, list); } } } [Fact] public void SetItemNullable() { if (!ExpectedIsReadOnly) { if (!ItemsMustBeNonNull) { object[] items = GenerateItems(32); IList list = GetList(items); list[0] = null; items[0] = null; CollectionAssert.Equal(items, list); items = GenerateItems(32); list = GetList(items); list[list.Count - 1] = null; items[items.Length - 1] = null; CollectionAssert.Equal(items, list); } } } [Fact] public void SetItemUnique() { if (!ExpectedIsReadOnly) { if (ItemsMustBeUnique) { object[] items = GenerateItems(32); IList list = GetList(items); Assert.Throws<ArgumentException>( () => list[0] = items[1]); CollectionAssert.Equal(items, list); } } } [Fact] public void SetItemNotUnique() { if (!ExpectedIsReadOnly) { if (!ItemsMustBeUnique) { object[] items = GenerateItems(32); IList list = GetList(items); for (var i = 0; i < items.Length; i++) { list[i] = items[items.Length - i - 1]; } Array.Reverse(items); CollectionAssert.Equal(items, list); } } } [Fact] public void SetItem() { if (!ExpectedIsReadOnly) { object[] items = GenerateItems(32); var origItems = (object[]) items.Clone(); IList list = GetList(items); // verify setting every item // reverse list, setting items to new elements to maintain uniqueness. for (var i = 0; i < items.Length; i++) { if (i < items.Length/2) { list[items.Length - i - 1] = GenerateItem(); } list[i] = items[items.Length - i - 1]; } Array.Reverse(items); CollectionAssert.Equal(items, list); // verify setting items back to the original items = origItems; if (ItemsMustBeUnique) { for (var i = 0; i < items.Length; i++) { list[i] = GenerateItem(); } } for (var i = 0; i < items.Length; i++) { list[i] = items[i]; } CollectionAssert.Equal(items, list); } } [Fact] public void AddFixedSizeOrReadonlyThrows() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { object[] items = GenerateItems(10); IList list = GetList(items); Assert.Throws<NotSupportedException>( () => list.Add(GenerateItem())); CollectionAssert.Equal(items, list); } } [Fact] public void AddWithNullValueInMiddle() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { const int size = 32; object[] items; IList list = GetList(null); object[] tempItems = GenerateItems(size); for (var i = 0; i < tempItems.Length/2; i++) { list.Add(tempItems[i]); } if (ItemsMustBeNonNull) { items = tempItems; Assert.Throws<ArgumentNullException>( () => list.Add(null)); } else { const int sizeWithNull = size + 1; items = new object[sizeWithNull]; list.Add(null); items[sizeWithNull/2] = null; Array.Copy(tempItems, items, sizeWithNull/2); Array.Copy( tempItems, sizeWithNull/2, items, sizeWithNull/2 + 1, sizeWithNull/2); } for (var i = 0; i < size/2; i++) { list.Add(tempItems[size/2 + i]); } CollectionAssert.Equal(items, list); } } [Fact] public void AddWithNullValueAtBeginning() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); object[] items; if (ItemsMustBeNonNull) { Assert.Throws<ArgumentNullException>( () => list.Add(null)); items = GenerateItems(16); list.AddRange(items); } else { const int size = 17; items = new object[size]; list.Add(null); items[0] = null; object[] tempItems = GenerateItems(size - 1); list.AddRange(tempItems); Array.Copy(tempItems, 0, items, 1, size - 1); } CollectionAssert.Equal(items, list); } } [Fact] public void AddWithNullValueAtEnd() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { object[] items = GenerateItems(16); IList list = GetList(items); if (ItemsMustBeNonNull) { Assert.Throws<ArgumentNullException>( () => list.Add(null)); } else { items[items.Length - 1] = null; list.RemoveAt(list.Count - 1); list.Add(null); } CollectionAssert.Equal(items, list); } } [Fact] public void AddDuplicateValue() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { object[] items; IList list = GetList(null); if (ItemsMustBeUnique) { items = GenerateItems(16); list.AddRange(items); Assert.Throws<ArgumentException>( () => list.Add(items[0])); } else { items = new object[32]; object[] tempItems = GenerateItems(16); list.AddRange(tempItems); list.AddRange(tempItems); Array.Copy(tempItems, items, 16); Array.Copy(tempItems, 0, items, 16, 16); } CollectionAssert.Equal(items, list); } } [Fact] public void AddAndClear() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); list.AddRange(GenerateItems(16)); list.Clear(); object[] items = GenerateItems(8); list.AddRange(items); CollectionAssert.Equal(items, list); } } [Fact] public void AddAndRemove() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { var items = new object[23]; IList list = GetList(null); object[] tempItems = GenerateItems(32); for (var i = 0; i < 16; i++) { list.Add(tempItems[i]); } for (var i = 0; i < 16; i++) { if ((i & 1) == 0) { list.RemoveAt(i/2); } else { items[i/2] = tempItems[i]; } } list.RemoveAt(list.Count - 1); for (var i = 0; i < 16; i++) { list.Add(tempItems[16 + i]); } Array.Copy(tempItems, 16, items, 7, 16); CollectionAssert.Equal(items, list); } } [Fact] public void AddAndRemoveAll() { IList list = GetList(null); object[] tempItems = GenerateItems(16); list.AddRange(tempItems); int count = tempItems.Length; foreach (object item in tempItems) { list.Remove(item); count--; Assert.Equal(count, list.Count); } Assert.Equal(0, list.Count); object[] items = GenerateItems(16); list.AddRange(items); CollectionAssert.Equal(items, list); } [Fact] public void AddWithInvalidTypes() { if (IsGenericCompatibility) { object[] items = GenerateItems(32); IList list = GetList(items); foreach (object invalid in GetInvalidValues()) { Type[] expectedExceptions; if (ExpectedIsFixedSize) { expectedExceptions = new[] { typeof (ArgumentException), typeof (NotSupportedException) }; } else { expectedExceptions = new[] { typeof (ArgumentException) }; } object invalid1 = invalid; AssertThrows( expectedExceptions, () => list.Add(invalid1)); CollectionAssert.Equal(items, list); } } } [Fact] public void ClearWithReadOnlyOrFixedSizeThrows() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { object[] items = GenerateItems(32); IList list = GetList(items); Assert.Throws<NotSupportedException>(() => list.Clear()); CollectionAssert.Equal(items, list); } } [Fact] public void ClearOnEmptyList() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); list.Clear(); // no exception should have been generated. Assert.Equal(0, list.Count); } } [Fact] public void RepeatClearOnEmptyList() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); list.Clear(); list.Clear(); list.Clear(); // no exception should have been generated. Assert.Equal(0, list.Count); } } [Fact] public void AddRemoveClearAdd() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); object[] items = GenerateItems(16); list.AddRange(items); for (var i = 0; i < items.Length; i++) { if ((i & 1) == 0) { list.RemoveAt(i/2); } } list.RemoveAt(list.Count - 1); list.Clear(); // no exception should have been generated Assert.Equal(0, list.Count); } } [Fact] public void AddRemoveAllClearAdd() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); object[] items = GenerateItems(16); list.AddRange(items); foreach (object item in items) { list.Remove(item); } list.Clear(); // no exception should have been generated Assert.Equal(0, list.Count); } } [Fact] public void ClearOneItem() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); object[] items = GenerateItems(1); list.AddRange(items); list.Clear(); // no exception should have been generated Assert.Equal(0, list.Count); } } [Fact] public void EmptyCollectionContainsNonNull() { IList list = GetList(null); Assert.False(list.Contains(GenerateItem())); } [Fact] public void EmptyCollectionContainsNull() { IList list = GetList(null); if (ItemsMustBeNonNull && SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.Contains(null)); } else { Assert.False(list.Contains(null)); } } [Fact] public void EmptyCollectionAddThenContainsSame() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); object[] items = GenerateItems(1); list.AddRange(items); Assert.True(list.Contains(items[0])); } } [Fact] public void EmptyCollectionAddThenContainsDifferent() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); object[] items = GenerateItems(1); list.AddRange(items); Assert.False(list.Contains(GenerateItem())); } } [Fact] public void EmptyCollectionAddThenContainsNull() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); object[] items = GenerateItems(1); list.AddRange(items); if (ItemsMustBeNonNull && SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.Contains(null)); } else { Assert.False(list.Contains(null)); } } } [Fact] public void AddAndContainsNullValue() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly && !ItemsMustBeNonNull) { IList list = GetList(null); list.Add(null); Assert.True(list.Contains(null)); } } [Fact] public void ContainsValueThatExistsTwice() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly && !ItemsMustBeNonNull && !ItemsMustBeUnique) { IList list = GetList(null); object[] items = GenerateItems(16); list.Add(items); list.Add(items); for (var i = 0; i < items.Length; i++) { Assert.True(list.Contains(items[i])); } Assert.False(list.Contains(GenerateItem())); } } [Theory] [InlineData(32, 0)] [InlineData(32, 16)] [InlineData(32, 31)] public void NullInMiddleContains( int collectionSize, int nullIndex) { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly && !ItemsMustBeNonNull) { IList list = GetList(null); object[] items = GenerateItems(collectionSize); list.AddRange(items); list.Insert(nullIndex, null); foreach (object item in items) { Assert.True(list.Contains(item)); } Assert.True(list.Contains(null)); Assert.False(list.Contains(GenerateItem())); } } [Fact] public void ContainsUniqueItems() { object[] items = GenerateItems(32); IList list = GetList(items); for (var i = 0; i < items.Length; i++) { Assert.True(list.Contains(items[i])); } Assert.False(list.Contains(GenerateItem())); } [Fact] public void ContainsInvalidValue() { if (IsGenericCompatibility) { foreach (object invalid in GetInvalidValues()) { object invalid1 = invalid; IList list = GetList(null); if (SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.Contains(invalid1)); } else { Assert.False(list.Contains(invalid1)); } } } } [Fact] public void EmptyCollectionIndexOf() { IList list = GetList(null); Assert.Equal(-1, list.IndexOf(GenerateItem())); } [Fact] public void EmptyCollectionIndexOfNull() { IList list = GetList(null); if (ItemsMustBeNonNull && SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.IndexOf(null)); } else { Assert.Equal(-1, list.IndexOf(null)); } } [Fact] public void AddIndexOfSameElement() { if (!ExpectedIsReadOnly && !ExpectedIsFixedSize) { IList list = GetList(null); object[] items = GenerateItems(1); list.AddRange(items); Assert.Equal(0, list.IndexOf(items[0])); } } [Fact] public void AddIndexOfDifferentElement() { if (!ExpectedIsReadOnly && !ExpectedIsFixedSize) { IList list = GetList(null); object[] items = GenerateItems(1); list.AddRange(items); Assert.Equal(-1, list.IndexOf(GenerateItem())); } } [Fact] public void AddIndexOfNull() { if (!ExpectedIsReadOnly && !ExpectedIsFixedSize) { IList list = GetList(null); object[] items = GenerateItems(1); list.AddRange(items); if (ItemsMustBeNonNull && SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.IndexOf(null)); } else { Assert.Equal(-1, list.IndexOf(null)); } } } [Fact] public void AddNullIndexOfNull() { if (!ExpectedIsReadOnly && !ExpectedIsFixedSize && !ItemsMustBeNonNull) { IList list = GetList(null); list.Add(null); Assert.Equal(0, list.IndexOf(null)); } } [Fact] public void IndexOfNonUnique() { if (!ExpectedIsReadOnly && !ExpectedIsFixedSize && !ItemsMustBeUnique) { IList list = GetList(null); object[] items = GenerateItems(16); list.AddRange(items); list.AddRange(items); for (var i = 0; i < items.Length; i++) { Assert.Equal(i, list.IndexOf(items[i])); } Assert.Equal(-1, list.IndexOf(GenerateItem())); } } [Theory] [InlineData(32, 0)] [InlineData(32, 16)] [InlineData(32, 31)] public void IndexOfNull(int collectionSize, int nullIndex) { if (!ExpectedIsReadOnly && !ExpectedIsFixedSize && !ItemsMustBeNonNull) { IList list = GetList(null); object[] items = GenerateItems(collectionSize); list.AddRange(items); list.Insert(nullIndex, null); for (var i = 0; i < nullIndex; i++) { Assert.Equal(i, list.IndexOf(items[i])); } Assert.Equal(nullIndex, list.IndexOf(null)); for (int i = nullIndex; i < collectionSize; i++) { Assert.Equal(i + 1, list.IndexOf(items[i])); } Assert.Equal(-1, list.IndexOf(GenerateItem())); } } [Fact] public void IndexOfUniqueItems() { object[] items = GenerateItems(32); IList list = GetList(items); for (var i = 0; i < items.Length; i++) { Assert.Equal(i, list.IndexOf(items[i])); } Assert.Equal(-1, list.IndexOf(GenerateItem())); } [Fact] public void IndexOfInvalidTypes() { if (!IsGenericCompatibility) { return; } foreach (object invalid in GetInvalidValues()) { IList list = GetList(null); object invalid1 = invalid; if (SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.IndexOf(invalid1)); } else { Assert.Equal(-1, list.IndexOf(invalid1)); } } } [Theory] [InlineData(int.MinValue, 16)] [InlineData(-1, 16)] [InlineData(1, 0)] [InlineData(33, 32)] [InlineData(int.MaxValue, 32)] public void InsertInvalidIndexThrows(int index, int size) { object[] items = GenerateItems(size); IList list = GetList(items); Assert.Throws<ArgumentOutOfRangeException>( () => list.Insert(index, GenerateItem())); CollectionAssert.Equal(items, list); } [Fact] public void InsertInvalidTypes() { if (!IsGenericCompatibility) { return; } object[] items = GenerateItems(16); IList list = GetList(items); foreach (object i in GetInvalidValues()) { object invalid = i; if (invalid == null) { Assert.Throws<ArgumentNullException>( () => list.Insert(0, null)); } else { Assert.Throws<ArgumentException>( () => list.Insert(0, invalid)); } CollectionAssert.Equal(items, list); } } [Fact] public void FixedSizeOrReadonlyInsertThrows() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { return; } object[] items = GenerateItems(16); IList list = GetList(items); Assert.Throws<NotSupportedException>( () => list.Insert(0, GenerateItem())); CollectionAssert.Equal(items, list); } [Fact] public void InsertItems() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(32); IList list = GetList(null); for (var i = 0; i < items.Length; i++) { list.Insert(i, items[i]); } CollectionAssert.Equal(items, list); } [Theory] [InlineData(0, 32)] [InlineData(16, 32)] [InlineData(32, 32)] public void InsertNull(int index, int size) { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(size); IList list = GetList(items); if (ItemsMustBeNonNull) { Assert.Throws<ArgumentNullException>( () => list.Insert(index, null)); } else { List<object> l = items.ToList(); l.Insert(index, null); items = l.ToArray(); list.Insert(index, null); } CollectionAssert.Equal(items, list); } [Fact] public void InsertExistingValue() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(16); IList list = GetList(items); if (ItemsMustBeUnique) { Assert.Throws<ArgumentException>( () => list.Insert(0, items[0])); } else { foreach (object item in items) { list.Insert(list.Count, item); } items = items.Push(items); } CollectionAssert.Equal(items, list); } [Fact] public void InsertClearInsert() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(16); IList list = GetList(null); list.InsertRange(items); list.Clear(); items = GenerateItems(16); list.InsertRange(items); CollectionAssert.Equal(items, list); } [Fact] public void InsertRemoveInsert() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(32); IList list = GetList(null); list.InsertRange(items); var tempItems = (object[]) items.Clone(); for (var i = 0; i < 16; i++) { list.RemoveAt(0); } Array.Copy(tempItems, 16, items, 0, 8); Array.Copy(tempItems, 24, items, 24, 8); tempItems = GenerateItems(16); for (var i = 0; i < 16; i++) { list.Insert(8 + i, tempItems[i]); } Array.Copy(tempItems, 0, items, 8, 16); CollectionAssert.Equal(items, list); } [Fact] public void InsertRemoveAllInsert() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(32); IList list = GetList(null); list.InsertRange(items); for (var i = 0; i < 32; i++) { list.Remove(items[i]); } items = GenerateItems(32); list.InsertRange(items); CollectionAssert.Equal(items, list); } [Fact] public void InsertAndAdd() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(48); IList list = GetList(null); list.InsertRange(0, items, 0, 16); list.AddRange(items, 16, 16); list.InsertRange(32, items, 32, 16); CollectionAssert.Equal(items, list); } [Fact] public void InsertAndRemove() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(32); var tempItems = new object[33]; IList list = GetList(items); for (var i = 0; i < items.Length; i++) { object newObject = GenerateItem(); list.Insert(i, newObject); Array.Copy(items, tempItems, i); tempItems[i] = newObject; Array.Copy(items, i, tempItems, i + 1, items.Length - i); CollectionAssert.Equal(tempItems, list); list.RemoveAt(i); } } [Fact] public void RemoveReadOnlyFixedSizeThrows() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { return; } object[] items = GenerateItems(16); IList list = GetList(items); Assert.Throws<NotSupportedException>( () => list.Remove(GenerateItem())); CollectionAssert.Equal(items, list); } [Fact] public void RemoveEmptyCollection() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(0); IList list = GetList(items); list.Remove(GenerateItem()); CollectionAssert.Equal(items, list); } [Fact] public void RemoveNullEmptyCollection() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(0); IList list = GetList(items); if (ItemsMustBeNonNull && SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.Remove(null)); } else { list.Remove(null); } CollectionAssert.Equal(items, list); } [Fact] public void AddRemoveValueEmptyCollection() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(0); IList list = GetList(items); object item = GenerateItem(); list.Add(item); list.Remove(item); CollectionAssert.Equal(items, list); } [Fact] public void AddRemoveDifferentValueEmptyCollection() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(0); IList list = GetList(items); object item = GenerateItem(); list.Add(item); items = items.Push(item); list.Remove(GenerateItem()); CollectionAssert.Equal(items, list); } [Fact] public void AddNonNullRemoveNullEmptyCollection() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(0); IList list = GetList(items); object item = GenerateItem(); list.Add(item); items = items.Push(item); if (ItemsMustBeNonNull && SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.Remove(null)); } else { list.Remove(null); } CollectionAssert.Equal(items, list); } [Fact] public void AddRemoveNullEmptyCollection() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } if (ItemsMustBeNonNull) { return; } object[] items = GenerateItems(0); IList list = GetList(items); list.Add(null); list.Remove(null); CollectionAssert.Equal(items, list); } [Fact] public void AddNullRemoveNonNullEmptyCollection() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } if (ItemsMustBeNonNull) { return; } object[] items = GenerateItems(0); IList list = GetList(items); list.Add(null); items = items.Push(null); list.Remove(GenerateItem()); CollectionAssert.Equal(items, list); } [Fact] public void RemoveItemsExistsTwice() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } if (ItemsMustBeUnique) { return; } object[] items = GenerateItems(16); var tempItems = (object[]) items.Clone(); IList list = GetList(items); list.AddRange(items); for (var i = 0; i < items.Length; i++) { int index = i + 1; items = new object[ tempItems.Length + tempItems.Length - index]; Array.Copy(tempItems, index, items, 0, 16 - index); Array.Copy(tempItems, 0, items, 16 - index, 16); list.Remove(tempItems[i]); CollectionAssert.Equal(items, list); } } [Fact] public void RemoveNonExisting() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(16); IList list = GetList(items); list.Remove(GenerateItem()); CollectionAssert.Equal(items, list); } [Fact] public void RemoveItems() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(16); IList list = GetList(items); for (var i = 0; i < items.Length; i++) { list.Remove(items[i]); CollectionAssert.Equal(items.Slice(i + 1), list); } } [Fact] public void RemoveNull() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } if (ItemsMustBeNonNull) { return; } var items = new object[15]; IList list = GetList(null); object[] tempItems = GenerateItems(16); list.AddRange(tempItems); Array.Copy(tempItems, items, 11); Array.Copy(tempItems, 12, items, 11, 4); list.Insert(8, null); list.Remove(tempItems[11]); list.Remove(null); list.Remove(GenerateItem()); CollectionAssert.Equal(items, list); } [Fact] public void RemoveInvalidValues() { if (!IsGenericCompatibility) { return; } Type[] expectedExceptions = ExpectedIsFixedSize ? new[] { typeof ( ArgumentException), typeof ( NotSupportedException) } : new[] { typeof ( ArgumentException) }; object[] items = GenerateItems(16); IList list = GetList(items); foreach (object i in GetInvalidValues()) { object invalid = i; if (ExpectedIsFixedSize || SearchingThrowsFromInvalidValue) { AssertThrows( expectedExceptions, () => list.Remove(invalid)); } else { list.Remove(invalid); } CollectionAssert.Equal(items, list); } } [Theory] [MemberData(nameof(RemoveAtInvalidData))] public void RemoveAtInvalid(int index, int size) { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(size); IList list = GetList(items); Assert.Throws<ArgumentOutOfRangeException>( () => list.RemoveAt(index)); CollectionAssert.Equal(items, list); } [Theory] [MemberData(nameof(RemoveAtInvalidData))] public void RemoveAtInvalidReadOnly(int index, int size) { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { return; } object[] items = GenerateItems(size); IList list = GetList(items); AssertThrows( new[] { typeof (ArgumentOutOfRangeException), typeof (NotSupportedException) }, () => list.RemoveAt(index)); CollectionAssert.Equal(items, list); } [Fact] public void RemoveAtFixedSizeThrows() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { object[] items = GenerateItems(16); IList list = GetList(items); Assert.Throws<NotSupportedException>( () => list.RemoveAt(0)); CollectionAssert.Equal(items, list); } } [Theory] [InlineData(32)] [InlineData(16)] public void RemoveAtDescending(int size) { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(size); IList list = GetList(items); for (var i = 0; i < size; i++) { list.RemoveAt(size - i - 1); items = items.Slice(0, items.Length - 1); CollectionAssert.Equal(items, list); } } [Theory] [InlineData(32)] [InlineData(16)] public void RemoveAt(int size) { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(size); IList list = GetList(items); for (var i = 0; i < size; i++) { list.RemoveAt(0); items = items.Slice(1); CollectionAssert.Equal(items, list); } } [Theory] [InlineData(32)] [InlineData(16)] public void RemoveAtEachIndex(int size) { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(size); IList list = GetList(items); for (var i = 0; i < size; i++) { list.RemoveAt(i); CollectionAssert.Equal(items.RemoveAt(i), list); list.Insert(i, items[i]); } } /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected abstract IEnumerable GetInvalidValues(); private IList GetList(object[] items) { ICollection obj = GetCollection(items); Assert.IsAssignableFrom<IList>(obj); return (IList) obj; } } public abstract class IListTest<TList, T> : IListTest<T> where TList : IList { private readonly bool _isGenericCompatibility; private readonly bool _isResetNotSupported; private readonly bool _itemsMustBeUnique; protected IListTest( bool isSynchronized, bool isReadOnly, bool isFixedSize, bool isResetNotSupported, bool isGenericCompatibility, bool itemsMustBeUnique) : base(isSynchronized, isReadOnly, isFixedSize) { _isResetNotSupported = isResetNotSupported; _isGenericCompatibility = isGenericCompatibility; _itemsMustBeUnique = itemsMustBeUnique; ValidArrayTypes = new[] {typeof (object), typeof (T)}; SearchingThrowsFromInvalidValue = false; } protected override sealed bool IsResetNotSupported { get { return _isResetNotSupported; } } protected override sealed bool IsGenericCompatibility { get { return _isGenericCompatibility; } } protected override sealed bool ItemsMustBeUnique { get { return _itemsMustBeUnique; } } protected override sealed bool ItemsMustBeNonNull { get { return default(T) != null; } } protected override sealed object GenerateItem() { return CreateItem(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected abstract T CreateItem(); /// <summary> /// When overridden in a derived class, Gets an instance of the list under test containing the given items. /// </summary> /// <param name="items">The items to initialize the list with.</param> /// <returns>An instance of the list under test containing the given items.</returns> protected abstract TList CreateList(IEnumerable<T> items); /// <summary> /// When overridden in a derived class, Gets an instance of the enumerable under test containing the given items. /// </summary> /// <param name="items">The items to initialize the enumerable with.</param> /// <returns>An instance of the enumerable under test containing the given items.</returns> protected override sealed IEnumerable GetEnumerable( object[] items) { return CreateList( items == null ? Enumerable.Empty<T>() : items.Cast<T>()); } /// <summary> /// When overridden in a derived class, invalidates any enumerators for the given list. /// </summary> /// <param name="list">The list to invalidate enumerators for.</param> /// <returns>The new contents of the list.</returns> protected abstract IEnumerable<T> InvalidateEnumerator( TList list); /// <summary> /// When overridden in a derived class, invalidates any enumerators for the given IEnumerable. /// </summary> /// <param name="enumerable">The <see cref="IEnumerable" /> to invalidate enumerators for.</param> /// <returns>The new set of items in the <see cref="IEnumerable" /></returns> protected override sealed object[] InvalidateEnumerator( IEnumerable enumerable) { return InvalidateEnumerator((TList) enumerable) .OfType<object>() .ToArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Xunit; namespace Tests.Collections { public static class CollectionAssert { public static void Equal( IEnumerable expected, IEnumerable actual) { Assert.Equal( expected.OfType<object>(), actual.OfType<object>()); } public static void Equal(IList expected, IList actual) { Equal((IEnumerable) expected, actual); // explicitly test Count and the indexer Assert.Equal(expected.Count, actual.Count); for (var i = 0; i < expected.Count; i++) { var expectedArray = expected as Array; var actualArray = expected as Array; int expectedLowerBound = expectedArray == null ? 0 : expectedArray .GetLowerBound(0); int actualLowerBound = actualArray == null ? 0 : actualArray.GetLowerBound( 0); Assert.Equal( expected[i + expectedLowerBound], actual[i + actualLowerBound]); } } } public static class IListExtensions { public static void AddRange(this IList list, IEnumerable items) { foreach (object item in items) { list.Add(item); } } public static void InsertRange(this IList list, object[] items) { list.InsertRange(0, items, 0, items.Length); } public static void InsertRange( this IList list, int listStartIndex, object[] items, int startIndex, int count) { int numToInsert = items.Length - startIndex; if (count < numToInsert) { numToInsert = count; } for (var i = 0; i < numToInsert; i++) { list.Insert(listStartIndex + i, items[startIndex + i]); } } public static void AddRange( this IList list, object[] items, int startIndex, int count) { int numToAdd = items.Length - startIndex; if (count < numToAdd) { numToAdd = count; } for (var i = 0; i < numToAdd; i++) { list.Add(items[startIndex + i]); } } } public abstract class IListTest<T> : ICollectionTest<T> { private readonly bool _expectedIsFixedSize; private readonly bool _expectedIsReadOnly; private bool _searchingThrowsFromInvalidValue; protected IListTest( bool isSynchronized, bool isReadOnly, bool isFixedSize) : base(isSynchronized) { _expectedIsReadOnly = isReadOnly; _expectedIsFixedSize = isFixedSize; SearchingThrowsFromInvalidValue = false; } protected bool ExpectedIsReadOnly { get { return _expectedIsReadOnly; } } protected bool ExpectedIsFixedSize { get { return _expectedIsFixedSize; } } protected bool SearchingThrowsFromInvalidValue { get { return _searchingThrowsFromInvalidValue; } set { _searchingThrowsFromInvalidValue = value; } } public static object[][] RemoveAtInvalidData { get { return new[] { new object[] {int.MinValue, 16}, new object[] {-1, 16}, new object[] {0, 0}, new object[] {1, 1}, new object[] {16, 16} }; } } [Fact] public void IsFixedSize() { Assert.Equal(ExpectedIsFixedSize, GetList(null).IsFixedSize); } [Fact] public void IsReadOnly() { Assert.Equal(ExpectedIsReadOnly, GetList(null).IsReadOnly); } [Theory] [InlineData(int.MinValue)] [InlineData(-1)] [InlineData(0)] public void GetItemArgumentOutOfRange(int index) { IList list = GetList(null); Assert.Throws<ArgumentOutOfRangeException>( () => list[index]); CollectionAssert.Equal(Array.Empty<object>(), list); } [Fact] public void GetItemArgumentOutOfRangeFilledCollection() { object[] items = GenerateItems(32); IList list = GetList(items); Assert.Throws<ArgumentOutOfRangeException>( () => list[list.Count]); CollectionAssert.Equal(items, list); } [Fact] public void GetItemEmpty() { var items = new object[0]; IList list = GetList(items); if (ExpectedIsFixedSize || ExpectedIsReadOnly) { CollectionAssert.Equal(items, list); } else { list.Clear(); items = GenerateItems(1); list.AddRange(items); CollectionAssert.Equal(items, list); list.Clear(); items = GenerateItems(1024); list.AddRange(items); CollectionAssert.Equal(items, list); } } [Fact] public void SetItemNotSupported() { if (ExpectedIsReadOnly) { object[] items = GenerateItems(10); IList list = GetList(items); Assert.Throws<NotSupportedException>( () => list[0] = GenerateItem()); CollectionAssert.Equal(items, list); Assert.Throws<NotSupportedException>( () => list[list.Count - 1] = GenerateItem()); CollectionAssert.Equal(items, list); } } [Fact] public void SetItemArgumentException() { Type[] expectedExceptions; if (ExpectedIsReadOnly) { expectedExceptions = new[] { typeof (ArgumentOutOfRangeException), typeof (NotSupportedException) }; } else { expectedExceptions = new[] { typeof (ArgumentOutOfRangeException) }; } { object[] items = GenerateItems(10); IList list = GetList(items); AssertThrows( expectedExceptions, () => list[int.MinValue] = GenerateItem()); CollectionAssert.Equal(items, list); AssertThrows( expectedExceptions, () => list[-1] = GenerateItem()); CollectionAssert.Equal(items, list); } { object[] items = GenerateItems(0); IList list = GetList(items); AssertThrows( expectedExceptions, () => list[0] = GenerateItem()); CollectionAssert.Equal(items, list); if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { items = GenerateItems(32); list.AddRange(items); AssertThrows( expectedExceptions, () => list[list.Count] = GenerateItem()); CollectionAssert.Equal(items, list); } } } [Fact] public void SetItemInvalidValue() { object[] items = GenerateItems(32); IList list = GetList(items); if (IsGenericCompatibility) { foreach (object invalid in GetInvalidValues()) { Type[] expectedExceptions; if (invalid == null) { if (ExpectedIsReadOnly) { expectedExceptions = new[] { typeof (ArgumentNullException), typeof (NotSupportedException) }; } else { expectedExceptions = new[] { typeof (ArgumentNullException) }; } } else if (ExpectedIsReadOnly) { expectedExceptions = new[] { typeof (ArgumentException), typeof (NotSupportedException) }; } else { expectedExceptions = new[] { typeof (ArgumentException) }; } object invalid1 = invalid; AssertThrows( expectedExceptions, () => list[0] = invalid1); CollectionAssert.Equal(items, list); } } } [Fact] public void SetItemNonNull() { if (!ExpectedIsReadOnly) { if (ItemsMustBeNonNull) { object[] items = GenerateItems(32); IList list = GetList(items); Assert.Throws<ArgumentNullException>( () => list[0] = null); CollectionAssert.Equal(items, list); } } } [Fact] public void SetItemNullable() { if (!ExpectedIsReadOnly) { if (!ItemsMustBeNonNull) { object[] items = GenerateItems(32); IList list = GetList(items); list[0] = null; items[0] = null; CollectionAssert.Equal(items, list); items = GenerateItems(32); list = GetList(items); list[list.Count - 1] = null; items[items.Length - 1] = null; CollectionAssert.Equal(items, list); } } } [Fact] public void SetItemUnique() { if (!ExpectedIsReadOnly) { if (ItemsMustBeUnique) { object[] items = GenerateItems(32); IList list = GetList(items); Assert.Throws<ArgumentException>( () => list[0] = items[1]); CollectionAssert.Equal(items, list); } } } [Fact] public void SetItemNotUnique() { if (!ExpectedIsReadOnly) { if (!ItemsMustBeUnique) { object[] items = GenerateItems(32); IList list = GetList(items); for (var i = 0; i < items.Length; i++) { list[i] = items[items.Length - i - 1]; } Array.Reverse(items); CollectionAssert.Equal(items, list); } } } [Fact] public void SetItem() { if (!ExpectedIsReadOnly) { object[] items = GenerateItems(32); var origItems = (object[]) items.Clone(); IList list = GetList(items); // verify setting every item // reverse list, setting items to new elements to maintain uniqueness. for (var i = 0; i < items.Length; i++) { if (i < items.Length/2) { list[items.Length - i - 1] = GenerateItem(); } list[i] = items[items.Length - i - 1]; } Array.Reverse(items); CollectionAssert.Equal(items, list); // verify setting items back to the original items = origItems; if (ItemsMustBeUnique) { for (var i = 0; i < items.Length; i++) { list[i] = GenerateItem(); } } for (var i = 0; i < items.Length; i++) { list[i] = items[i]; } CollectionAssert.Equal(items, list); } } [Fact] public void AddFixedSizeOrReadonlyThrows() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { object[] items = GenerateItems(10); IList list = GetList(items); Assert.Throws<NotSupportedException>( () => list.Add(GenerateItem())); CollectionAssert.Equal(items, list); } } [Fact] public void AddWithNullValueInMiddle() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { const int size = 32; object[] items; IList list = GetList(null); object[] tempItems = GenerateItems(size); for (var i = 0; i < tempItems.Length/2; i++) { list.Add(tempItems[i]); } if (ItemsMustBeNonNull) { items = tempItems; Assert.Throws<ArgumentNullException>( () => list.Add(null)); } else { const int sizeWithNull = size + 1; items = new object[sizeWithNull]; list.Add(null); items[sizeWithNull/2] = null; Array.Copy(tempItems, items, sizeWithNull/2); Array.Copy( tempItems, sizeWithNull/2, items, sizeWithNull/2 + 1, sizeWithNull/2); } for (var i = 0; i < size/2; i++) { list.Add(tempItems[size/2 + i]); } CollectionAssert.Equal(items, list); } } [Fact] public void AddWithNullValueAtBeginning() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); object[] items; if (ItemsMustBeNonNull) { Assert.Throws<ArgumentNullException>( () => list.Add(null)); items = GenerateItems(16); list.AddRange(items); } else { const int size = 17; items = new object[size]; list.Add(null); items[0] = null; object[] tempItems = GenerateItems(size - 1); list.AddRange(tempItems); Array.Copy(tempItems, 0, items, 1, size - 1); } CollectionAssert.Equal(items, list); } } [Fact] public void AddWithNullValueAtEnd() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { object[] items = GenerateItems(16); IList list = GetList(items); if (ItemsMustBeNonNull) { Assert.Throws<ArgumentNullException>( () => list.Add(null)); } else { items[items.Length - 1] = null; list.RemoveAt(list.Count - 1); list.Add(null); } CollectionAssert.Equal(items, list); } } [Fact] public void AddDuplicateValue() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { object[] items; IList list = GetList(null); if (ItemsMustBeUnique) { items = GenerateItems(16); list.AddRange(items); Assert.Throws<ArgumentException>( () => list.Add(items[0])); } else { items = new object[32]; object[] tempItems = GenerateItems(16); list.AddRange(tempItems); list.AddRange(tempItems); Array.Copy(tempItems, items, 16); Array.Copy(tempItems, 0, items, 16, 16); } CollectionAssert.Equal(items, list); } } [Fact] public void AddAndClear() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); list.AddRange(GenerateItems(16)); list.Clear(); object[] items = GenerateItems(8); list.AddRange(items); CollectionAssert.Equal(items, list); } } [Fact] public void AddAndRemove() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { var items = new object[23]; IList list = GetList(null); object[] tempItems = GenerateItems(32); for (var i = 0; i < 16; i++) { list.Add(tempItems[i]); } for (var i = 0; i < 16; i++) { if ((i & 1) == 0) { list.RemoveAt(i/2); } else { items[i/2] = tempItems[i]; } } list.RemoveAt(list.Count - 1); for (var i = 0; i < 16; i++) { list.Add(tempItems[16 + i]); } Array.Copy(tempItems, 16, items, 7, 16); CollectionAssert.Equal(items, list); } } [Fact] public void AddAndRemoveAll() { IList list = GetList(null); object[] tempItems = GenerateItems(16); list.AddRange(tempItems); int count = tempItems.Length; foreach (object item in tempItems) { list.Remove(item); count--; Assert.Equal(count, list.Count); } Assert.Equal(0, list.Count); object[] items = GenerateItems(16); list.AddRange(items); CollectionAssert.Equal(items, list); } [Fact] public void AddWithInvalidTypes() { if (IsGenericCompatibility) { object[] items = GenerateItems(32); IList list = GetList(items); foreach (object invalid in GetInvalidValues()) { Type[] expectedExceptions; if (ExpectedIsFixedSize) { expectedExceptions = new[] { typeof (ArgumentException), typeof (NotSupportedException) }; } else { expectedExceptions = new[] { typeof (ArgumentException) }; } object invalid1 = invalid; AssertThrows( expectedExceptions, () => list.Add(invalid1)); CollectionAssert.Equal(items, list); } } } [Fact] public void ClearWithReadOnlyOrFixedSizeThrows() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { object[] items = GenerateItems(32); IList list = GetList(items); Assert.Throws<NotSupportedException>(() => list.Clear()); CollectionAssert.Equal(items, list); } } [Fact] public void ClearOnEmptyList() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); list.Clear(); // no exception should have been generated. Assert.Equal(0, list.Count); } } [Fact] public void RepeatClearOnEmptyList() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); list.Clear(); list.Clear(); list.Clear(); // no exception should have been generated. Assert.Equal(0, list.Count); } } [Fact] public void AddRemoveClearAdd() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); object[] items = GenerateItems(16); list.AddRange(items); for (var i = 0; i < items.Length; i++) { if ((i & 1) == 0) { list.RemoveAt(i/2); } } list.RemoveAt(list.Count - 1); list.Clear(); // no exception should have been generated Assert.Equal(0, list.Count); } } [Fact] public void AddRemoveAllClearAdd() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); object[] items = GenerateItems(16); list.AddRange(items); foreach (object item in items) { list.Remove(item); } list.Clear(); // no exception should have been generated Assert.Equal(0, list.Count); } } [Fact] public void ClearOneItem() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); object[] items = GenerateItems(1); list.AddRange(items); list.Clear(); // no exception should have been generated Assert.Equal(0, list.Count); } } [Fact] public void EmptyCollectionContainsNonNull() { IList list = GetList(null); Assert.False(list.Contains(GenerateItem())); } [Fact] public void EmptyCollectionContainsNull() { IList list = GetList(null); if (ItemsMustBeNonNull && SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.Contains(null)); } else { Assert.False(list.Contains(null)); } } [Fact] public void EmptyCollectionAddThenContainsSame() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); object[] items = GenerateItems(1); list.AddRange(items); Assert.True(list.Contains(items[0])); } } [Fact] public void EmptyCollectionAddThenContainsDifferent() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); object[] items = GenerateItems(1); list.AddRange(items); Assert.False(list.Contains(GenerateItem())); } } [Fact] public void EmptyCollectionAddThenContainsNull() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { IList list = GetList(null); object[] items = GenerateItems(1); list.AddRange(items); if (ItemsMustBeNonNull && SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.Contains(null)); } else { Assert.False(list.Contains(null)); } } } [Fact] public void AddAndContainsNullValue() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly && !ItemsMustBeNonNull) { IList list = GetList(null); list.Add(null); Assert.True(list.Contains(null)); } } [Fact] public void ContainsValueThatExistsTwice() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly && !ItemsMustBeNonNull && !ItemsMustBeUnique) { IList list = GetList(null); object[] items = GenerateItems(16); list.Add(items); list.Add(items); for (var i = 0; i < items.Length; i++) { Assert.True(list.Contains(items[i])); } Assert.False(list.Contains(GenerateItem())); } } [Theory] [InlineData(32, 0)] [InlineData(32, 16)] [InlineData(32, 31)] public void NullInMiddleContains( int collectionSize, int nullIndex) { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly && !ItemsMustBeNonNull) { IList list = GetList(null); object[] items = GenerateItems(collectionSize); list.AddRange(items); list.Insert(nullIndex, null); foreach (object item in items) { Assert.True(list.Contains(item)); } Assert.True(list.Contains(null)); Assert.False(list.Contains(GenerateItem())); } } [Fact] public void ContainsUniqueItems() { object[] items = GenerateItems(32); IList list = GetList(items); for (var i = 0; i < items.Length; i++) { Assert.True(list.Contains(items[i])); } Assert.False(list.Contains(GenerateItem())); } [Fact] public void ContainsInvalidValue() { if (IsGenericCompatibility) { foreach (object invalid in GetInvalidValues()) { object invalid1 = invalid; IList list = GetList(null); if (SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.Contains(invalid1)); } else { Assert.False(list.Contains(invalid1)); } } } } [Fact] public void EmptyCollectionIndexOf() { IList list = GetList(null); Assert.Equal(-1, list.IndexOf(GenerateItem())); } [Fact] public void EmptyCollectionIndexOfNull() { IList list = GetList(null); if (ItemsMustBeNonNull && SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.IndexOf(null)); } else { Assert.Equal(-1, list.IndexOf(null)); } } [Fact] public void AddIndexOfSameElement() { if (!ExpectedIsReadOnly && !ExpectedIsFixedSize) { IList list = GetList(null); object[] items = GenerateItems(1); list.AddRange(items); Assert.Equal(0, list.IndexOf(items[0])); } } [Fact] public void AddIndexOfDifferentElement() { if (!ExpectedIsReadOnly && !ExpectedIsFixedSize) { IList list = GetList(null); object[] items = GenerateItems(1); list.AddRange(items); Assert.Equal(-1, list.IndexOf(GenerateItem())); } } [Fact] public void AddIndexOfNull() { if (!ExpectedIsReadOnly && !ExpectedIsFixedSize) { IList list = GetList(null); object[] items = GenerateItems(1); list.AddRange(items); if (ItemsMustBeNonNull && SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.IndexOf(null)); } else { Assert.Equal(-1, list.IndexOf(null)); } } } [Fact] public void AddNullIndexOfNull() { if (!ExpectedIsReadOnly && !ExpectedIsFixedSize && !ItemsMustBeNonNull) { IList list = GetList(null); list.Add(null); Assert.Equal(0, list.IndexOf(null)); } } [Fact] public void IndexOfNonUnique() { if (!ExpectedIsReadOnly && !ExpectedIsFixedSize && !ItemsMustBeUnique) { IList list = GetList(null); object[] items = GenerateItems(16); list.AddRange(items); list.AddRange(items); for (var i = 0; i < items.Length; i++) { Assert.Equal(i, list.IndexOf(items[i])); } Assert.Equal(-1, list.IndexOf(GenerateItem())); } } [Theory] [InlineData(32, 0)] [InlineData(32, 16)] [InlineData(32, 31)] public void IndexOfNull(int collectionSize, int nullIndex) { if (!ExpectedIsReadOnly && !ExpectedIsFixedSize && !ItemsMustBeNonNull) { IList list = GetList(null); object[] items = GenerateItems(collectionSize); list.AddRange(items); list.Insert(nullIndex, null); for (var i = 0; i < nullIndex; i++) { Assert.Equal(i, list.IndexOf(items[i])); } Assert.Equal(nullIndex, list.IndexOf(null)); for (int i = nullIndex; i < collectionSize; i++) { Assert.Equal(i + 1, list.IndexOf(items[i])); } Assert.Equal(-1, list.IndexOf(GenerateItem())); } } [Fact] public void IndexOfUniqueItems() { object[] items = GenerateItems(32); IList list = GetList(items); for (var i = 0; i < items.Length; i++) { Assert.Equal(i, list.IndexOf(items[i])); } Assert.Equal(-1, list.IndexOf(GenerateItem())); } [Fact] public void IndexOfInvalidTypes() { if (!IsGenericCompatibility) { return; } foreach (object invalid in GetInvalidValues()) { IList list = GetList(null); object invalid1 = invalid; if (SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.IndexOf(invalid1)); } else { Assert.Equal(-1, list.IndexOf(invalid1)); } } } [Theory] [InlineData(int.MinValue, 16)] [InlineData(-1, 16)] [InlineData(1, 0)] [InlineData(33, 32)] [InlineData(int.MaxValue, 32)] public void InsertInvalidIndexThrows(int index, int size) { object[] items = GenerateItems(size); IList list = GetList(items); Assert.Throws<ArgumentOutOfRangeException>( () => list.Insert(index, GenerateItem())); CollectionAssert.Equal(items, list); } [Fact] public void InsertInvalidTypes() { if (!IsGenericCompatibility) { return; } object[] items = GenerateItems(16); IList list = GetList(items); foreach (object i in GetInvalidValues()) { object invalid = i; if (invalid == null) { Assert.Throws<ArgumentNullException>( () => list.Insert(0, null)); } else { Assert.Throws<ArgumentException>( () => list.Insert(0, invalid)); } CollectionAssert.Equal(items, list); } } [Fact] public void FixedSizeOrReadonlyInsertThrows() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { return; } object[] items = GenerateItems(16); IList list = GetList(items); Assert.Throws<NotSupportedException>( () => list.Insert(0, GenerateItem())); CollectionAssert.Equal(items, list); } [Fact] public void InsertItems() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(32); IList list = GetList(null); for (var i = 0; i < items.Length; i++) { list.Insert(i, items[i]); } CollectionAssert.Equal(items, list); } [Theory] [InlineData(0, 32)] [InlineData(16, 32)] [InlineData(32, 32)] public void InsertNull(int index, int size) { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(size); IList list = GetList(items); if (ItemsMustBeNonNull) { Assert.Throws<ArgumentNullException>( () => list.Insert(index, null)); } else { List<object> l = items.ToList(); l.Insert(index, null); items = l.ToArray(); list.Insert(index, null); } CollectionAssert.Equal(items, list); } [Fact] public void InsertExistingValue() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(16); IList list = GetList(items); if (ItemsMustBeUnique) { Assert.Throws<ArgumentException>( () => list.Insert(0, items[0])); } else { foreach (object item in items) { list.Insert(list.Count, item); } items = items.Push(items); } CollectionAssert.Equal(items, list); } [Fact] public void InsertClearInsert() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(16); IList list = GetList(null); list.InsertRange(items); list.Clear(); items = GenerateItems(16); list.InsertRange(items); CollectionAssert.Equal(items, list); } [Fact] public void InsertRemoveInsert() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(32); IList list = GetList(null); list.InsertRange(items); var tempItems = (object[]) items.Clone(); for (var i = 0; i < 16; i++) { list.RemoveAt(0); } Array.Copy(tempItems, 16, items, 0, 8); Array.Copy(tempItems, 24, items, 24, 8); tempItems = GenerateItems(16); for (var i = 0; i < 16; i++) { list.Insert(8 + i, tempItems[i]); } Array.Copy(tempItems, 0, items, 8, 16); CollectionAssert.Equal(items, list); } [Fact] public void InsertRemoveAllInsert() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(32); IList list = GetList(null); list.InsertRange(items); for (var i = 0; i < 32; i++) { list.Remove(items[i]); } items = GenerateItems(32); list.InsertRange(items); CollectionAssert.Equal(items, list); } [Fact] public void InsertAndAdd() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(48); IList list = GetList(null); list.InsertRange(0, items, 0, 16); list.AddRange(items, 16, 16); list.InsertRange(32, items, 32, 16); CollectionAssert.Equal(items, list); } [Fact] public void InsertAndRemove() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(32); var tempItems = new object[33]; IList list = GetList(items); for (var i = 0; i < items.Length; i++) { object newObject = GenerateItem(); list.Insert(i, newObject); Array.Copy(items, tempItems, i); tempItems[i] = newObject; Array.Copy(items, i, tempItems, i + 1, items.Length - i); CollectionAssert.Equal(tempItems, list); list.RemoveAt(i); } } [Fact] public void RemoveReadOnlyFixedSizeThrows() { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { return; } object[] items = GenerateItems(16); IList list = GetList(items); Assert.Throws<NotSupportedException>( () => list.Remove(GenerateItem())); CollectionAssert.Equal(items, list); } [Fact] public void RemoveEmptyCollection() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(0); IList list = GetList(items); list.Remove(GenerateItem()); CollectionAssert.Equal(items, list); } [Fact] public void RemoveNullEmptyCollection() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(0); IList list = GetList(items); if (ItemsMustBeNonNull && SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.Remove(null)); } else { list.Remove(null); } CollectionAssert.Equal(items, list); } [Fact] public void AddRemoveValueEmptyCollection() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(0); IList list = GetList(items); object item = GenerateItem(); list.Add(item); list.Remove(item); CollectionAssert.Equal(items, list); } [Fact] public void AddRemoveDifferentValueEmptyCollection() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(0); IList list = GetList(items); object item = GenerateItem(); list.Add(item); items = items.Push(item); list.Remove(GenerateItem()); CollectionAssert.Equal(items, list); } [Fact] public void AddNonNullRemoveNullEmptyCollection() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(0); IList list = GetList(items); object item = GenerateItem(); list.Add(item); items = items.Push(item); if (ItemsMustBeNonNull && SearchingThrowsFromInvalidValue) { Assert.Throws<ArgumentException>( () => list.Remove(null)); } else { list.Remove(null); } CollectionAssert.Equal(items, list); } [Fact] public void AddRemoveNullEmptyCollection() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } if (ItemsMustBeNonNull) { return; } object[] items = GenerateItems(0); IList list = GetList(items); list.Add(null); list.Remove(null); CollectionAssert.Equal(items, list); } [Fact] public void AddNullRemoveNonNullEmptyCollection() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } if (ItemsMustBeNonNull) { return; } object[] items = GenerateItems(0); IList list = GetList(items); list.Add(null); items = items.Push(null); list.Remove(GenerateItem()); CollectionAssert.Equal(items, list); } [Fact] public void RemoveItemsExistsTwice() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } if (ItemsMustBeUnique) { return; } object[] items = GenerateItems(16); var tempItems = (object[]) items.Clone(); IList list = GetList(items); list.AddRange(items); for (var i = 0; i < items.Length; i++) { int index = i + 1; items = new object[ tempItems.Length + tempItems.Length - index]; Array.Copy(tempItems, index, items, 0, 16 - index); Array.Copy(tempItems, 0, items, 16 - index, 16); list.Remove(tempItems[i]); CollectionAssert.Equal(items, list); } } [Fact] public void RemoveNonExisting() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(16); IList list = GetList(items); list.Remove(GenerateItem()); CollectionAssert.Equal(items, list); } [Fact] public void RemoveItems() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(16); IList list = GetList(items); for (var i = 0; i < items.Length; i++) { list.Remove(items[i]); CollectionAssert.Equal(items.Slice(i + 1), list); } } [Fact] public void RemoveNull() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } if (ItemsMustBeNonNull) { return; } var items = new object[15]; IList list = GetList(null); object[] tempItems = GenerateItems(16); list.AddRange(tempItems); Array.Copy(tempItems, items, 11); Array.Copy(tempItems, 12, items, 11, 4); list.Insert(8, null); list.Remove(tempItems[11]); list.Remove(null); list.Remove(GenerateItem()); CollectionAssert.Equal(items, list); } [Fact] public void RemoveInvalidValues() { if (!IsGenericCompatibility) { return; } Type[] expectedExceptions = ExpectedIsFixedSize ? new[] { typeof ( ArgumentException), typeof ( NotSupportedException) } : new[] { typeof ( ArgumentException) }; object[] items = GenerateItems(16); IList list = GetList(items); foreach (object i in GetInvalidValues()) { object invalid = i; if (ExpectedIsFixedSize || SearchingThrowsFromInvalidValue) { AssertThrows( expectedExceptions, () => list.Remove(invalid)); } else { list.Remove(invalid); } CollectionAssert.Equal(items, list); } } [Theory] [MemberData(nameof(RemoveAtInvalidData))] public void RemoveAtInvalid(int index, int size) { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(size); IList list = GetList(items); Assert.Throws<ArgumentOutOfRangeException>( () => list.RemoveAt(index)); CollectionAssert.Equal(items, list); } [Theory] [MemberData(nameof(RemoveAtInvalidData))] public void RemoveAtInvalidReadOnly(int index, int size) { if (!ExpectedIsFixedSize && !ExpectedIsReadOnly) { return; } object[] items = GenerateItems(size); IList list = GetList(items); AssertThrows( new[] { typeof (ArgumentOutOfRangeException), typeof (NotSupportedException) }, () => list.RemoveAt(index)); CollectionAssert.Equal(items, list); } [Fact] public void RemoveAtFixedSizeThrows() { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { object[] items = GenerateItems(16); IList list = GetList(items); Assert.Throws<NotSupportedException>( () => list.RemoveAt(0)); CollectionAssert.Equal(items, list); } } [Theory] [InlineData(32)] [InlineData(16)] public void RemoveAtDescending(int size) { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(size); IList list = GetList(items); for (var i = 0; i < size; i++) { list.RemoveAt(size - i - 1); items = items.Slice(0, items.Length - 1); CollectionAssert.Equal(items, list); } } [Theory] [InlineData(32)] [InlineData(16)] public void RemoveAt(int size) { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(size); IList list = GetList(items); for (var i = 0; i < size; i++) { list.RemoveAt(0); items = items.Slice(1); CollectionAssert.Equal(items, list); } } [Theory] [InlineData(32)] [InlineData(16)] public void RemoveAtEachIndex(int size) { if (ExpectedIsFixedSize || ExpectedIsReadOnly) { return; } object[] items = GenerateItems(size); IList list = GetList(items); for (var i = 0; i < size; i++) { list.RemoveAt(i); CollectionAssert.Equal(items.RemoveAt(i), list); list.Insert(i, items[i]); } } /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected abstract IEnumerable GetInvalidValues(); private IList GetList(object[] items) { ICollection obj = GetCollection(items); Assert.IsAssignableFrom<IList>(obj); return (IList) obj; } } public abstract class IListTest<TList, T> : IListTest<T> where TList : IList { private readonly bool _isGenericCompatibility; private readonly bool _isResetNotSupported; private readonly bool _itemsMustBeUnique; protected IListTest( bool isSynchronized, bool isReadOnly, bool isFixedSize, bool isResetNotSupported, bool isGenericCompatibility, bool itemsMustBeUnique) : base(isSynchronized, isReadOnly, isFixedSize) { _isResetNotSupported = isResetNotSupported; _isGenericCompatibility = isGenericCompatibility; _itemsMustBeUnique = itemsMustBeUnique; ValidArrayTypes = new[] {typeof (object), typeof (T)}; SearchingThrowsFromInvalidValue = false; } protected override sealed bool IsResetNotSupported { get { return _isResetNotSupported; } } protected override sealed bool IsGenericCompatibility { get { return _isGenericCompatibility; } } protected override sealed bool ItemsMustBeUnique { get { return _itemsMustBeUnique; } } protected override sealed bool ItemsMustBeNonNull { get { return default(T) != null; } } protected override sealed object GenerateItem() { return CreateItem(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected abstract T CreateItem(); /// <summary> /// When overridden in a derived class, Gets an instance of the list under test containing the given items. /// </summary> /// <param name="items">The items to initialize the list with.</param> /// <returns>An instance of the list under test containing the given items.</returns> protected abstract TList CreateList(IEnumerable<T> items); /// <summary> /// When overridden in a derived class, Gets an instance of the enumerable under test containing the given items. /// </summary> /// <param name="items">The items to initialize the enumerable with.</param> /// <returns>An instance of the enumerable under test containing the given items.</returns> protected override sealed IEnumerable GetEnumerable( object[] items) { return CreateList( items == null ? Enumerable.Empty<T>() : items.Cast<T>()); } /// <summary> /// When overridden in a derived class, invalidates any enumerators for the given list. /// </summary> /// <param name="list">The list to invalidate enumerators for.</param> /// <returns>The new contents of the list.</returns> protected abstract IEnumerable<T> InvalidateEnumerator( TList list); /// <summary> /// When overridden in a derived class, invalidates any enumerators for the given IEnumerable. /// </summary> /// <param name="enumerable">The <see cref="IEnumerable" /> to invalidate enumerators for.</param> /// <returns>The new set of items in the <see cref="IEnumerable" /></returns> protected override sealed object[] InvalidateEnumerator( IEnumerable enumerable) { return InvalidateEnumerator((TList) enumerable) .OfType<object>() .ToArray(); } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Net.Http/tests/UnitTests/Headers/EntityTagHeaderValueTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Http.Headers; using Xunit; namespace System.Net.Http.Tests { public class EntityTagHeaderValueTest { [Fact] public void Ctor_ETagNull_Throw() { AssertExtensions.Throws<ArgumentException>("tag", () => { new EntityTagHeaderValue(null); }); } [Fact] public void Ctor_ETagEmpty_Throw() { // null and empty should be treated the same. So we also throw for empty strings. AssertExtensions.Throws<ArgumentException>("tag", () => { new EntityTagHeaderValue(string.Empty); }); } [Fact] public void Ctor_ETagInvalidFormat_ThrowFormatException() { // When adding values using strongly typed objects, no leading/trailing LWS (whitespace) are allowed. AssertFormatException("tag"); AssertFormatException("*"); AssertFormatException(" tag "); AssertFormatException("\"tag\" invalid"); AssertFormatException("\"tag"); AssertFormatException("tag\""); AssertFormatException("\"tag\"\""); AssertFormatException("\"\"tag\"\""); AssertFormatException("\"\"tag\""); AssertFormatException("W/\"tag\""); } [Fact] public void Ctor_ETagValidFormat_SuccessfullyCreated() { EntityTagHeaderValue etag = new EntityTagHeaderValue("\"tag\""); Assert.Equal("\"tag\"", etag.Tag); Assert.False(etag.IsWeak); } [Fact] public void Ctor_ETagValidFormatAndIsWeak_SuccessfullyCreated() { EntityTagHeaderValue etag = new EntityTagHeaderValue("\"e tag\"", true); Assert.Equal("\"e tag\"", etag.Tag); Assert.True(etag.IsWeak); } [Fact] public void ToString_UseDifferentETags_AllSerializedCorrectly() { EntityTagHeaderValue etag = new EntityTagHeaderValue("\"e tag\""); Assert.Equal("\"e tag\"", etag.ToString()); etag = new EntityTagHeaderValue("\"e tag\"", true); Assert.Equal("W/\"e tag\"", etag.ToString()); etag = new EntityTagHeaderValue("\"\"", false); Assert.Equal("\"\"", etag.ToString()); } [Fact] public void GetHashCode_UseSameAndDifferentETags_SameOrDifferentHashCodes() { EntityTagHeaderValue etag1 = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue etag2 = new EntityTagHeaderValue("\"TAG\""); EntityTagHeaderValue etag3 = new EntityTagHeaderValue("\"tag\"", true); EntityTagHeaderValue etag4 = new EntityTagHeaderValue("\"tag1\""); EntityTagHeaderValue etag5 = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue etag6 = EntityTagHeaderValue.Any; Assert.NotEqual(etag1.GetHashCode(), etag2.GetHashCode()); Assert.NotEqual(etag1.GetHashCode(), etag3.GetHashCode()); Assert.NotEqual(etag1.GetHashCode(), etag4.GetHashCode()); Assert.NotEqual(etag1.GetHashCode(), etag6.GetHashCode()); Assert.Equal(etag1.GetHashCode(), etag5.GetHashCode()); } [Fact] public void Equals_UseSameAndDifferentETags_EqualOrNotEqualNoExceptions() { EntityTagHeaderValue etag1 = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue etag2 = new EntityTagHeaderValue("\"TAG\""); EntityTagHeaderValue etag3 = new EntityTagHeaderValue("\"tag\"", true); EntityTagHeaderValue etag4 = new EntityTagHeaderValue("\"tag1\""); EntityTagHeaderValue etag5 = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue etag6 = EntityTagHeaderValue.Any; Assert.False(etag1.Equals(etag2)); Assert.False(etag2.Equals(etag1)); Assert.False(etag1.Equals(null)); Assert.False(etag1.Equals(etag3)); Assert.False(etag3.Equals(etag1)); Assert.False(etag1.Equals(etag4)); Assert.False(etag1.Equals(etag6)); Assert.True(etag1.Equals(etag5)); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { EntityTagHeaderValue source = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue clone = (EntityTagHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Tag, clone.Tag); Assert.Equal(source.IsWeak, clone.IsWeak); source = new EntityTagHeaderValue("\"tag\"", true); clone = (EntityTagHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Tag, clone.Tag); Assert.Equal(source.IsWeak, clone.IsWeak); Assert.Same(EntityTagHeaderValue.Any, ((ICloneable)EntityTagHeaderValue.Any).Clone()); } [Fact] public void GetEntityTagLength_DifferentValidScenarios_AllReturnNonZero() { EntityTagHeaderValue result = null; Assert.Equal(6, EntityTagHeaderValue.GetEntityTagLength("\"ta\u4F1Ag\"", 0, out result)); Assert.Equal("\"ta\u4F1Ag\"", result.Tag); Assert.False(result.IsWeak); Assert.Equal(9, EntityTagHeaderValue.GetEntityTagLength("W/\"tag\" ", 0, out result)); Assert.Equal("\"tag\"", result.Tag); Assert.True(result.IsWeak); // Note that even if after a valid tag & whitespace there are invalid characters, GetEntityTagLength() // will return the length of the valid tag and ignore the invalid characters at the end. It is the callers // responsibility to consider the whole string invalid if after a valid ETag there are invalid chars. Assert.Equal(9, EntityTagHeaderValue.GetEntityTagLength("\"tag\" !!", 0, out result)); Assert.Equal("\"tag\"", result.Tag); Assert.False(result.IsWeak); Assert.Equal(7, EntityTagHeaderValue.GetEntityTagLength("\"W/tag\"", 0, out result)); Assert.Equal("\"W/tag\"", result.Tag); Assert.False(result.IsWeak); Assert.Equal(9, EntityTagHeaderValue.GetEntityTagLength("W/ \"tag\"", 0, out result)); Assert.Equal("\"tag\"", result.Tag); Assert.True(result.IsWeak); // We also accept lower-case 'w': e.g. 'w/"tag"' rather than 'W/"tag"' Assert.Equal(4, EntityTagHeaderValue.GetEntityTagLength("w/\"\"", 0, out result)); Assert.Equal("\"\"", result.Tag); Assert.True(result.IsWeak); Assert.Equal(2, EntityTagHeaderValue.GetEntityTagLength("\"\"", 0, out result)); Assert.Equal("\"\"", result.Tag); Assert.False(result.IsWeak); Assert.Equal(2, EntityTagHeaderValue.GetEntityTagLength(",* , ", 1, out result)); Assert.Same(EntityTagHeaderValue.Any, result); } [Fact] public void GetEntityTagLength_DifferentInvalidScenarios_AllReturnZero() { EntityTagHeaderValue result = null; // no leading spaces allowed. Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(" \"tag\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("\"tag", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("tag\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("a/\"tag\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W//\"tag\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W/", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W/\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(null, 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(string.Empty, 0, out result)); Assert.Null(result); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidParse("\"tag\"", new EntityTagHeaderValue("\"tag\"")); CheckValidParse(" \"tag\" ", new EntityTagHeaderValue("\"tag\"")); CheckValidParse("\"tag\"", new EntityTagHeaderValue("\"tag\"")); CheckValidParse("\"tag\u4F1A\"", new EntityTagHeaderValue("\"tag\u4F1A\"")); CheckValidParse("W/\"tag\"", new EntityTagHeaderValue("\"tag\"", true)); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse(null); CheckInvalidParse(string.Empty); CheckInvalidParse(" "); CheckInvalidParse(" !"); CheckInvalidParse("tag\" !"); CheckInvalidParse("!\"tag\""); CheckInvalidParse("\"tag\","); CheckInvalidParse("\"tag\" \"tag2\""); CheckInvalidParse("/\"tag\""); CheckInvalidParse("*"); // "any" is not allowed as ETag value. CheckInvalidParse("\r\n \"tag\"\r\n "); CheckInvalidParse("\"tag\" \r\n !!"); } #region Helper methods private void CheckValidParse(string input, EntityTagHeaderValue expectedResult) { EntityTagHeaderValue result = EntityTagHeaderValue.Parse(input); Assert.Equal(expectedResult, result); Assert.True(EntityTagHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>(() => { EntityTagHeaderValue.Parse(input); }); Assert.False(EntityTagHeaderValue.TryParse(input, out EntityTagHeaderValue result)); Assert.Null(result); } private static void AssertFormatException(string tag) { Assert.Throws<FormatException>(() => { new EntityTagHeaderValue(tag); }); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Http.Headers; using Xunit; namespace System.Net.Http.Tests { public class EntityTagHeaderValueTest { [Fact] public void Ctor_ETagNull_Throw() { AssertExtensions.Throws<ArgumentException>("tag", () => { new EntityTagHeaderValue(null); }); } [Fact] public void Ctor_ETagEmpty_Throw() { // null and empty should be treated the same. So we also throw for empty strings. AssertExtensions.Throws<ArgumentException>("tag", () => { new EntityTagHeaderValue(string.Empty); }); } [Fact] public void Ctor_ETagInvalidFormat_ThrowFormatException() { // When adding values using strongly typed objects, no leading/trailing LWS (whitespace) are allowed. AssertFormatException("tag"); AssertFormatException("*"); AssertFormatException(" tag "); AssertFormatException("\"tag\" invalid"); AssertFormatException("\"tag"); AssertFormatException("tag\""); AssertFormatException("\"tag\"\""); AssertFormatException("\"\"tag\"\""); AssertFormatException("\"\"tag\""); AssertFormatException("W/\"tag\""); } [Fact] public void Ctor_ETagValidFormat_SuccessfullyCreated() { EntityTagHeaderValue etag = new EntityTagHeaderValue("\"tag\""); Assert.Equal("\"tag\"", etag.Tag); Assert.False(etag.IsWeak); } [Fact] public void Ctor_ETagValidFormatAndIsWeak_SuccessfullyCreated() { EntityTagHeaderValue etag = new EntityTagHeaderValue("\"e tag\"", true); Assert.Equal("\"e tag\"", etag.Tag); Assert.True(etag.IsWeak); } [Fact] public void ToString_UseDifferentETags_AllSerializedCorrectly() { EntityTagHeaderValue etag = new EntityTagHeaderValue("\"e tag\""); Assert.Equal("\"e tag\"", etag.ToString()); etag = new EntityTagHeaderValue("\"e tag\"", true); Assert.Equal("W/\"e tag\"", etag.ToString()); etag = new EntityTagHeaderValue("\"\"", false); Assert.Equal("\"\"", etag.ToString()); } [Fact] public void GetHashCode_UseSameAndDifferentETags_SameOrDifferentHashCodes() { EntityTagHeaderValue etag1 = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue etag2 = new EntityTagHeaderValue("\"TAG\""); EntityTagHeaderValue etag3 = new EntityTagHeaderValue("\"tag\"", true); EntityTagHeaderValue etag4 = new EntityTagHeaderValue("\"tag1\""); EntityTagHeaderValue etag5 = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue etag6 = EntityTagHeaderValue.Any; Assert.NotEqual(etag1.GetHashCode(), etag2.GetHashCode()); Assert.NotEqual(etag1.GetHashCode(), etag3.GetHashCode()); Assert.NotEqual(etag1.GetHashCode(), etag4.GetHashCode()); Assert.NotEqual(etag1.GetHashCode(), etag6.GetHashCode()); Assert.Equal(etag1.GetHashCode(), etag5.GetHashCode()); } [Fact] public void Equals_UseSameAndDifferentETags_EqualOrNotEqualNoExceptions() { EntityTagHeaderValue etag1 = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue etag2 = new EntityTagHeaderValue("\"TAG\""); EntityTagHeaderValue etag3 = new EntityTagHeaderValue("\"tag\"", true); EntityTagHeaderValue etag4 = new EntityTagHeaderValue("\"tag1\""); EntityTagHeaderValue etag5 = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue etag6 = EntityTagHeaderValue.Any; Assert.False(etag1.Equals(etag2)); Assert.False(etag2.Equals(etag1)); Assert.False(etag1.Equals(null)); Assert.False(etag1.Equals(etag3)); Assert.False(etag3.Equals(etag1)); Assert.False(etag1.Equals(etag4)); Assert.False(etag1.Equals(etag6)); Assert.True(etag1.Equals(etag5)); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { EntityTagHeaderValue source = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue clone = (EntityTagHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Tag, clone.Tag); Assert.Equal(source.IsWeak, clone.IsWeak); source = new EntityTagHeaderValue("\"tag\"", true); clone = (EntityTagHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Tag, clone.Tag); Assert.Equal(source.IsWeak, clone.IsWeak); Assert.Same(EntityTagHeaderValue.Any, ((ICloneable)EntityTagHeaderValue.Any).Clone()); } [Fact] public void GetEntityTagLength_DifferentValidScenarios_AllReturnNonZero() { EntityTagHeaderValue result = null; Assert.Equal(6, EntityTagHeaderValue.GetEntityTagLength("\"ta\u4F1Ag\"", 0, out result)); Assert.Equal("\"ta\u4F1Ag\"", result.Tag); Assert.False(result.IsWeak); Assert.Equal(9, EntityTagHeaderValue.GetEntityTagLength("W/\"tag\" ", 0, out result)); Assert.Equal("\"tag\"", result.Tag); Assert.True(result.IsWeak); // Note that even if after a valid tag & whitespace there are invalid characters, GetEntityTagLength() // will return the length of the valid tag and ignore the invalid characters at the end. It is the callers // responsibility to consider the whole string invalid if after a valid ETag there are invalid chars. Assert.Equal(9, EntityTagHeaderValue.GetEntityTagLength("\"tag\" !!", 0, out result)); Assert.Equal("\"tag\"", result.Tag); Assert.False(result.IsWeak); Assert.Equal(7, EntityTagHeaderValue.GetEntityTagLength("\"W/tag\"", 0, out result)); Assert.Equal("\"W/tag\"", result.Tag); Assert.False(result.IsWeak); Assert.Equal(9, EntityTagHeaderValue.GetEntityTagLength("W/ \"tag\"", 0, out result)); Assert.Equal("\"tag\"", result.Tag); Assert.True(result.IsWeak); // We also accept lower-case 'w': e.g. 'w/"tag"' rather than 'W/"tag"' Assert.Equal(4, EntityTagHeaderValue.GetEntityTagLength("w/\"\"", 0, out result)); Assert.Equal("\"\"", result.Tag); Assert.True(result.IsWeak); Assert.Equal(2, EntityTagHeaderValue.GetEntityTagLength("\"\"", 0, out result)); Assert.Equal("\"\"", result.Tag); Assert.False(result.IsWeak); Assert.Equal(2, EntityTagHeaderValue.GetEntityTagLength(",* , ", 1, out result)); Assert.Same(EntityTagHeaderValue.Any, result); } [Fact] public void GetEntityTagLength_DifferentInvalidScenarios_AllReturnZero() { EntityTagHeaderValue result = null; // no leading spaces allowed. Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(" \"tag\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("\"tag", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("tag\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("a/\"tag\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W//\"tag\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W/", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W/\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(null, 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(string.Empty, 0, out result)); Assert.Null(result); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidParse("\"tag\"", new EntityTagHeaderValue("\"tag\"")); CheckValidParse(" \"tag\" ", new EntityTagHeaderValue("\"tag\"")); CheckValidParse("\"tag\"", new EntityTagHeaderValue("\"tag\"")); CheckValidParse("\"tag\u4F1A\"", new EntityTagHeaderValue("\"tag\u4F1A\"")); CheckValidParse("W/\"tag\"", new EntityTagHeaderValue("\"tag\"", true)); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse(null); CheckInvalidParse(string.Empty); CheckInvalidParse(" "); CheckInvalidParse(" !"); CheckInvalidParse("tag\" !"); CheckInvalidParse("!\"tag\""); CheckInvalidParse("\"tag\","); CheckInvalidParse("\"tag\" \"tag2\""); CheckInvalidParse("/\"tag\""); CheckInvalidParse("*"); // "any" is not allowed as ETag value. CheckInvalidParse("\r\n \"tag\"\r\n "); CheckInvalidParse("\"tag\" \r\n !!"); } #region Helper methods private void CheckValidParse(string input, EntityTagHeaderValue expectedResult) { EntityTagHeaderValue result = EntityTagHeaderValue.Parse(input); Assert.Equal(expectedResult, result); Assert.True(EntityTagHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>(() => { EntityTagHeaderValue.Parse(input); }); Assert.False(EntityTagHeaderValue.TryParse(input, out EntityTagHeaderValue result)); Assert.Null(result); } private static void AssertFormatException(string tag) { Assert.Throws<FormatException>(() => { new EntityTagHeaderValue(tag); }); } #endregion } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.ComponentModel.Composition/tests/System/ComponentModel/Composition/Factories/ImportDefinitionFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Linq.Expressions; namespace System.ComponentModel.Composition.Factories { // This class deliberately does not create instances of ImportDefinition, // so as to test other derived classes from ImportDefinition. internal static partial class ImportDefinitionFactory { public static ImportDefinition Create(Type contractType, ImportCardinality cardinality) { return Create(AttributedModelServices.GetContractName(contractType), cardinality); } public static ImportDefinition Create(string contractName) { return Create(contractName, (IEnumerable<KeyValuePair<string, Type>>)null, ImportCardinality.ExactlyOne, true, false); } public static ImportDefinition Create(string contractName, IEnumerable<KeyValuePair<string, Type>> requiredMetadata) { return Create(contractName, requiredMetadata, ImportCardinality.ExactlyOne, true, false); } public static ImportDefinition Create(string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { return Create(contractName, (IEnumerable<KeyValuePair<string, Type>>)null, cardinality, isRecomposable, isPrerequisite); } public static ImportDefinition Create(string contractName, ImportCardinality cardinality) { return Create(contractName, (IEnumerable<KeyValuePair<string, Type>>)null, cardinality, false, false); } public static ImportDefinition Create(string contractName, bool isRecomposable) { return Create(contractName, (IEnumerable<KeyValuePair<string, Type>>)null, ImportCardinality.ExactlyOne, isRecomposable, false); } public static ImportDefinition Create(string contractName, bool isRecomposable, bool isPrerequisite) { return Create(contractName, (IEnumerable<KeyValuePair<string, Type>>)null, ImportCardinality.ExactlyOne, isRecomposable, isPrerequisite); } public static ImportDefinition Create(string contractName, IEnumerable<KeyValuePair<string, Type>> requiredMetadata, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { return new DerivedContractBasedImportDefinition(contractName, requiredMetadata, cardinality, isRecomposable, isPrerequisite); } public static ImportDefinition Create() { return Create((Expression<Func<ExportDefinition, bool>>)null); } public static ImportDefinition Create(Expression<Func<ExportDefinition, bool>> constraint) { return Create(constraint, ImportCardinality.ExactlyOne, true, false); } public static ImportDefinition Create(Expression<Func<ExportDefinition, bool>> constraint, ImportCardinality cardinality) { return Create(constraint, cardinality, true, false); } public static ImportDefinition Create(Expression<Func<ExportDefinition, bool>> constraint, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { return new DerivedImportDefinition(constraint, cardinality, isRecomposable, isPrerequisite); } public static ImportDefinition CreateDefault(string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { return new ContractBasedImportDefinition(contractName, (string)null, (IEnumerable<KeyValuePair<string, Type>>)null, cardinality, isRecomposable, isPrerequisite, CreationPolicy.Any); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Linq.Expressions; namespace System.ComponentModel.Composition.Factories { // This class deliberately does not create instances of ImportDefinition, // so as to test other derived classes from ImportDefinition. internal static partial class ImportDefinitionFactory { public static ImportDefinition Create(Type contractType, ImportCardinality cardinality) { return Create(AttributedModelServices.GetContractName(contractType), cardinality); } public static ImportDefinition Create(string contractName) { return Create(contractName, (IEnumerable<KeyValuePair<string, Type>>)null, ImportCardinality.ExactlyOne, true, false); } public static ImportDefinition Create(string contractName, IEnumerable<KeyValuePair<string, Type>> requiredMetadata) { return Create(contractName, requiredMetadata, ImportCardinality.ExactlyOne, true, false); } public static ImportDefinition Create(string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { return Create(contractName, (IEnumerable<KeyValuePair<string, Type>>)null, cardinality, isRecomposable, isPrerequisite); } public static ImportDefinition Create(string contractName, ImportCardinality cardinality) { return Create(contractName, (IEnumerable<KeyValuePair<string, Type>>)null, cardinality, false, false); } public static ImportDefinition Create(string contractName, bool isRecomposable) { return Create(contractName, (IEnumerable<KeyValuePair<string, Type>>)null, ImportCardinality.ExactlyOne, isRecomposable, false); } public static ImportDefinition Create(string contractName, bool isRecomposable, bool isPrerequisite) { return Create(contractName, (IEnumerable<KeyValuePair<string, Type>>)null, ImportCardinality.ExactlyOne, isRecomposable, isPrerequisite); } public static ImportDefinition Create(string contractName, IEnumerable<KeyValuePair<string, Type>> requiredMetadata, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { return new DerivedContractBasedImportDefinition(contractName, requiredMetadata, cardinality, isRecomposable, isPrerequisite); } public static ImportDefinition Create() { return Create((Expression<Func<ExportDefinition, bool>>)null); } public static ImportDefinition Create(Expression<Func<ExportDefinition, bool>> constraint) { return Create(constraint, ImportCardinality.ExactlyOne, true, false); } public static ImportDefinition Create(Expression<Func<ExportDefinition, bool>> constraint, ImportCardinality cardinality) { return Create(constraint, cardinality, true, false); } public static ImportDefinition Create(Expression<Func<ExportDefinition, bool>> constraint, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { return new DerivedImportDefinition(constraint, cardinality, isRecomposable, isPrerequisite); } public static ImportDefinition CreateDefault(string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { return new ContractBasedImportDefinition(contractName, (string)null, (IEnumerable<KeyValuePair<string, Type>>)null, cardinality, isRecomposable, isPrerequisite, CreationPolicy.Any); } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/ILCompiler.DependencyAnalysisFramework.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>ILCompiler.DependencyAnalysisFramework</RootNamespace> <AssemblyName>ILCompiler.DependencyAnalysisFramework</AssemblyName> <TargetFramework>net5.0</TargetFramework> <EnableDefaultCompileItems>false</EnableDefaultCompileItems> <Platforms>x64;x86</Platforms> <PlatformTarget>AnyCPU</PlatformTarget> <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath> <!-- We're binplacing these into an existing publish layout so that F5 build in VS updates the same bits tests expect to see in artifacts/crossgen2. That way we never need to wonder which binaries are up to date and which are stale. --> <GenerateDependencyFile>false</GenerateDependencyFile> <Configurations>Debug;Release;Checked</Configurations> </PropertyGroup> <ItemGroup> <PackageReference Include="System.Collections.Immutable"> <Version>$(SystemCollectionsImmutableVersion)</Version> </PackageReference> </ItemGroup> <ItemGroup> <Compile Include="ComputedStaticDependencyNode.cs" /> <Compile Include="DependencyAnalyzer.cs" /> <Compile Include="DependencyAnalyzerBase.cs" /> <Compile Include="DependencyNode.cs" /> <Compile Include="DependencyNodeCore.cs" /> <Compile Include="DgmlWriter.cs" /> <Compile Include="EventSourceLogStrategy.cs" /> <Compile Include="FirstMarkLogStrategy.cs" /> <Compile Include="FullGraphLogStrategy.cs" /> <Compile Include="IDependencyAnalyzerLogEdgeVisitor.cs" /> <Compile Include="IDependencyAnalyzerLogNodeVisitor.cs" /> <Compile Include="IDependencyAnalysisMarkStrategy.cs" /> <Compile Include="IDependencyNode.cs" /> <Compile Include="NoLogStrategy.cs" /> <Compile Include="PerfEventSource.cs" /> <Compile Include="..\..\Common\Sorting\ArrayAccessor.cs"> <Link>Sorting\ArrayAccessor.cs</Link> </Compile> <Compile Include="..\..\Common\Sorting\ICompareAsEqualAction.cs"> <Link>Sorting\ICompareAsEqualAction.cs</Link> </Compile> <Compile Include="..\..\Common\Sorting\ISortableDataStructureAccessor.cs"> <Link>Sorting\ISortableDataStructureAccessor.cs</Link> </Compile> <Compile Include="..\..\Common\Sorting\ListAccessor.cs"> <Link>Sorting\ListAccessor.cs</Link> </Compile> <Compile Include="..\..\Common\Sorting\MergeSort.cs"> <Link>Sorting\MergeSort.cs</Link> </Compile> <Compile Include="..\..\Common\Sorting\MergeSortCore.cs"> <Link>Sorting\MergeSortCore.cs</Link> </Compile> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>ILCompiler.DependencyAnalysisFramework</RootNamespace> <AssemblyName>ILCompiler.DependencyAnalysisFramework</AssemblyName> <TargetFramework>net5.0</TargetFramework> <EnableDefaultCompileItems>false</EnableDefaultCompileItems> <Platforms>x64;x86</Platforms> <PlatformTarget>AnyCPU</PlatformTarget> <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath> <!-- We're binplacing these into an existing publish layout so that F5 build in VS updates the same bits tests expect to see in artifacts/crossgen2. That way we never need to wonder which binaries are up to date and which are stale. --> <GenerateDependencyFile>false</GenerateDependencyFile> <Configurations>Debug;Release;Checked</Configurations> </PropertyGroup> <ItemGroup> <PackageReference Include="System.Collections.Immutable"> <Version>$(SystemCollectionsImmutableVersion)</Version> </PackageReference> </ItemGroup> <ItemGroup> <Compile Include="ComputedStaticDependencyNode.cs" /> <Compile Include="DependencyAnalyzer.cs" /> <Compile Include="DependencyAnalyzerBase.cs" /> <Compile Include="DependencyNode.cs" /> <Compile Include="DependencyNodeCore.cs" /> <Compile Include="DgmlWriter.cs" /> <Compile Include="EventSourceLogStrategy.cs" /> <Compile Include="FirstMarkLogStrategy.cs" /> <Compile Include="FullGraphLogStrategy.cs" /> <Compile Include="IDependencyAnalyzerLogEdgeVisitor.cs" /> <Compile Include="IDependencyAnalyzerLogNodeVisitor.cs" /> <Compile Include="IDependencyAnalysisMarkStrategy.cs" /> <Compile Include="IDependencyNode.cs" /> <Compile Include="NoLogStrategy.cs" /> <Compile Include="PerfEventSource.cs" /> <Compile Include="..\..\Common\Sorting\ArrayAccessor.cs"> <Link>Sorting\ArrayAccessor.cs</Link> </Compile> <Compile Include="..\..\Common\Sorting\ICompareAsEqualAction.cs"> <Link>Sorting\ICompareAsEqualAction.cs</Link> </Compile> <Compile Include="..\..\Common\Sorting\ISortableDataStructureAccessor.cs"> <Link>Sorting\ISortableDataStructureAccessor.cs</Link> </Compile> <Compile Include="..\..\Common\Sorting\ListAccessor.cs"> <Link>Sorting\ListAccessor.cs</Link> </Compile> <Compile Include="..\..\Common\Sorting\MergeSort.cs"> <Link>Sorting\MergeSort.cs</Link> </Compile> <Compile Include="..\..\Common\Sorting\MergeSortCore.cs"> <Link>Sorting\MergeSortCore.cs</Link> </Compile> </ItemGroup> </Project>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Xml.XmlDocument/src/System.Xml.XmlDocument.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <IsPartialFacadeAssembly>true</IsPartialFacadeAssembly> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <ProjectReference Include="$(LibrariesProjectRoot)System.Private.Xml\src\System.Private.Xml.csproj" /> <Reference Include="System.Runtime" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <IsPartialFacadeAssembly>true</IsPartialFacadeAssembly> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <ProjectReference Include="$(LibrariesProjectRoot)System.Private.Xml\src\System.Private.Xml.csproj" /> <Reference Include="System.Runtime" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/mono/mono/tests/decimal-array.cs
using System; class Test { public static int Main() { decimal[,] tab = new decimal[2,2] {{3,4},{5,6}}; bool b1 = false; decimal d; try { d = tab[1,2]; } catch (Exception e) { b1 = true; } if (!b1) return 1; d = tab[1,1]; if (d != 6) return 1; return 0; } }
using System; class Test { public static int Main() { decimal[,] tab = new decimal[2,2] {{3,4},{5,6}}; bool b1 = false; decimal d; try { d = tab[1,2]; } catch (Exception e) { b1 = true; } if (!b1) return 1; d = tab[1,1]; if (d != 6) return 1; return 0; } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/GC/Features/Pinning/PinningOther/PinnedObject.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Tests Pinning of objects // Cannot pin array of objects using System; using System.Runtime.InteropServices; public class Test_PinnedObject { public static int Main() { Object[] arr = new Object[100]; try { GCHandle handle1 = GCUtil.Alloc(arr, GCHandleType.Pinned); } catch (Exception e) { Console.WriteLine("Caught: {0}", e); Console.WriteLine("Test passed"); return 100; } Console.WriteLine("Test failed"); return 1; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Tests Pinning of objects // Cannot pin array of objects using System; using System.Runtime.InteropServices; public class Test_PinnedObject { public static int Main() { Object[] arr = new Object[100]; try { GCHandle handle1 = GCUtil.Alloc(arr, GCHandleType.Pinned); } catch (Exception e) { Console.WriteLine("Caught: {0}", e); Console.WriteLine("Test passed"); return 100; } Console.WriteLine("Test failed"); return 1; } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/mono/System.Private.CoreLib/src/ILLink/ILLink.Substitutions.iOS.xml
<linker> <assembly fullname="System.Private.CoreLib"> <type fullname="System.Runtime.CompilerServices.RuntimeFeature"> <method signature="System.Boolean get_IsDynamicCodeCompiled()" body="stub" value="false" /> </type> </assembly> </linker>
<linker> <assembly fullname="System.Private.CoreLib"> <type fullname="System.Runtime.CompilerServices.RuntimeFeature"> <method signature="System.Boolean get_IsDynamicCodeCompiled()" body="stub" value="false" /> </type> </assembly> </linker>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HKDF.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Runtime.Versioning; namespace System.Security.Cryptography { /// <summary> /// RFC5869 HMAC-based Extract-and-Expand Key Derivation (HKDF) /// </summary> /// <remarks> /// In situations where the input key material is already a uniformly random bitstring, the HKDF standard allows the Extract /// phase to be skipped, and the master key to be used directly as the pseudorandom key. /// See <a href="https://tools.ietf.org/html/rfc5869">RFC5869</a> for more information. /// </remarks> [UnsupportedOSPlatform("browser")] public static class HKDF { /// <summary> /// Performs the HKDF-Extract function. /// See section 2.2 of <a href="https://tools.ietf.org/html/rfc5869#section-2.2">RFC5869</a> /// </summary> /// <param name="hashAlgorithmName">The hash algorithm used for HMAC operations.</param> /// <param name="ikm">The input keying material.</param> /// <param name="salt">The optional salt value (a non-secret random value). If not provided it defaults to a byte array of <see cref="HashLength"/> zeros.</param> /// <returns>The pseudo random key (prk).</returns> public static byte[] Extract(HashAlgorithmName hashAlgorithmName, byte[] ikm!!, byte[]? salt = null) { int hashLength = HashLength(hashAlgorithmName); byte[] prk = new byte[hashLength]; Extract(hashAlgorithmName, hashLength, ikm, salt, prk); return prk; } /// <summary> /// Performs the HKDF-Extract function. /// See section 2.2 of <a href="https://tools.ietf.org/html/rfc5869#section-2.2">RFC5869</a> /// </summary> /// <param name="hashAlgorithmName">The hash algorithm used for HMAC operations.</param> /// <param name="ikm">The input keying material.</param> /// <param name="salt">The salt value (a non-secret random value).</param> /// <param name="prk">The destination buffer to receive the pseudo-random key (prk).</param> /// <returns>The number of bytes written to the <paramref name="prk"/> buffer.</returns> public static int Extract(HashAlgorithmName hashAlgorithmName, ReadOnlySpan<byte> ikm, ReadOnlySpan<byte> salt, Span<byte> prk) { int hashLength = HashLength(hashAlgorithmName); if (prk.Length < hashLength) { throw new ArgumentException(SR.Format(SR.Cryptography_Prk_TooSmall, hashLength), nameof(prk)); } if (prk.Length > hashLength) { prk = prk.Slice(0, hashLength); } Extract(hashAlgorithmName, hashLength, ikm, salt, prk); return hashLength; } private static void Extract(HashAlgorithmName hashAlgorithmName, int hashLength, ReadOnlySpan<byte> ikm, ReadOnlySpan<byte> salt, Span<byte> prk) { Debug.Assert(HashLength(hashAlgorithmName) == hashLength); int written = HashOneShotHelpers.MacData(hashAlgorithmName, salt, ikm, prk); Debug.Assert(written == prk.Length, $"Bytes written is {written} bytes which does not match output length ({prk.Length} bytes)"); } /// <summary> /// Performs the HKDF-Expand function /// See section 2.3 of <a href="https://tools.ietf.org/html/rfc5869#section-2.3">RFC5869</a> /// </summary> /// <param name="hashAlgorithmName">The hash algorithm used for HMAC operations.</param> /// <param name="prk">The pseudorandom key of at least <see cref="HashLength"/> bytes (usually the output from Expand step).</param> /// <param name="outputLength">The length of the output keying material.</param> /// <param name="info">The optional context and application specific information.</param> /// <returns>The output keying material.</returns> /// <exception cref="ArgumentNullException"><paramref name="prk"/>is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="outputLength"/> is less than 1.</exception> public static byte[] Expand(HashAlgorithmName hashAlgorithmName, byte[] prk!!, int outputLength, byte[]? info = null) { if (outputLength <= 0) throw new ArgumentOutOfRangeException(nameof(outputLength), SR.ArgumentOutOfRange_NeedPosNum); int hashLength = HashLength(hashAlgorithmName); // Constant comes from section 2.3 (the constraint on L in the Inputs section) int maxOkmLength = 255 * hashLength; if (outputLength <= 0 || outputLength > maxOkmLength) throw new ArgumentOutOfRangeException(nameof(outputLength), SR.Format(SR.Cryptography_Okm_TooLarge, maxOkmLength)); byte[] result = new byte[outputLength]; Expand(hashAlgorithmName, hashLength, prk, result, info); return result; } /// <summary> /// Performs the HKDF-Expand function /// See section 2.3 of <a href="https://tools.ietf.org/html/rfc5869#section-2.3">RFC5869</a> /// </summary> /// <param name="hashAlgorithmName">The hash algorithm used for HMAC operations.</param> /// <param name="prk">The pseudorandom key of at least <see cref="HashLength"/> bytes (usually the output from Expand step).</param> /// <param name="output">The destination buffer to receive the output keying material.</param> /// <param name="info">The context and application specific information (can be an empty span).</param> /// <exception cref="ArgumentException"><paramref name="output"/> is empty, or is larger than the maximum allowed length.</exception> public static void Expand(HashAlgorithmName hashAlgorithmName, ReadOnlySpan<byte> prk, Span<byte> output, ReadOnlySpan<byte> info) { int hashLength = HashLength(hashAlgorithmName); if (output.Length == 0) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(output)); // Constant comes from section 2.3 (the constraint on L in the Inputs section) int maxOkmLength = 255 * hashLength; if (output.Length > maxOkmLength) throw new ArgumentException(SR.Format(SR.Cryptography_Okm_TooLarge, maxOkmLength), nameof(output)); Expand(hashAlgorithmName, hashLength, prk, output, info); } private static void Expand(HashAlgorithmName hashAlgorithmName, int hashLength, ReadOnlySpan<byte> prk, Span<byte> output, ReadOnlySpan<byte> info) { Debug.Assert(HashLength(hashAlgorithmName) == hashLength); if (prk.Length < hashLength) throw new ArgumentException(SR.Format(SR.Cryptography_Prk_TooSmall, hashLength), nameof(prk)); Span<byte> counterSpan = stackalloc byte[1]; ref byte counter = ref counterSpan[0]; Span<byte> t = Span<byte>.Empty; Span<byte> remainingOutput = output; const int MaxStackInfoBuffer = 64; Span<byte> tempInfoBuffer = stackalloc byte[MaxStackInfoBuffer]; ReadOnlySpan<byte> infoBuffer = stackalloc byte[0]; byte[]? rentedTempInfoBuffer = null; if (output.Overlaps(info)) { if (info.Length > MaxStackInfoBuffer) { rentedTempInfoBuffer = CryptoPool.Rent(info.Length); tempInfoBuffer = rentedTempInfoBuffer; } tempInfoBuffer = tempInfoBuffer.Slice(0, info.Length); info.CopyTo(tempInfoBuffer); infoBuffer = tempInfoBuffer; } else { infoBuffer = info; } using (IncrementalHash hmac = IncrementalHash.CreateHMAC(hashAlgorithmName, prk)) { for (int i = 1; ; i++) { hmac.AppendData(t); hmac.AppendData(infoBuffer); counter = (byte)i; hmac.AppendData(counterSpan); if (remainingOutput.Length >= hashLength) { t = remainingOutput.Slice(0, hashLength); remainingOutput = remainingOutput.Slice(hashLength); GetHashAndReset(hmac, t); } else { if (remainingOutput.Length > 0) { Debug.Assert(hashLength <= 512 / 8, "hashLength is larger than expected, consider increasing this value or using regular allocation"); Span<byte> lastChunk = stackalloc byte[hashLength]; GetHashAndReset(hmac, lastChunk); lastChunk.Slice(0, remainingOutput.Length).CopyTo(remainingOutput); } break; } } } if (rentedTempInfoBuffer is not null) { CryptoPool.Return(rentedTempInfoBuffer, clearSize: info.Length); } } /// <summary> /// Performs the key derivation HKDF Expand and Extract functions /// </summary> /// <param name="hashAlgorithmName">The hash algorithm used for HMAC operations.</param> /// <param name="ikm">The input keying material.</param> /// <param name="outputLength">The length of the output keying material.</param> /// <param name="salt">The optional salt value (a non-secret random value). If not provided it defaults to a byte array of <see cref="HashLength"/> zeros.</param> /// <param name="info">The optional context and application specific information.</param> /// <returns>The output keying material.</returns> /// <exception cref="ArgumentNullException"><paramref name="ikm"/>is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="outputLength"/> is less than 1.</exception> public static byte[] DeriveKey(HashAlgorithmName hashAlgorithmName, byte[] ikm!!, int outputLength, byte[]? salt = null, byte[]? info = null) { if (outputLength <= 0) throw new ArgumentOutOfRangeException(nameof(outputLength), SR.ArgumentOutOfRange_NeedPosNum); int hashLength = HashLength(hashAlgorithmName); Debug.Assert(hashLength <= 512 / 8, "hashLength is larger than expected, consider increasing this value or using regular allocation"); // Constant comes from section 2.3 (the constraint on L in the Inputs section) int maxOkmLength = 255 * hashLength; if (outputLength > maxOkmLength) throw new ArgumentOutOfRangeException(nameof(outputLength), SR.Format(SR.Cryptography_Okm_TooLarge, maxOkmLength)); Span<byte> prk = stackalloc byte[hashLength]; Extract(hashAlgorithmName, hashLength, ikm, salt, prk); byte[] result = new byte[outputLength]; Expand(hashAlgorithmName, hashLength, prk, result, info); return result; } /// <summary> /// Performs the key derivation HKDF Expand and Extract functions /// </summary> /// <param name="hashAlgorithmName">The hash algorithm used for HMAC operations.</param> /// <param name="ikm">The input keying material.</param> /// <param name="output">The output buffer representing output keying material.</param> /// <param name="salt">The salt value (a non-secret random value).</param> /// <param name="info">The context and application specific information (can be an empty span).</param> /// <exception cref="ArgumentException"><paramref name="ikm"/> is empty, or is larger than the maximum allowed length.</exception> public static void DeriveKey(HashAlgorithmName hashAlgorithmName, ReadOnlySpan<byte> ikm, Span<byte> output, ReadOnlySpan<byte> salt, ReadOnlySpan<byte> info) { int hashLength = HashLength(hashAlgorithmName); if (output.Length == 0) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(output)); // Constant comes from section 2.3 (the constraint on L in the Inputs section) int maxOkmLength = 255 * hashLength; if (output.Length > maxOkmLength) throw new ArgumentException(SR.Format(SR.Cryptography_Okm_TooLarge, maxOkmLength), nameof(output)); Debug.Assert(hashLength <= 512 / 8, "hashLength is larger than expected, consider increasing this value or using regular allocation"); Span<byte> prk = stackalloc byte[hashLength]; Extract(hashAlgorithmName, hashLength, ikm, salt, prk); Expand(hashAlgorithmName, hashLength, prk, output, info); } private static void GetHashAndReset(IncrementalHash hmac, Span<byte> output) { if (!hmac.TryGetHashAndReset(output, out int bytesWritten)) { Debug.Assert(false, "HMAC operation failed unexpectedly"); throw new CryptographicException(SR.Arg_CryptographyException); } Debug.Assert(bytesWritten == output.Length, $"Bytes written is {bytesWritten} bytes which does not match output length ({output.Length} bytes)"); } private static int HashLength(HashAlgorithmName hashAlgorithmName) { if (hashAlgorithmName == HashAlgorithmName.SHA1) { return HMACSHA1.HashSizeInBytes; } else if (hashAlgorithmName == HashAlgorithmName.SHA256) { return HMACSHA256.HashSizeInBytes; } else if (hashAlgorithmName == HashAlgorithmName.SHA384) { return HMACSHA384.HashSizeInBytes; } else if (hashAlgorithmName == HashAlgorithmName.SHA512) { return HMACSHA512.HashSizeInBytes; } else if (hashAlgorithmName == HashAlgorithmName.MD5) { return HMACMD5.HashSizeInBytes; } else { throw new ArgumentOutOfRangeException(nameof(hashAlgorithmName)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Runtime.Versioning; namespace System.Security.Cryptography { /// <summary> /// RFC5869 HMAC-based Extract-and-Expand Key Derivation (HKDF) /// </summary> /// <remarks> /// In situations where the input key material is already a uniformly random bitstring, the HKDF standard allows the Extract /// phase to be skipped, and the master key to be used directly as the pseudorandom key. /// See <a href="https://tools.ietf.org/html/rfc5869">RFC5869</a> for more information. /// </remarks> [UnsupportedOSPlatform("browser")] public static class HKDF { /// <summary> /// Performs the HKDF-Extract function. /// See section 2.2 of <a href="https://tools.ietf.org/html/rfc5869#section-2.2">RFC5869</a> /// </summary> /// <param name="hashAlgorithmName">The hash algorithm used for HMAC operations.</param> /// <param name="ikm">The input keying material.</param> /// <param name="salt">The optional salt value (a non-secret random value). If not provided it defaults to a byte array of <see cref="HashLength"/> zeros.</param> /// <returns>The pseudo random key (prk).</returns> public static byte[] Extract(HashAlgorithmName hashAlgorithmName, byte[] ikm!!, byte[]? salt = null) { int hashLength = HashLength(hashAlgorithmName); byte[] prk = new byte[hashLength]; Extract(hashAlgorithmName, hashLength, ikm, salt, prk); return prk; } /// <summary> /// Performs the HKDF-Extract function. /// See section 2.2 of <a href="https://tools.ietf.org/html/rfc5869#section-2.2">RFC5869</a> /// </summary> /// <param name="hashAlgorithmName">The hash algorithm used for HMAC operations.</param> /// <param name="ikm">The input keying material.</param> /// <param name="salt">The salt value (a non-secret random value).</param> /// <param name="prk">The destination buffer to receive the pseudo-random key (prk).</param> /// <returns>The number of bytes written to the <paramref name="prk"/> buffer.</returns> public static int Extract(HashAlgorithmName hashAlgorithmName, ReadOnlySpan<byte> ikm, ReadOnlySpan<byte> salt, Span<byte> prk) { int hashLength = HashLength(hashAlgorithmName); if (prk.Length < hashLength) { throw new ArgumentException(SR.Format(SR.Cryptography_Prk_TooSmall, hashLength), nameof(prk)); } if (prk.Length > hashLength) { prk = prk.Slice(0, hashLength); } Extract(hashAlgorithmName, hashLength, ikm, salt, prk); return hashLength; } private static void Extract(HashAlgorithmName hashAlgorithmName, int hashLength, ReadOnlySpan<byte> ikm, ReadOnlySpan<byte> salt, Span<byte> prk) { Debug.Assert(HashLength(hashAlgorithmName) == hashLength); int written = HashOneShotHelpers.MacData(hashAlgorithmName, salt, ikm, prk); Debug.Assert(written == prk.Length, $"Bytes written is {written} bytes which does not match output length ({prk.Length} bytes)"); } /// <summary> /// Performs the HKDF-Expand function /// See section 2.3 of <a href="https://tools.ietf.org/html/rfc5869#section-2.3">RFC5869</a> /// </summary> /// <param name="hashAlgorithmName">The hash algorithm used for HMAC operations.</param> /// <param name="prk">The pseudorandom key of at least <see cref="HashLength"/> bytes (usually the output from Expand step).</param> /// <param name="outputLength">The length of the output keying material.</param> /// <param name="info">The optional context and application specific information.</param> /// <returns>The output keying material.</returns> /// <exception cref="ArgumentNullException"><paramref name="prk"/>is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="outputLength"/> is less than 1.</exception> public static byte[] Expand(HashAlgorithmName hashAlgorithmName, byte[] prk!!, int outputLength, byte[]? info = null) { if (outputLength <= 0) throw new ArgumentOutOfRangeException(nameof(outputLength), SR.ArgumentOutOfRange_NeedPosNum); int hashLength = HashLength(hashAlgorithmName); // Constant comes from section 2.3 (the constraint on L in the Inputs section) int maxOkmLength = 255 * hashLength; if (outputLength <= 0 || outputLength > maxOkmLength) throw new ArgumentOutOfRangeException(nameof(outputLength), SR.Format(SR.Cryptography_Okm_TooLarge, maxOkmLength)); byte[] result = new byte[outputLength]; Expand(hashAlgorithmName, hashLength, prk, result, info); return result; } /// <summary> /// Performs the HKDF-Expand function /// See section 2.3 of <a href="https://tools.ietf.org/html/rfc5869#section-2.3">RFC5869</a> /// </summary> /// <param name="hashAlgorithmName">The hash algorithm used for HMAC operations.</param> /// <param name="prk">The pseudorandom key of at least <see cref="HashLength"/> bytes (usually the output from Expand step).</param> /// <param name="output">The destination buffer to receive the output keying material.</param> /// <param name="info">The context and application specific information (can be an empty span).</param> /// <exception cref="ArgumentException"><paramref name="output"/> is empty, or is larger than the maximum allowed length.</exception> public static void Expand(HashAlgorithmName hashAlgorithmName, ReadOnlySpan<byte> prk, Span<byte> output, ReadOnlySpan<byte> info) { int hashLength = HashLength(hashAlgorithmName); if (output.Length == 0) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(output)); // Constant comes from section 2.3 (the constraint on L in the Inputs section) int maxOkmLength = 255 * hashLength; if (output.Length > maxOkmLength) throw new ArgumentException(SR.Format(SR.Cryptography_Okm_TooLarge, maxOkmLength), nameof(output)); Expand(hashAlgorithmName, hashLength, prk, output, info); } private static void Expand(HashAlgorithmName hashAlgorithmName, int hashLength, ReadOnlySpan<byte> prk, Span<byte> output, ReadOnlySpan<byte> info) { Debug.Assert(HashLength(hashAlgorithmName) == hashLength); if (prk.Length < hashLength) throw new ArgumentException(SR.Format(SR.Cryptography_Prk_TooSmall, hashLength), nameof(prk)); Span<byte> counterSpan = stackalloc byte[1]; ref byte counter = ref counterSpan[0]; Span<byte> t = Span<byte>.Empty; Span<byte> remainingOutput = output; const int MaxStackInfoBuffer = 64; Span<byte> tempInfoBuffer = stackalloc byte[MaxStackInfoBuffer]; ReadOnlySpan<byte> infoBuffer = stackalloc byte[0]; byte[]? rentedTempInfoBuffer = null; if (output.Overlaps(info)) { if (info.Length > MaxStackInfoBuffer) { rentedTempInfoBuffer = CryptoPool.Rent(info.Length); tempInfoBuffer = rentedTempInfoBuffer; } tempInfoBuffer = tempInfoBuffer.Slice(0, info.Length); info.CopyTo(tempInfoBuffer); infoBuffer = tempInfoBuffer; } else { infoBuffer = info; } using (IncrementalHash hmac = IncrementalHash.CreateHMAC(hashAlgorithmName, prk)) { for (int i = 1; ; i++) { hmac.AppendData(t); hmac.AppendData(infoBuffer); counter = (byte)i; hmac.AppendData(counterSpan); if (remainingOutput.Length >= hashLength) { t = remainingOutput.Slice(0, hashLength); remainingOutput = remainingOutput.Slice(hashLength); GetHashAndReset(hmac, t); } else { if (remainingOutput.Length > 0) { Debug.Assert(hashLength <= 512 / 8, "hashLength is larger than expected, consider increasing this value or using regular allocation"); Span<byte> lastChunk = stackalloc byte[hashLength]; GetHashAndReset(hmac, lastChunk); lastChunk.Slice(0, remainingOutput.Length).CopyTo(remainingOutput); } break; } } } if (rentedTempInfoBuffer is not null) { CryptoPool.Return(rentedTempInfoBuffer, clearSize: info.Length); } } /// <summary> /// Performs the key derivation HKDF Expand and Extract functions /// </summary> /// <param name="hashAlgorithmName">The hash algorithm used for HMAC operations.</param> /// <param name="ikm">The input keying material.</param> /// <param name="outputLength">The length of the output keying material.</param> /// <param name="salt">The optional salt value (a non-secret random value). If not provided it defaults to a byte array of <see cref="HashLength"/> zeros.</param> /// <param name="info">The optional context and application specific information.</param> /// <returns>The output keying material.</returns> /// <exception cref="ArgumentNullException"><paramref name="ikm"/>is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="outputLength"/> is less than 1.</exception> public static byte[] DeriveKey(HashAlgorithmName hashAlgorithmName, byte[] ikm!!, int outputLength, byte[]? salt = null, byte[]? info = null) { if (outputLength <= 0) throw new ArgumentOutOfRangeException(nameof(outputLength), SR.ArgumentOutOfRange_NeedPosNum); int hashLength = HashLength(hashAlgorithmName); Debug.Assert(hashLength <= 512 / 8, "hashLength is larger than expected, consider increasing this value or using regular allocation"); // Constant comes from section 2.3 (the constraint on L in the Inputs section) int maxOkmLength = 255 * hashLength; if (outputLength > maxOkmLength) throw new ArgumentOutOfRangeException(nameof(outputLength), SR.Format(SR.Cryptography_Okm_TooLarge, maxOkmLength)); Span<byte> prk = stackalloc byte[hashLength]; Extract(hashAlgorithmName, hashLength, ikm, salt, prk); byte[] result = new byte[outputLength]; Expand(hashAlgorithmName, hashLength, prk, result, info); return result; } /// <summary> /// Performs the key derivation HKDF Expand and Extract functions /// </summary> /// <param name="hashAlgorithmName">The hash algorithm used for HMAC operations.</param> /// <param name="ikm">The input keying material.</param> /// <param name="output">The output buffer representing output keying material.</param> /// <param name="salt">The salt value (a non-secret random value).</param> /// <param name="info">The context and application specific information (can be an empty span).</param> /// <exception cref="ArgumentException"><paramref name="ikm"/> is empty, or is larger than the maximum allowed length.</exception> public static void DeriveKey(HashAlgorithmName hashAlgorithmName, ReadOnlySpan<byte> ikm, Span<byte> output, ReadOnlySpan<byte> salt, ReadOnlySpan<byte> info) { int hashLength = HashLength(hashAlgorithmName); if (output.Length == 0) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(output)); // Constant comes from section 2.3 (the constraint on L in the Inputs section) int maxOkmLength = 255 * hashLength; if (output.Length > maxOkmLength) throw new ArgumentException(SR.Format(SR.Cryptography_Okm_TooLarge, maxOkmLength), nameof(output)); Debug.Assert(hashLength <= 512 / 8, "hashLength is larger than expected, consider increasing this value or using regular allocation"); Span<byte> prk = stackalloc byte[hashLength]; Extract(hashAlgorithmName, hashLength, ikm, salt, prk); Expand(hashAlgorithmName, hashLength, prk, output, info); } private static void GetHashAndReset(IncrementalHash hmac, Span<byte> output) { if (!hmac.TryGetHashAndReset(output, out int bytesWritten)) { Debug.Assert(false, "HMAC operation failed unexpectedly"); throw new CryptographicException(SR.Arg_CryptographyException); } Debug.Assert(bytesWritten == output.Length, $"Bytes written is {bytesWritten} bytes which does not match output length ({output.Length} bytes)"); } private static int HashLength(HashAlgorithmName hashAlgorithmName) { if (hashAlgorithmName == HashAlgorithmName.SHA1) { return HMACSHA1.HashSizeInBytes; } else if (hashAlgorithmName == HashAlgorithmName.SHA256) { return HMACSHA256.HashSizeInBytes; } else if (hashAlgorithmName == HashAlgorithmName.SHA384) { return HMACSHA384.HashSizeInBytes; } else if (hashAlgorithmName == HashAlgorithmName.SHA512) { return HMACSHA512.HashSizeInBytes; } else if (hashAlgorithmName == HashAlgorithmName.MD5) { return HMACMD5.HashSizeInBytes; } else { throw new ArgumentOutOfRangeException(nameof(hashAlgorithmName)); } } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest256/Generated256.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated256 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public sequential sealed MyStruct306`2<T0, T1> extends [mscorlib]System.ValueType implements class IBase1`1<class BaseClass1>, class IBase2`2<!T1,class BaseClass0> { .pack 0 .size 1 .method public hidebysig newslot virtual instance string Method4() cil managed noinlining { ldstr "MyStruct306::Method4.2435()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass1>.Method4'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass1>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ret } .method public hidebysig newslot virtual instance string Method5() cil managed noinlining { ldstr "MyStruct306::Method5.2437()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass1>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass1>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ret } .method public hidebysig virtual instance string Method6<M0>() cil managed noinlining { ldstr "MyStruct306::Method6.2439<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass1>.Method6'<M0>() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass1>::Method6<[1]>() ldstr "MyStruct306::Method6.MI.2440<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct306::Method7.2441<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod605<M0>() cil managed noinlining { ldstr "MyStruct306::ClassMethod605.2442<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod606<M0>() cil managed noinlining { ldstr "MyStruct306::ClassMethod606.2443<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase1`1<+T0> { .method public hidebysig newslot abstract virtual instance string Method4() cil managed { } .method public hidebysig newslot abstract virtual instance string Method5() cil managed { } .method public hidebysig newslot abstract virtual instance string Method6<M0>() cil managed { } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated256 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct306.T.T<T0,T1,(valuetype MyStruct306`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct306.T.T<T0,T1,(valuetype MyStruct306`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct306`2<!!T0,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct306`2<!!T0,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct306`2<!!T0,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct306`2<!!T0,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct306.A.T<T1,(valuetype MyStruct306`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct306.A.T<T1,(valuetype MyStruct306`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct306.A.A<(valuetype MyStruct306`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct306.A.A<(valuetype MyStruct306`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct306.A.B<(valuetype MyStruct306`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct306.A.B<(valuetype MyStruct306`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct306.B.T<T1,(valuetype MyStruct306`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct306.B.T<T1,(valuetype MyStruct306`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct306.B.A<(valuetype MyStruct306`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct306.B.A<(valuetype MyStruct306`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct306.B.B<(valuetype MyStruct306`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct306.B.B<(valuetype MyStruct306`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass0> V_1) ldloca V_1 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloca V_1 dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method4() ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method5() ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::ClassMethod605<object>() ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::ClassMethod606<object>() ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::ToString() pop pop ldloc V_1 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass1> V_2) ldloca V_2 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloca V_2 dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method4() ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method5() ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::ClassMethod605<object>() ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::ClassMethod606<object>() ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::ToString() pop pop ldloc V_2 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass0> V_3) ldloca V_3 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloca V_3 dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method4() ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method5() ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method6<object>() ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::ClassMethod605<object>() ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::ClassMethod606<object>() ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::ToString() pop pop ldloc V_3 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass1> V_4) ldloca V_4 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloca V_4 dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method4() ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method5() ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::ClassMethod605<object>() ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::ClassMethod606<object>() ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::ToString() pop pop ldloc V_4 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass0> V_5) ldloca V_5 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass0> .try { ldloc V_5 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_5 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.B<valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_5 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_5 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_5 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.A<valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_5 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .try { ldloc V_5 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.A<valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_5 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_5 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_5 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.B<valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass1> V_6) ldloca V_6 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass1> .try { ldloc V_6 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_6 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.B<valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV12 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV13 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.A<valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV14 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14: .try { ldloc V_6 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV15 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15: .try { ldloc V_6 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.A<valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV16 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV17 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV18 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.A<valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV19 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV20 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV21 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.B<valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV22 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV23 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV24 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV24} LV24: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.B<valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV25 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV25} LV25: .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass0> V_7) ldloca V_7 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass0> .try { ldloc V_7 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV26 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV26} LV26: .try { ldloc V_7 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.B<valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV27 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV27} LV27: .try { ldloc V_7 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV28 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV28} LV28: .try { ldloc V_7 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV29 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV29} LV29: .try { ldloc V_7 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.A<valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV30 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV30} LV30: .try { ldloc V_7 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV31 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV31} LV31: .try { ldloc V_7 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.A<valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV32 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV32} LV32: .try { ldloc V_7 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV33 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV33} LV33: .try { ldloc V_7 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV34 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV34} LV34: .try { ldloc V_7 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.B<valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV35 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV35} LV35: .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass1> V_8) ldloca V_8 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass1> .try { ldloc V_8 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV36 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV36} LV36: .try { ldloc V_8 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.B<valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV37 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV37} LV37: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV38 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV38} LV38: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV39 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV39} LV39: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.A<valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV40 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV40} LV40: .try { ldloc V_8 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV41 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV41} LV41: .try { ldloc V_8 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.A<valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV42 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV42} LV42: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV43 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV43} LV43: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV44 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV44} LV44: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.A<valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV45 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV45} LV45: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV46 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV46} LV46: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV47 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV47} LV47: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.B<valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV48 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV48} LV48: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV49 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV49} LV49: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV50 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV50} LV50: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.B<valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV51 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV51} LV51: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass0> V_9) ldloca V_9 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass0> .try { ldloc V_9 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_9 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.A.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_9 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.A.A<valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass1> V_10) ldloca V_10 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass1> .try { ldloc V_10 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_10 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.A.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_10 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.A.B<valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass0> V_11) ldloca V_11 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass0> .try { ldloc V_11 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_11 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.B.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_11 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.B.A<valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass1> V_12) ldloca V_12 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass1> .try { ldloc V_12 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_12 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.B.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_12 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.B.B<valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass0> V_13) ldloca V_13 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::ClassMethod605<object>() calli default string(object) ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::ClassMethod606<object>() calli default string(object) ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldnull ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance bool valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::ToString() calli default string(object) pop ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass1> V_14) ldloca V_14 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::ClassMethod605<object>() calli default string(object) ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::ClassMethod606<object>() calli default string(object) ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldnull ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance bool valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::ToString() calli default string(object) pop ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass0> V_15) ldloca V_15 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::ClassMethod605<object>() calli default string(object) ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::ClassMethod606<object>() calli default string(object) ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldnull ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance bool valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::ToString() calli default string(object) pop ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass1> V_16) ldloca V_16 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::ClassMethod605<object>() calli default string(object) ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::ClassMethod606<object>() calli default string(object) ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldnull ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance bool valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::ToString() calli default string(object) pop ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated256::MethodCallingTest() call void Generated256::ConstrainedCallsTest() call void Generated256::StructConstrainedInterfaceCallsTest() call void Generated256::CalliTest() ldc.i4 100 ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated256 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public sequential sealed MyStruct306`2<T0, T1> extends [mscorlib]System.ValueType implements class IBase1`1<class BaseClass1>, class IBase2`2<!T1,class BaseClass0> { .pack 0 .size 1 .method public hidebysig newslot virtual instance string Method4() cil managed noinlining { ldstr "MyStruct306::Method4.2435()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass1>.Method4'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass1>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ret } .method public hidebysig newslot virtual instance string Method5() cil managed noinlining { ldstr "MyStruct306::Method5.2437()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass1>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass1>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ret } .method public hidebysig virtual instance string Method6<M0>() cil managed noinlining { ldstr "MyStruct306::Method6.2439<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass1>.Method6'<M0>() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass1>::Method6<[1]>() ldstr "MyStruct306::Method6.MI.2440<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct306::Method7.2441<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod605<M0>() cil managed noinlining { ldstr "MyStruct306::ClassMethod605.2442<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod606<M0>() cil managed noinlining { ldstr "MyStruct306::ClassMethod606.2443<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase1`1<+T0> { .method public hidebysig newslot abstract virtual instance string Method4() cil managed { } .method public hidebysig newslot abstract virtual instance string Method5() cil managed { } .method public hidebysig newslot abstract virtual instance string Method6<M0>() cil managed { } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated256 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct306.T.T<T0,T1,(valuetype MyStruct306`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct306.T.T<T0,T1,(valuetype MyStruct306`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct306`2<!!T0,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct306`2<!!T0,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct306`2<!!T0,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct306`2<!!T0,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct306.A.T<T1,(valuetype MyStruct306`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct306.A.T<T1,(valuetype MyStruct306`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct306.A.A<(valuetype MyStruct306`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct306.A.A<(valuetype MyStruct306`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct306.A.B<(valuetype MyStruct306`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct306.A.B<(valuetype MyStruct306`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct306.B.T<T1,(valuetype MyStruct306`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct306.B.T<T1,(valuetype MyStruct306`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,!!T1> callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct306.B.A<(valuetype MyStruct306`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct306.B.A<(valuetype MyStruct306`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct306.B.B<(valuetype MyStruct306`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct306.B.B<(valuetype MyStruct306`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct306`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass0> V_1) ldloca V_1 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloca V_1 dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method4() ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method5() ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::ClassMethod605<object>() ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::ClassMethod606<object>() ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::ToString() pop pop ldloc V_1 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass1> V_2) ldloca V_2 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloca V_2 dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method4() ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method5() ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::ClassMethod605<object>() ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::ClassMethod606<object>() ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::ToString() pop pop ldloc V_2 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass0> V_3) ldloca V_3 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloca V_3 dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method4() ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method5() ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method6<object>() ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::ClassMethod605<object>() ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::ClassMethod606<object>() ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::ToString() pop pop ldloc V_3 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass1> V_4) ldloca V_4 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloca V_4 dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method4() ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method5() ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::ClassMethod605<object>() ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::ClassMethod606<object>() ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type MyStruct306" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::ToString() pop pop ldloc V_4 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass0> V_5) ldloca V_5 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass0> .try { ldloc V_5 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_5 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.B<valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_5 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_5 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_5 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.A<valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_5 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .try { ldloc V_5 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.A<valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_5 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_5 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_5 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.B<valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass1> V_6) ldloca V_6 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass1> .try { ldloc V_6 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_6 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.B<valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV12 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV13 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.A<valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV14 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14: .try { ldloc V_6 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV15 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15: .try { ldloc V_6 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.A<valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV16 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV17 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV18 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.A<valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV19 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV20 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV21 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.B<valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV22 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV23 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV24 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV24} LV24: .try { ldloc V_6 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.B<valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV25 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV25} LV25: .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass0> V_7) ldloca V_7 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass0> .try { ldloc V_7 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV26 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV26} LV26: .try { ldloc V_7 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.B<valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV27 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV27} LV27: .try { ldloc V_7 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV28 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV28} LV28: .try { ldloc V_7 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV29 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV29} LV29: .try { ldloc V_7 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.A<valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV30 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV30} LV30: .try { ldloc V_7 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV31 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV31} LV31: .try { ldloc V_7 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.A<valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV32 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV32} LV32: .try { ldloc V_7 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV33 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV33} LV33: .try { ldloc V_7 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV34 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV34} LV34: .try { ldloc V_7 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.B<valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV35 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV35} LV35: .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass1> V_8) ldloca V_8 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass1> .try { ldloc V_8 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV36 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV36} LV36: .try { ldloc V_8 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.B<valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV37 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV37} LV37: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV38 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV38} LV38: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV39 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV39} LV39: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.A<valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV40 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV40} LV40: .try { ldloc V_8 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV41 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV41} LV41: .try { ldloc V_8 ldstr "MyStruct306::Method4.MI.2436()#MyStruct306::Method5.MI.2438()#MyStruct306::Method6.MI.2440<System.Object>()#" call void Generated256::M.IBase1.A<valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV42 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV42} LV42: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV43 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV43} LV43: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV44 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV44} LV44: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.A<valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV45 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV45} LV45: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV46 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV46} LV46: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV47 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV47} LV47: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.A.B<valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV48 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV48} LV48: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV49 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV49} LV49: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV50 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV50} LV50: .try { ldloc V_8 ldstr "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.IBase2.B.B<valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV51 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV51} LV51: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass0> V_9) ldloca V_9 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass0> .try { ldloc V_9 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_9 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.A.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_9 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.A.A<valuetype MyStruct306`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass1> V_10) ldloca V_10 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass1> .try { ldloc V_10 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_10 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.A.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_10 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.A.B<valuetype MyStruct306`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass0> V_11) ldloca V_11 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass0> .try { ldloc V_11 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_11 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.B.T<class BaseClass0,valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_11 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.B.A<valuetype MyStruct306`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass1> V_12) ldloca V_12 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass1> .try { ldloc V_12 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_12 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.B.T<class BaseClass1,valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_12 ldstr "MyStruct306::Method4.MI.2436()#" + "MyStruct306::Method5.MI.2438()#" + "MyStruct306::Method6.MI.2440<System.Object>()#" + "MyStruct306::Method7.2441<System.Object>()#" call void Generated256::M.MyStruct306.B.B<valuetype MyStruct306`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass0> V_13) ldloca V_13 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::ClassMethod605<object>() calli default string(object) ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::ClassMethod606<object>() calli default string(object) ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldnull ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance bool valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass0>::ToString() calli default string(object) pop ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct306`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct306`2<class BaseClass0,class BaseClass1> V_14) ldloca V_14 initobj valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::ClassMethod605<object>() calli default string(object) ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::ClassMethod606<object>() calli default string(object) ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldnull ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance bool valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass0,class BaseClass1>::ToString() calli default string(object) pop ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct306`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass0> V_15) ldloca V_15 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::ClassMethod605<object>() calli default string(object) ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::ClassMethod606<object>() calli default string(object) ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldnull ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance bool valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass0>::ToString() calli default string(object) pop ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct306`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct306`2<class BaseClass1,class BaseClass1> V_16) ldloca V_16 initobj valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct306::Method4.2435()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct306::Method5.2437()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.2439<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::ClassMethod605<object>() calli default string(object) ldstr "MyStruct306::ClassMethod605.2442<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::ClassMethod606<object>() calli default string(object) ldstr "MyStruct306::ClassMethod606.2443<System.Object>()" ldstr "valuetype MyStruct306`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldnull ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance bool valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct306`2<class BaseClass1,class BaseClass1>::ToString() calli default string(object) pop ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct306::Method4.MI.2436()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct306::Method5.MI.2438()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct306::Method6.MI.2440<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct306`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct306::Method7.2441<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct306`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated256::MethodCallingTest() call void Generated256::ConstrainedCallsTest() call void Generated256::StructConstrainedInterfaceCallsTest() call void Generated256::CalliTest() ldc.i4 100 ret } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/Microsoft.VisualBasic.Core/src/Microsoft.VisualBasic.Core.vbproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <NoVbRuntimeReference>true</NoVbRuntimeReference> <VBRuntime>None</VBRuntime> <OptionStrict>On</OptionStrict> <OptionExplicit>On</OptionExplicit> <OptionInfer>Off</OptionInfer> <MyType>Empty</MyType> <OptionCompare>Binary</OptionCompare> <WarningsNotAsErrors>42025</WarningsNotAsErrors> <DefineConstants>$(DefineConstants),LATEBINDING=True</DefineConstants> <NoWarn>$(NoWarn),CA1052,CA1810,CA2200</NoWarn> <!-- Avoid unused fields warnings in Unix build --> <AssemblyName>Microsoft.VisualBasic.Core</AssemblyName> <RemoveIntegerChecks>false</RemoveIntegerChecks> <RootNamespace /> <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppCurrent)-windows</TargetFrameworks> </PropertyGroup> <!-- DesignTimeBuild requires all the TargetFramework Derived Properties to not be present in the first property group. --> <PropertyGroup> <TargetPlatformIdentifier>$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)'))</TargetPlatformIdentifier> <ILLinkDescriptorsXml Condition="'$(TargetPlatformIdentifier)' == 'windows'">$(MSBuildProjectDirectory)\ILLink\ILLink.Descriptors.Windows.xml</ILLinkDescriptorsXml> <DefineConstants Condition="'$(TargetPlatformIdentifier)' == 'windows'">$(DefineConstants),TARGET_WINDOWS=True</DefineConstants> <NoWarn Condition="'$(TargetPlatformIdentifier)' != 'windows'">$(NoWarn);CA1823</NoWarn> </PropertyGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'windows'"> <Compile Include="Microsoft\VisualBasic\Helpers\NativeMethods.vb" /> <Compile Include="Microsoft\VisualBasic\Helpers\NativeTypes.vb" /> <Compile Include="Microsoft\VisualBasic\Helpers\SafeNativeMethods.vb" /> <Compile Include="Microsoft\VisualBasic\Helpers\UnsafeNativeMethods.vb" /> </ItemGroup> <ItemGroup> <Compile Include="Microsoft\VisualBasic\Collection.vb" /> <Compile Include="Microsoft\VisualBasic\ComClassAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\BooleanType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\ByteType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\CacheDict.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\CharType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\CharArrayType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\ConversionResolution.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\Conversions.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\DateType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\DecimalType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\DesignerGeneratedAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\DoubleType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\ExceptionUtils.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\IDOBinder.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\IncompleteInitialization.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\IntegerType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\IOUtils.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\LateBinding.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\LikeOperator.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\LongType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\NewLateBinding.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\ObjectFlowControl.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\ObjectType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\Operators.Resolution.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\Operators.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\OptionCompareAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\OptionTextAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\OverloadResolution.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\ProjectData.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\ShortType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\SingleType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\StandardModuleAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\StaticLocalInitFlag.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\StringType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\StructUtils.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\Symbols.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\Utils.LateBinder.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\Utils.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\VB6BinaryFile.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\VB6File.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\VB6InputFile.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\VB6OutputFile.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\VB6RandomFile.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\VBBinder.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\Versioned.vb" /> <Compile Include="Microsoft\VisualBasic\Constants.vb" /> <Compile Include="Microsoft\VisualBasic\ControlChars.vb" /> <Compile Include="Microsoft\VisualBasic\Conversion.vb" /> <Compile Include="Microsoft\VisualBasic\DateAndTime.vb" /> <Compile Include="Microsoft\VisualBasic\ErrObject.vb" /> <Compile Include="Microsoft\VisualBasic\FileIO\FileSystem.vb" /> <Compile Include="Microsoft\VisualBasic\FileIO\MalformedLineException.vb" /> <Compile Include="Microsoft\VisualBasic\FileIO\SpecialDirectories.vb" /> <Compile Include="Microsoft\VisualBasic\FileIO\TextFieldParser.vb" /> <Compile Include="Microsoft\VisualBasic\FileSystem.vb" /> <Compile Include="Microsoft\VisualBasic\Financial.vb" /> <Compile Include="Microsoft\VisualBasic\Globals.vb" /> <Compile Include="Microsoft\VisualBasic\Helpers\ForEachEnum.vb" /> <Compile Include="Microsoft\VisualBasic\HideModuleNameAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\Information.vb" /> <Compile Include="Microsoft\VisualBasic\Interaction.vb" /> <Compile Include="Microsoft\VisualBasic\MyGroupCollectionAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\Strings.vb" /> <Compile Include="Microsoft\VisualBasic\VBFixedArrayAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\VBFixedStringAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\VBMath.vb" /> </ItemGroup> <ItemGroup> <Reference Include="Microsoft.Win32.Primitives" /> <Reference Include="Microsoft.Win32.Registry" /> <Reference Include="System.Collections" /> <Reference Include="System.Collections.NonGeneric" /> <Reference Include="System.Collections.Specialized" /> <Reference Include="System.ComponentModel" /> <Reference Include="System.ComponentModel.Primitives" /> <Reference Include="System.Diagnostics.Debug" /> <Reference Include="System.Diagnostics.Process" /> <Reference Include="System.Dynamic.Runtime" /> <Reference Include="System.Globalization" /> <Reference Include="System.IO" /> <Reference Include="System.IO.FileSystem" /> <Reference Include="System.IO.FileSystem.DriveInfo" /> <Reference Include="System.Linq" /> <Reference Include="System.Linq.Expressions" /> <Reference Include="System.ObjectModel" /> <Reference Include="System.Reflection" /> <Reference Include="System.Reflection.Emit" /> <Reference Include="System.Reflection.Emit.ILGeneration" /> <Reference Include="System.Reflection.Emit.Lightweight" /> <Reference Include="System.Reflection.Extensions" /> <Reference Include="System.Reflection.Primitives" /> <Reference Include="System.Reflection.TypeExtensions" /> <Reference Include="System.Resources.ResourceManager" /> <Reference Include="System.Runtime" /> <Reference Include="System.Runtime.Extensions" /> <Reference Include="System.Runtime.InteropServices" /> <Reference Include="System.Security.Principal" /> <Reference Include="System.Text.RegularExpressions" /> <Reference Include="System.Threading" /> <Reference Include="System.Threading.Tasks" /> <Reference Include="System.Threading.Thread" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <NoVbRuntimeReference>true</NoVbRuntimeReference> <VBRuntime>None</VBRuntime> <OptionStrict>On</OptionStrict> <OptionExplicit>On</OptionExplicit> <OptionInfer>Off</OptionInfer> <MyType>Empty</MyType> <OptionCompare>Binary</OptionCompare> <WarningsNotAsErrors>42025</WarningsNotAsErrors> <DefineConstants>$(DefineConstants),LATEBINDING=True</DefineConstants> <NoWarn>$(NoWarn),CA1052,CA1810,CA2200</NoWarn> <!-- Avoid unused fields warnings in Unix build --> <AssemblyName>Microsoft.VisualBasic.Core</AssemblyName> <RemoveIntegerChecks>false</RemoveIntegerChecks> <RootNamespace /> <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppCurrent)-windows</TargetFrameworks> </PropertyGroup> <!-- DesignTimeBuild requires all the TargetFramework Derived Properties to not be present in the first property group. --> <PropertyGroup> <TargetPlatformIdentifier>$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)'))</TargetPlatformIdentifier> <ILLinkDescriptorsXml Condition="'$(TargetPlatformIdentifier)' == 'windows'">$(MSBuildProjectDirectory)\ILLink\ILLink.Descriptors.Windows.xml</ILLinkDescriptorsXml> <DefineConstants Condition="'$(TargetPlatformIdentifier)' == 'windows'">$(DefineConstants),TARGET_WINDOWS=True</DefineConstants> <NoWarn Condition="'$(TargetPlatformIdentifier)' != 'windows'">$(NoWarn);CA1823</NoWarn> </PropertyGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'windows'"> <Compile Include="Microsoft\VisualBasic\Helpers\NativeMethods.vb" /> <Compile Include="Microsoft\VisualBasic\Helpers\NativeTypes.vb" /> <Compile Include="Microsoft\VisualBasic\Helpers\SafeNativeMethods.vb" /> <Compile Include="Microsoft\VisualBasic\Helpers\UnsafeNativeMethods.vb" /> </ItemGroup> <ItemGroup> <Compile Include="Microsoft\VisualBasic\Collection.vb" /> <Compile Include="Microsoft\VisualBasic\ComClassAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\BooleanType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\ByteType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\CacheDict.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\CharType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\CharArrayType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\ConversionResolution.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\Conversions.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\DateType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\DecimalType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\DesignerGeneratedAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\DoubleType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\ExceptionUtils.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\IDOBinder.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\IncompleteInitialization.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\IntegerType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\IOUtils.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\LateBinding.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\LikeOperator.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\LongType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\NewLateBinding.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\ObjectFlowControl.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\ObjectType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\Operators.Resolution.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\Operators.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\OptionCompareAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\OptionTextAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\OverloadResolution.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\ProjectData.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\ShortType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\SingleType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\StandardModuleAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\StaticLocalInitFlag.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\StringType.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\StructUtils.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\Symbols.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\Utils.LateBinder.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\Utils.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\VB6BinaryFile.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\VB6File.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\VB6InputFile.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\VB6OutputFile.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\VB6RandomFile.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\VBBinder.vb" /> <Compile Include="Microsoft\VisualBasic\CompilerServices\Versioned.vb" /> <Compile Include="Microsoft\VisualBasic\Constants.vb" /> <Compile Include="Microsoft\VisualBasic\ControlChars.vb" /> <Compile Include="Microsoft\VisualBasic\Conversion.vb" /> <Compile Include="Microsoft\VisualBasic\DateAndTime.vb" /> <Compile Include="Microsoft\VisualBasic\ErrObject.vb" /> <Compile Include="Microsoft\VisualBasic\FileIO\FileSystem.vb" /> <Compile Include="Microsoft\VisualBasic\FileIO\MalformedLineException.vb" /> <Compile Include="Microsoft\VisualBasic\FileIO\SpecialDirectories.vb" /> <Compile Include="Microsoft\VisualBasic\FileIO\TextFieldParser.vb" /> <Compile Include="Microsoft\VisualBasic\FileSystem.vb" /> <Compile Include="Microsoft\VisualBasic\Financial.vb" /> <Compile Include="Microsoft\VisualBasic\Globals.vb" /> <Compile Include="Microsoft\VisualBasic\Helpers\ForEachEnum.vb" /> <Compile Include="Microsoft\VisualBasic\HideModuleNameAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\Information.vb" /> <Compile Include="Microsoft\VisualBasic\Interaction.vb" /> <Compile Include="Microsoft\VisualBasic\MyGroupCollectionAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\Strings.vb" /> <Compile Include="Microsoft\VisualBasic\VBFixedArrayAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\VBFixedStringAttribute.vb" /> <Compile Include="Microsoft\VisualBasic\VBMath.vb" /> </ItemGroup> <ItemGroup> <Reference Include="Microsoft.Win32.Primitives" /> <Reference Include="Microsoft.Win32.Registry" /> <Reference Include="System.Collections" /> <Reference Include="System.Collections.NonGeneric" /> <Reference Include="System.Collections.Specialized" /> <Reference Include="System.ComponentModel" /> <Reference Include="System.ComponentModel.Primitives" /> <Reference Include="System.Diagnostics.Debug" /> <Reference Include="System.Diagnostics.Process" /> <Reference Include="System.Dynamic.Runtime" /> <Reference Include="System.Globalization" /> <Reference Include="System.IO" /> <Reference Include="System.IO.FileSystem" /> <Reference Include="System.IO.FileSystem.DriveInfo" /> <Reference Include="System.Linq" /> <Reference Include="System.Linq.Expressions" /> <Reference Include="System.ObjectModel" /> <Reference Include="System.Reflection" /> <Reference Include="System.Reflection.Emit" /> <Reference Include="System.Reflection.Emit.ILGeneration" /> <Reference Include="System.Reflection.Emit.Lightweight" /> <Reference Include="System.Reflection.Extensions" /> <Reference Include="System.Reflection.Primitives" /> <Reference Include="System.Reflection.TypeExtensions" /> <Reference Include="System.Resources.ResourceManager" /> <Reference Include="System.Runtime" /> <Reference Include="System.Runtime.Extensions" /> <Reference Include="System.Runtime.InteropServices" /> <Reference Include="System.Security.Principal" /> <Reference Include="System.Text.RegularExpressions" /> <Reference Include="System.Threading" /> <Reference Include="System.Threading.Tasks" /> <Reference Include="System.Threading.Thread" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/AtomFeeds/link-same-rel-different-types.xml
<!-- Description: entry with two atom:link elements with a rel attribute value of alternate that has the differing types Expect: !Error --> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://contoso.com/"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>Author Name</name> </author> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href="http://contoso.com/2003/12/13/atom03.pdf" rel="alternate" type="application/pdf"/> <link href="http://contoso.com/2003/12/13/atom03.html" rel="alternate" type="text/html"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> </entry> </feed>
<!-- Description: entry with two atom:link elements with a rel attribute value of alternate that has the differing types Expect: !Error --> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://contoso.com/"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>Author Name</name> </author> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href="http://contoso.com/2003/12/13/atom03.pdf" rel="alternate" type="application/pdf"/> <link href="http://contoso.com/2003/12/13/atom03.html" rel="alternate" type="text/html"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> </entry> </feed>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/mono/mono/tests/jit-int.cs
using System; public class TestJit { public static int test_short () { int max = 32767; int min = -32768; int t1 = 0xffeedd; short s1 = (short)t1; int t2 = s1; if ((uint)t2 != 0xffffeedd) return 1; Console.WriteLine (t2.ToString ("X")); if (Int16.Parse((min).ToString()) != -32768) return 1; if (Int16.Parse((max).ToString()) != 32767) return 1; return 0; } public static int test_call (int a, int b) { return a+b; } public static int test_shift () { int a = 9, b = 1; if ((a << 1) != 18) return 1; if ((a << b) != 18) return 1; if ((a >> 1) != 4) return 1; if ((a >> b) != 4) return 1; a = -9; if ((a >> b) != -5) return 1; return 0; } public static int test_alu () { int a = 9, b = 6; if ((a + b) != 15) return 1; if ((a - b) != 3) return 1; if ((a & 8) != 8) return 1; if ((a | 2) != 11) return 1; if ((a * b) != 54) return 1; if ((a / 4) != 2) return 1; if ((a % 4) != 1) return 1; if (-a != -9) return 1; b = -1; if (~b != 0) return 1; return 0; } public static int test_branch () { int a = 5, b = 5, t; if (a == b) t = 1; else t = 0; if (t != 1) return 1; if (a != b) t = 0; else t = 1; if (t != 1) return 1; if (a >= b) t = 1; else t = 0; if (t != 1) return 1; if (a > b) t = 0; else t = 1; if (t != 1) return 1; if (a <= b) t = 1; else t = 0; if (t != 1) return 1; if (a < b) t = 0; else t = 1; if (t != 1) return 1; return 0; } public static int Main() { int num = 0; num++; if (test_short () != 0) return num; num++; if (test_call (3, 5) != 8) return num; num++; if (test_branch () != 0) return num; num++; if (test_alu () != 0) return num; num++; if (test_shift () != 0) return num; num++; return 0; } }
using System; public class TestJit { public static int test_short () { int max = 32767; int min = -32768; int t1 = 0xffeedd; short s1 = (short)t1; int t2 = s1; if ((uint)t2 != 0xffffeedd) return 1; Console.WriteLine (t2.ToString ("X")); if (Int16.Parse((min).ToString()) != -32768) return 1; if (Int16.Parse((max).ToString()) != 32767) return 1; return 0; } public static int test_call (int a, int b) { return a+b; } public static int test_shift () { int a = 9, b = 1; if ((a << 1) != 18) return 1; if ((a << b) != 18) return 1; if ((a >> 1) != 4) return 1; if ((a >> b) != 4) return 1; a = -9; if ((a >> b) != -5) return 1; return 0; } public static int test_alu () { int a = 9, b = 6; if ((a + b) != 15) return 1; if ((a - b) != 3) return 1; if ((a & 8) != 8) return 1; if ((a | 2) != 11) return 1; if ((a * b) != 54) return 1; if ((a / 4) != 2) return 1; if ((a % 4) != 1) return 1; if (-a != -9) return 1; b = -1; if (~b != 0) return 1; return 0; } public static int test_branch () { int a = 5, b = 5, t; if (a == b) t = 1; else t = 0; if (t != 1) return 1; if (a != b) t = 0; else t = 1; if (t != 1) return 1; if (a >= b) t = 1; else t = 0; if (t != 1) return 1; if (a > b) t = 0; else t = 1; if (t != 1) return 1; if (a <= b) t = 1; else t = 0; if (t != 1) return 1; if (a < b) t = 0; else t = 1; if (t != 1) return 1; return 0; } public static int Main() { int num = 0; num++; if (test_short () != 0) return num; num++; if (test_call (3, 5) != 8) return num; num++; if (test_branch () != 0) return num; num++; if (test_alu () != 0) return num; num++; if (test_shift () != 0) return num; num++; return 0; } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.1;netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <Nullable>enable</Nullable> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <EnableDefaultItems>true</EnableDefaultItems> <!-- Use targeting pack references instead of granular ones in the project file. --> <DisableImplicitAssemblyReferences>false</DisableImplicitAssemblyReferences> <IsPackable>true</IsPackable> <PackageDescription>JSON configuration provider implementation for Microsoft.Extensions.Configuration.</PackageDescription> </PropertyGroup> <ItemGroup> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Configuration\src\Microsoft.Extensions.Configuration.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Configuration.Abstractions\src\Microsoft.Extensions.Configuration.Abstractions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Configuration.FileExtensions\src\Microsoft.Extensions.Configuration.FileExtensions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.FileProviders.Abstractions\src\Microsoft.Extensions.FileProviders.Abstractions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)System.Text.Json\src\System.Text.Json.csproj" /> </ItemGroup> <ItemGroup Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'netstandard2.1'))"> <PackageReference Include="System.Memory" Version="$(SystemMemoryVersion)" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.1;netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <Nullable>enable</Nullable> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <EnableDefaultItems>true</EnableDefaultItems> <!-- Use targeting pack references instead of granular ones in the project file. --> <DisableImplicitAssemblyReferences>false</DisableImplicitAssemblyReferences> <IsPackable>true</IsPackable> <PackageDescription>JSON configuration provider implementation for Microsoft.Extensions.Configuration.</PackageDescription> </PropertyGroup> <ItemGroup> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Configuration\src\Microsoft.Extensions.Configuration.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Configuration.Abstractions\src\Microsoft.Extensions.Configuration.Abstractions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Configuration.FileExtensions\src\Microsoft.Extensions.Configuration.FileExtensions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.FileProviders.Abstractions\src\Microsoft.Extensions.FileProviders.Abstractions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)System.Text.Json\src\System.Text.Json.csproj" /> </ItemGroup> <ItemGroup Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'netstandard2.1'))"> <PackageReference Include="System.Memory" Version="$(SystemMemoryVersion)" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/InsertSelectedScalar.Vector128.Double.1.Vector128.Double.1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1() { var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray3, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1 testClass) { var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1 testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Double*)pFld1), 1, AdvSimd.LoadVector128((Double*)pFld2), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly byte ElementIndex1 = 1; private static readonly byte ElementIndex2 = 1; private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data3 = new Double[Op3ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar3; private Vector128<Double> _fld1; private Vector128<Double> _fld3; private DataTable _dataTable; static InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data3, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.InsertSelectedScalar( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), 1, Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), 1, AdvSimd.LoadVector128((Double*)(_dataTable.inArray3Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector128<Double>), typeof(byte), typeof(Vector128<Double>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), ElementIndex1, Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector128<Double>), typeof(byte), typeof(Vector128<Double>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), ElementIndex1, AdvSimd.LoadVector128((Double*)(_dataTable.inArray3Ptr)), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar( _clsVar1, 1, _clsVar3, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar3 = &_clsVar3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Double*)(pClsVar1)), 1, AdvSimd.LoadVector128((Double*)(pClsVar3)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op3 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op3 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray3Ptr)); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Double*)pFld1), 1, AdvSimd.LoadVector128((Double*)pFld2), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Double*)pFld1), 1, AdvSimd.LoadVector128((Double*)pFld2), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Double*)(&test._fld1)), 1, AdvSimd.LoadVector128((Double*)(&test._fld3)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op3, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray3 = new Double[Op3ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op3, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray3 = new Double[Op3ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Helpers.Insert(firstOp, ElementIndex1, thirdOp[ElementIndex2], i)) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.InsertSelectedScalar)}<Double>(Vector128<Double>, {1}, Vector128<Double>, {1}): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1() { var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray3, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1 testClass) { var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1 testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Double*)pFld1), 1, AdvSimd.LoadVector128((Double*)pFld2), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly byte ElementIndex1 = 1; private static readonly byte ElementIndex2 = 1; private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data3 = new Double[Op3ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar3; private Vector128<Double> _fld1; private Vector128<Double> _fld3; private DataTable _dataTable; static InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data3, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.InsertSelectedScalar( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), 1, Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), 1, AdvSimd.LoadVector128((Double*)(_dataTable.inArray3Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector128<Double>), typeof(byte), typeof(Vector128<Double>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), ElementIndex1, Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector128<Double>), typeof(byte), typeof(Vector128<Double>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), ElementIndex1, AdvSimd.LoadVector128((Double*)(_dataTable.inArray3Ptr)), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar( _clsVar1, 1, _clsVar3, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar3 = &_clsVar3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Double*)(pClsVar1)), 1, AdvSimd.LoadVector128((Double*)(pClsVar3)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op3 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op3 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray3Ptr)); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Double_1_Vector128_Double_1(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Double*)pFld1), 1, AdvSimd.LoadVector128((Double*)pFld2), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Double*)pFld1), 1, AdvSimd.LoadVector128((Double*)pFld2), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Double*)(&test._fld1)), 1, AdvSimd.LoadVector128((Double*)(&test._fld3)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op3, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray3 = new Double[Op3ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op3, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray3 = new Double[Op3ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Helpers.Insert(firstOp, ElementIndex1, thirdOp[ElementIndex2], i)) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.InsertSelectedScalar)}<Double>(Vector128<Double>, {1}, Vector128<Double>, {1}): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Collections.NonGeneric/src/System/Collections/DictionaryBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================ ** ** Class: DictionaryBase ** ** Purpose: Provides the abstract base class for a ** strongly typed collection of key/value pairs. ** ===========================================================*/ namespace System.Collections { // Useful base class for typed read/write collections where items derive from object public abstract class DictionaryBase : IDictionary { private Hashtable? _hashtable; protected Hashtable InnerHashtable { get { if (_hashtable == null) _hashtable = new Hashtable(); return _hashtable; } } protected IDictionary Dictionary { get { return (IDictionary)this; } } public int Count { // to avoid newing inner list if no items are ever added get { return _hashtable == null ? 0 : _hashtable.Count; } } bool IDictionary.IsReadOnly { get { return InnerHashtable.IsReadOnly; } } bool IDictionary.IsFixedSize { get { return InnerHashtable.IsFixedSize; } } bool ICollection.IsSynchronized { get { return InnerHashtable.IsSynchronized; } } ICollection IDictionary.Keys { get { return InnerHashtable.Keys; } } object ICollection.SyncRoot { get { return InnerHashtable.SyncRoot; } } ICollection IDictionary.Values { get { return InnerHashtable.Values; } } public void CopyTo(Array array, int index) { InnerHashtable.CopyTo(array, index); } object? IDictionary.this[object key] { get { object? currentValue = InnerHashtable[key]; OnGet(key, currentValue); return currentValue; } set { OnValidate(key, value); bool keyExists = true; object? temp = InnerHashtable[key]; if (temp == null) { keyExists = InnerHashtable.Contains(key); } OnSet(key, temp, value); InnerHashtable[key] = value; try { OnSetComplete(key, temp, value); } catch { if (keyExists) { InnerHashtable[key] = temp; } else { InnerHashtable.Remove(key); } throw; } } } bool IDictionary.Contains(object key) { return InnerHashtable.Contains(key); } void IDictionary.Add(object key, object? value) { OnValidate(key, value); OnInsert(key, value); InnerHashtable.Add(key, value); try { OnInsertComplete(key, value); } catch { InnerHashtable.Remove(key); throw; } } public void Clear() { OnClear(); InnerHashtable.Clear(); OnClearComplete(); } void IDictionary.Remove(object key) { if (InnerHashtable.Contains(key)) { object? temp = InnerHashtable[key]; OnValidate(key, temp); OnRemove(key, temp); InnerHashtable.Remove(key); try { OnRemoveComplete(key, temp); } catch { InnerHashtable.Add(key, temp); throw; } } } public IDictionaryEnumerator GetEnumerator() { return InnerHashtable.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return InnerHashtable.GetEnumerator(); } protected virtual object? OnGet(object key, object? currentValue) { return currentValue; } protected virtual void OnSet(object key, object? oldValue, object? newValue) { } protected virtual void OnInsert(object key, object? value) { } protected virtual void OnClear() { } protected virtual void OnRemove(object key, object? value) { } protected virtual void OnValidate(object key, object? value) { } protected virtual void OnSetComplete(object key, object? oldValue, object? newValue) { } protected virtual void OnInsertComplete(object key, object? value) { } protected virtual void OnClearComplete() { } protected virtual void OnRemoveComplete(object key, object? value) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================ ** ** Class: DictionaryBase ** ** Purpose: Provides the abstract base class for a ** strongly typed collection of key/value pairs. ** ===========================================================*/ namespace System.Collections { // Useful base class for typed read/write collections where items derive from object public abstract class DictionaryBase : IDictionary { private Hashtable? _hashtable; protected Hashtable InnerHashtable { get { if (_hashtable == null) _hashtable = new Hashtable(); return _hashtable; } } protected IDictionary Dictionary { get { return (IDictionary)this; } } public int Count { // to avoid newing inner list if no items are ever added get { return _hashtable == null ? 0 : _hashtable.Count; } } bool IDictionary.IsReadOnly { get { return InnerHashtable.IsReadOnly; } } bool IDictionary.IsFixedSize { get { return InnerHashtable.IsFixedSize; } } bool ICollection.IsSynchronized { get { return InnerHashtable.IsSynchronized; } } ICollection IDictionary.Keys { get { return InnerHashtable.Keys; } } object ICollection.SyncRoot { get { return InnerHashtable.SyncRoot; } } ICollection IDictionary.Values { get { return InnerHashtable.Values; } } public void CopyTo(Array array, int index) { InnerHashtable.CopyTo(array, index); } object? IDictionary.this[object key] { get { object? currentValue = InnerHashtable[key]; OnGet(key, currentValue); return currentValue; } set { OnValidate(key, value); bool keyExists = true; object? temp = InnerHashtable[key]; if (temp == null) { keyExists = InnerHashtable.Contains(key); } OnSet(key, temp, value); InnerHashtable[key] = value; try { OnSetComplete(key, temp, value); } catch { if (keyExists) { InnerHashtable[key] = temp; } else { InnerHashtable.Remove(key); } throw; } } } bool IDictionary.Contains(object key) { return InnerHashtable.Contains(key); } void IDictionary.Add(object key, object? value) { OnValidate(key, value); OnInsert(key, value); InnerHashtable.Add(key, value); try { OnInsertComplete(key, value); } catch { InnerHashtable.Remove(key); throw; } } public void Clear() { OnClear(); InnerHashtable.Clear(); OnClearComplete(); } void IDictionary.Remove(object key) { if (InnerHashtable.Contains(key)) { object? temp = InnerHashtable[key]; OnValidate(key, temp); OnRemove(key, temp); InnerHashtable.Remove(key); try { OnRemoveComplete(key, temp); } catch { InnerHashtable.Add(key, temp); throw; } } } public IDictionaryEnumerator GetEnumerator() { return InnerHashtable.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return InnerHashtable.GetEnumerator(); } protected virtual object? OnGet(object key, object? currentValue) { return currentValue; } protected virtual void OnSet(object key, object? oldValue, object? newValue) { } protected virtual void OnInsert(object key, object? value) { } protected virtual void OnClear() { } protected virtual void OnRemove(object key, object? value) { } protected virtual void OnValidate(object key, object? value) { } protected virtual void OnSetComplete(object key, object? oldValue, object? newValue) { } protected virtual void OnInsertComplete(object key, object? value) { } protected virtual void OnClearComplete() { } protected virtual void OnRemoveComplete(object key, object? value) { } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/AtomFeeds/id-valid-tag-uris.xml
<!-- Description: Valid Tag URIs, according to RFC 4151, should not produce errors Expect: !InvalidTAG --> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://contoso.com/"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>Author Name</name> </author> <id>tag:contoso.com,2000:</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href="http://contoso.com/1"/> <id>tag:contoso.com,2000:#anchor</id> <updated>2005-12-18T13:32:18Z</updated> </entry> <entry> <title>Atom-Powered Robots Test Empty Fragments</title> <link href="http://contoso.com/2"/> <id>tag:contoso.com,2000:#</id> <updated>2005-12-18T13:32:33Z</updated> </entry> </feed>
<!-- Description: Valid Tag URIs, according to RFC 4151, should not produce errors Expect: !InvalidTAG --> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://contoso.com/"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>Author Name</name> </author> <id>tag:contoso.com,2000:</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href="http://contoso.com/1"/> <id>tag:contoso.com,2000:#anchor</id> <updated>2005-12-18T13:32:18Z</updated> </entry> <entry> <title>Atom-Powered Robots Test Empty Fragments</title> <link href="http://contoso.com/2"/> <id>tag:contoso.com,2000:#</id> <updated>2005-12-18T13:32:33Z</updated> </entry> </feed>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/Math/Functions/Single/Cbrt.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace System.MathBenchmarks { public partial class Single { // Tests MathF.Cbrt(float) over 5000 iterations for the domain +0, +PI private const float cbrtDelta = 0.000628318531f; private const float cbrtExpectedResult = 5491.4541f; public void Cbrt() => CbrtTest(); public static void CbrtTest() { float result = 0.0f, value = 0.0f; for (int iteration = 0; iteration < MathTests.Iterations; iteration++) { result += MathF.Cbrt(value); value += cbrtDelta; } float diff = MathF.Abs(cbrtExpectedResult - result); if (float.IsNaN(result) || (diff > MathTests.SingleEpsilon)) { throw new Exception($"Expected Result {cbrtExpectedResult,10:g9}; Actual Result {result,10:g9}"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace System.MathBenchmarks { public partial class Single { // Tests MathF.Cbrt(float) over 5000 iterations for the domain +0, +PI private const float cbrtDelta = 0.000628318531f; private const float cbrtExpectedResult = 5491.4541f; public void Cbrt() => CbrtTest(); public static void CbrtTest() { float result = 0.0f, value = 0.0f; for (int iteration = 0; iteration < MathTests.Iterations; iteration++) { result += MathF.Cbrt(value); value += cbrtDelta; } float diff = MathF.Abs(cbrtExpectedResult - result); if (float.IsNaN(result) || (diff > MathTests.SingleEpsilon)) { throw new Exception($"Expected Result {cbrtExpectedResult,10:g9}; Actual Result {result,10:g9}"); } } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyBySelectedScalar.Vector64.UInt32.Vector128.UInt32.3.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3() { var test = new ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<UInt32> _fld1; public Vector128<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3 testClass) { var result = AdvSimd.MultiplyBySelectedScalar(_fld1, _fld2, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3 testClass) { fixed (Vector64<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = AdvSimd.MultiplyBySelectedScalar( AdvSimd.LoadVector64((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)), 3 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static readonly byte Imm = 3; private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector64<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector64<UInt32> _fld1; private Vector128<UInt32> _fld2; private DataTable _dataTable; static ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyBySelectedScalar( Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyBySelectedScalar( AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalar), new Type[] { typeof(Vector64<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalar), new Type[] { typeof(Vector64<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyBySelectedScalar( _clsVar1, _clsVar2, 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.MultiplyBySelectedScalar( AdvSimd.LoadVector64((UInt32*)(pClsVar1)), AdvSimd.LoadVector128((UInt32*)(pClsVar2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var result = AdvSimd.MultiplyBySelectedScalar(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.MultiplyBySelectedScalar(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3(); var result = AdvSimd.MultiplyBySelectedScalar(test._fld1, test._fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3(); fixed (Vector64<UInt32>* pFld1 = &test._fld1) fixed (Vector128<UInt32>* pFld2 = &test._fld2) { var result = AdvSimd.MultiplyBySelectedScalar( AdvSimd.LoadVector64((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyBySelectedScalar(_fld1, _fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = AdvSimd.MultiplyBySelectedScalar( AdvSimd.LoadVector64((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalar(test._fld1, test._fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalar( AdvSimd.LoadVector64((UInt32*)(&test._fld1)), AdvSimd.LoadVector128((UInt32*)(&test._fld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<UInt32> firstOp, Vector128<UInt32> secondOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), secondOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] secondOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Multiply(firstOp[i], secondOp[Imm]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyBySelectedScalar)}<UInt32>(Vector64<UInt32>, Vector128<UInt32>, 3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3() { var test = new ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<UInt32> _fld1; public Vector128<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3 testClass) { var result = AdvSimd.MultiplyBySelectedScalar(_fld1, _fld2, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3 testClass) { fixed (Vector64<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = AdvSimd.MultiplyBySelectedScalar( AdvSimd.LoadVector64((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)), 3 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static readonly byte Imm = 3; private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector64<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector64<UInt32> _fld1; private Vector128<UInt32> _fld2; private DataTable _dataTable; static ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyBySelectedScalar( Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyBySelectedScalar( AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalar), new Type[] { typeof(Vector64<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalar), new Type[] { typeof(Vector64<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyBySelectedScalar( _clsVar1, _clsVar2, 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.MultiplyBySelectedScalar( AdvSimd.LoadVector64((UInt32*)(pClsVar1)), AdvSimd.LoadVector128((UInt32*)(pClsVar2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var result = AdvSimd.MultiplyBySelectedScalar(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.MultiplyBySelectedScalar(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3(); var result = AdvSimd.MultiplyBySelectedScalar(test._fld1, test._fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmBinaryOpTest__MultiplyBySelectedScalar_Vector64_UInt32_Vector128_UInt32_3(); fixed (Vector64<UInt32>* pFld1 = &test._fld1) fixed (Vector128<UInt32>* pFld2 = &test._fld2) { var result = AdvSimd.MultiplyBySelectedScalar( AdvSimd.LoadVector64((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyBySelectedScalar(_fld1, _fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = AdvSimd.MultiplyBySelectedScalar( AdvSimd.LoadVector64((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalar(test._fld1, test._fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalar( AdvSimd.LoadVector64((UInt32*)(&test._fld1)), AdvSimd.LoadVector128((UInt32*)(&test._fld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<UInt32> firstOp, Vector128<UInt32> secondOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), secondOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] secondOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Multiply(firstOp[i], secondOp[Imm]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyBySelectedScalar)}<UInt32>(Vector64<UInt32>, Vector128<UInt32>, 3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/mono/wasm/wasm.proj
<Project Sdk="Microsoft.Build.NoTargets"> <UsingTask TaskName="Microsoft.WebAssembly.Build.Tasks.RunWithEmSdkEnv" AssemblyFile="$(WasmAppBuilderTasksAssemblyPath)" /> <PropertyGroup> <!-- FIXME: clean up the duplication with libraries Directory.Build.props --> <PackageRID>browser-wasm</PackageRID> <NativeBinDir>$([MSBuild]::NormalizeDirectory('$(ArtifactsBinDir)', 'native', '$(NetCoreAppCurrent)-$(TargetOS)-$(Configuration)-$(TargetArchitecture)'))</NativeBinDir> <ICULibDir>$([MSBuild]::NormalizeDirectory('$(PkgMicrosoft_NETCore_Runtime_ICU_Transport)', 'runtimes', 'browser-wasm', 'native', 'lib'))</ICULibDir> <WasmEnableES6 Condition="'$(WasmEnableES6)' == ''">false</WasmEnableES6> <FilterSystemTimeZones Condition="'$(FilterSystemTimeZones)' == ''">false</FilterSystemTimeZones> <EmccCmd>emcc</EmccCmd> <WasmObjDir>$(ArtifactsObjDir)wasm</WasmObjDir> <_EmccDefaultsRspPath>$(NativeBinDir)src\emcc-default.rsp</_EmccDefaultsRspPath> <_EmccCompileRspPath>$(NativeBinDir)src\emcc-compile.rsp</_EmccCompileRspPath> <_EmccLinkRspPath>$(NativeBinDir)src\emcc-link.rsp</_EmccLinkRspPath> <WasmNativeStrip Condition="'$(ContinuousIntegrationBuild)' == 'true'">false</WasmNativeStrip> </PropertyGroup> <Target Name="CheckEnv"> <Error Condition="'$(TargetArchitecture)' != 'wasm'" Text="Expected TargetArchitecture==wasm, got '$(TargetArchitecture)'"/> <Error Condition="'$(TargetOS)' != 'Browser'" Text="Expected TargetOS==Browser, got '$(TargetOS)'"/> <Error Condition="'$(EMSDK_PATH)' == ''" Text="The EMSDK_PATH environment variable should be set pointing to the emscripten SDK root dir."/> </Target> <ItemGroup> <PackageReference Include="Microsoft.NETCore.Runtime.ICU.Transport" PrivateAssets="all" Version="$(MicrosoftNETCoreRuntimeICUTransportVersion)" GeneratePathProperty="true" /> <PackageReference Include="System.Runtime.TimeZoneData" PrivateAssets="all" Version="$(SystemRuntimeTimeZoneDataVersion)" GeneratePathProperty="true" /> </ItemGroup> <UsingTask TaskName="PInvokeTableGenerator" AssemblyFile="$(WasmAppBuilderTasksAssemblyPath)"/> <Target Name="BuildPInvokeTable" DependsOnTargets="CheckEnv;ResolveLibrariesFromLocalBuild"> <PropertyGroup> <WasmPInvokeTablePath>$(ArtifactsObjDir)wasm\pinvoke-table.h</WasmPInvokeTablePath> </PropertyGroup> <ItemGroup> <WasmPInvokeModule Include="libSystem.Native" /> <WasmPInvokeModule Include="libSystem.IO.Compression.Native" /> <WasmPInvokeModule Include="libSystem.Globalization.Native" /> <WasmPInvokeAssembly Include="@(LibrariesRuntimeFiles)" Condition="'%(Extension)' == '.dll' and '%(IsNative)' != 'true'" /> </ItemGroup> <!-- Retrieve CoreLib's targetpath via GetTargetPath as it isn't binplaced yet. --> <MSBuild Projects="$(CoreLibProject)" Targets="GetTargetPath"> <Output TaskParameter="TargetOutputs" ItemName="WasmPInvokeAssembly" /> </MSBuild> <MakeDir Directories="$(ArtifactsObjDir)wasm" /> <PInvokeTableGenerator Modules="@(WasmPInvokeModule)" Assemblies="@(WasmPInvokeAssembly)" OutputPath="$(WasmPInvokeTablePath)" /> </Target> <UsingTask TaskName="GenerateWasmBundle" AssemblyFile="$(WasmBuildTasksAssemblyPath)"/> <Target Name="BundleTimeZones"> <PropertyGroup> <TimeZonesDataPath>$(NativeBinDir)dotnet.timezones.blat</TimeZonesDataPath> </PropertyGroup> <GenerateWasmBundle InputDirectory="$([MSBuild]::NormalizePath('$(PkgSystem_Runtime_TimeZoneData)', 'contentFiles', 'any', 'any', 'data'))" OutputFileName="$(TimeZonesDataPath)" /> </Target> <Target Name="GenerateEmccPropsAndRspFiles"> <!-- Generate emcc-props.json --> <RunWithEmSdkEnv Command="$(EmccCmd) --version" ConsoleToMsBuild="true" EmSdkPath="$(EMSDK_PATH)" IgnoreStandardErrorWarningFormat="true"> <Output TaskParameter="ConsoleOutput" ItemName="_VersionLines" /> </RunWithEmSdkEnv> <!-- we want to get the first line from the output, which has the version. Rest of the lines are the license --> <ItemGroup> <_ReversedVersionLines Include="@(_VersionLines->Reverse())" /> </ItemGroup> <PropertyGroup> <_EmccVersionRaw>%(_ReversedVersionLines.Identity)</_EmccVersionRaw> <_EmccVersionRegexPattern>^ *emcc \([^\)]+\) *([0-9\.]+).*\(([^\)]+)\)$</_EmccVersionRegexPattern> <_EmccVersion>$([System.Text.RegularExpressions.Regex]::Match($(_EmccVersionRaw), $(_EmccVersionRegexPattern)).Groups[1].Value)</_EmccVersion> <_EmccVersionHash>$([System.Text.RegularExpressions.Regex]::Match($(_EmccVersionRaw), $(_EmccVersionRegexPattern)).Groups[2].Value)</_EmccVersionHash> </PropertyGroup> <Error Text="Failed to parse emcc version, and hash from the full version string: '$(_EmccVersionRaw)'" Condition="'$(_EmccVersion)' == '' or '$(_EmccVersionHash)' == ''" /> <PropertyGroup> <_EmccPropsJson> <![CDATA[ { "items": { "EmccProperties": [ { "identity": "RuntimeEmccVersion", "value": "$(_EmccVersion)" }, { "identity": "RuntimeEmccVersionRaw", "value": "$(_EmccVersionRaw)" }, { "identity": "RuntimeEmccVersionHash", "value": "$(_EmccVersionHash)" } ] } } ]]> </_EmccPropsJson> </PropertyGroup> <WriteLinesToFile File="$(NativeBinDir)src\emcc-props.json" Lines="$(_EmccPropsJson)" Overwrite="true" WriteOnlyWhenDifferent="true" /> <ItemGroup> <_EmccLinkFlags Include="-s EXPORT_ES6=1" Condition="'$(WasmEnableES6)' == 'true'" /> <_EmccLinkFlags Include="-s ALLOW_MEMORY_GROWTH=1" /> <_EmccLinkFlags Include="-s NO_EXIT_RUNTIME=1" /> <_EmccLinkFlags Include="-s FORCE_FILESYSTEM=1" /> <_EmccLinkFlags Include="-s EXPORTED_RUNTIME_METHODS=&quot;['FS','print','ccall','cwrap','setValue','getValue','UTF8ToString','UTF8ArrayToString','FS_createPath','FS_createDataFile','removeRunDependency','addRunDependency', 'FS_readFile']&quot;" /> <!-- _htons,_ntohs,__get_daylight,__get_timezone,__get_tzname are exported temporarily, until the issue is fixed in emscripten, https://github.com/dotnet/runtime/issues/64724 --> <_EmccLinkFlags Include="-s EXPORTED_FUNCTIONS=_free,_malloc,_memalign,_memset" Condition="$([MSBuild]::VersionGreaterThan('$(_EmccVersion)', '3.0'))" /> <_EmccLinkFlags Include="-s EXPORTED_FUNCTIONS=_free,_malloc,_htons,_ntohs,__get_daylight,__get_timezone,__get_tzname,_memalign" Condition="$([MSBuild]::VersionLessThan('$(_EmccVersion)', '3.0'))" /> <_EmccLinkFlags Include="--source-map-base http://example.com" /> <_EmccLinkFlags Include="-s STRICT_JS=1" /> <_EmccLinkFlags Include="-s EXPORT_NAME=&quot;'createDotnetRuntime'&quot;" /> <_EmccLinkFlags Include="-s MODULARIZE=1"/> <_EmccLinkFlags Include="-Wl,--allow-undefined"/> <_EmccLinkFlags Include="-s ENVIRONMENT=&quot;web,webview,worker,node,shell&quot;" /> </ItemGroup> <ItemGroup Condition="'$(OS)' != 'Windows_NT'"> <_EmccLinkFlags Include="--profiling-funcs" /> <_EmccFlags Include="@(_EmccCommonFlags)" /> </ItemGroup> <ItemGroup Condition="'$(OS)' == 'Windows_NT'"> <_EmccFlags Include="@(_EmccCommonFlags)" /> </ItemGroup> <WriteLinesToFile File="$(_EmccDefaultsRspPath)" Lines="@(_EmccFlags)" WriteOnlyWhenDifferent="true" Overwrite="true" /> <WriteLinesToFile File="$(_EmccCompileRspPath)" Lines="@(_EmccCompileFlags)" WriteOnlyWhenDifferent="true" Overwrite="true" /> <WriteLinesToFile File="$(_EmccLinkRspPath)" Lines="@(_EmccLinkFlags)" WriteOnlyWhenDifferent="true" Overwrite="true" /> </Target> <!-- This is a documented target that is invoked by developers in their innerloop work. --> <Target Name="BuildWasmRuntimes" AfterTargets="Build" DependsOnTargets="GenerateEmccPropsAndRspFiles;BuildPInvokeTable;BundleTimeZones;InstallNpmPackages;BuildWithRollup"> <ItemGroup> <ICULibNativeFiles Include="$(ICULibDir)/libicuuc.a; $(ICULibDir)/libicui18n.a" /> <ICULibFiles Include="$(ICULibDir)/*.dat" /> </ItemGroup> <PropertyGroup> <PInvokeTableFile>$(ArtifactsObjDir)wasm/pinvoke-table.h</PInvokeTableFile> <CMakeConfigurationEmccFlags Condition="'$(Configuration)' == 'Debug'">-g -Os -s -DDEBUG=1 -DENABLE_AOT_PROFILER=1</CMakeConfigurationEmccFlags> <CMakeConfigurationEmccFlags Condition="'$(Configuration)' == 'Release'">-Oz</CMakeConfigurationEmccFlags> <CMakeConfigurationLinkFlags Condition="'$(Configuration)' == 'Debug'" >$(CMakeConfigurationEmccFlags)</CMakeConfigurationLinkFlags> <CMakeConfigurationLinkFlags Condition="'$(Configuration)' == 'Release'">-O2</CMakeConfigurationLinkFlags> <CMakeConfigurationLinkFlags >$(CMakeConfigurationLinkFlags) --emit-symbol-map</CMakeConfigurationLinkFlags> <CMakeConfigurationEmsdkPath Condition="'$(Configuration)' == 'Release'"> -DEMSDK_PATH=&quot;$(EMSDK_PATH.TrimEnd('\/'))&quot;</CMakeConfigurationEmsdkPath> <CMakeBuildRuntimeConfigureCmd>emcmake cmake $(MSBuildThisFileDirectory)runtime</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DCMAKE_BUILD_TYPE=$(Configuration)</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DCONFIGURATION_EMCC_FLAGS=&quot;$(CMakeConfigurationEmccFlags)&quot;</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DCONFIGURATION_LINK_FLAGS=&quot;$(CMakeConfigurationLinkFlags)&quot;</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DMONO_INCLUDES=&quot;$(MonoArtifactsPath)include/mono-2.0&quot;</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DMONO_OBJ_INCLUDES=&quot;$(MonoObjDir.TrimEnd('\/'))&quot;</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DICU_LIB_DIR=&quot;$(ICULibDir.TrimEnd('\/'))&quot;</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DMONO_ARTIFACTS_DIR=&quot;$(MonoArtifactsPath.TrimEnd('\/'))&quot;</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DNATIVE_BIN_DIR=&quot;$(NativeBinDir.TrimEnd('\/'))&quot;</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) $(CMakeConfigurationEmsdkPath)</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd Condition="'$(OS)' == 'Windows_NT'">call &quot;$(RepositoryEngineeringDir)native\init-vs-env.cmd&quot; &amp;&amp; call &quot;$([MSBuild]::NormalizePath('$(EMSDK_PATH)', 'emsdk_env.bat'))&quot; &amp;&amp; $(CMakeBuildRuntimeConfigureCmd)</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd Condition="'$(OS)' != 'Windows_NT'">bash -c 'source $(EMSDK_PATH)/emsdk_env.sh 2>&amp;1 &amp;&amp; $(CMakeBuildRuntimeConfigureCmd)'</CMakeBuildRuntimeConfigureCmd> <CMakeOptions Condition="'$(MonoVerboseBuild)' != ''">-v</CMakeOptions> <CMakeBuildRuntimeCmd>cmake --build . --config $(Configuration) $(CmakeOptions)</CMakeBuildRuntimeCmd> <CMakeBuildRuntimeCmd Condition="'$(OS)' == 'Windows_NT'">call &quot;$(RepositoryEngineeringDir)native\init-vs-env.cmd&quot; &amp;&amp; call &quot;$([MSBuild]::NormalizePath('$(EMSDK_PATH)', 'emsdk_env.bat'))&quot; &amp;&amp; $(CMakeBuildRuntimeCmd)</CMakeBuildRuntimeCmd> <CMakeBuildRuntimeCmd Condition="'$(OS)' != 'Windows_NT'">bash -c 'source $(EMSDK_PATH)/emsdk_env.sh 2>&amp;1 &amp;&amp; $(CMakeBuildRuntimeCmd)'</CMakeBuildRuntimeCmd> </PropertyGroup> <Copy SourceFiles="$(PInvokeTableFile)" DestinationFolder="$(MonoObjDir)" SkipUnchangedFiles="true" /> <Copy SourceFiles="runtime/driver.c; runtime/pinvoke.c; runtime/corebindings.c; $(SharedNativeRoot)libs\System.Native\pal_random.lib.js;" DestinationFolder="$(NativeBinDir)src" SkipUnchangedFiles="true" /> <Copy SourceFiles="runtime/cjs/dotnet.cjs.pre.js; runtime/cjs/dotnet.cjs.lib.js; runtime/cjs/dotnet.cjs.post.js; runtime/cjs/dotnet.cjs.extpost.js;" DestinationFolder="$(NativeBinDir)src/cjs" SkipUnchangedFiles="true" /> <Copy SourceFiles="runtime/es6/dotnet.es6.pre.js; runtime/es6/dotnet.es6.lib.js; runtime/es6/dotnet.es6.post.js;" DestinationFolder="$(NativeBinDir)src/es6" SkipUnchangedFiles="true" /> <Copy SourceFiles="runtime\pinvoke.h" DestinationFolder="$(NativeBinDir)include\wasm" SkipUnchangedFiles="true" /> <Copy SourceFiles="@(ICULibFiles); @(ICULibNativeFiles);" DestinationFolder="$(NativeBinDir)" SkipUnchangedFiles="true" /> <Exec Command="$(CMakeBuildRuntimeConfigureCmd)" WorkingDirectory="$(NativeBinDir)" /> <Exec Command="$(CMakeBuildRuntimeCmd)" WorkingDirectory="$(NativeBinDir)" /> <ItemGroup> <IcuDataFiles Include="$(NativeBinDir)*.dat" /> <WasmSrcFiles Include="$(NativeBinDir)src\*.c; $(NativeBinDir)src\*.js; $(_EmccDefaultsRspPath); $(_EmccCompileRspPath); $(_EmccLinkRspPath); $(NativeBinDir)src\emcc-props.json" /> <WasmSrcFilesCjs Include="$(NativeBinDir)src\cjs\*.js;" /> <WasmSrcFilesEs6 Include="$(NativeBinDir)src\es6\*.js;" /> <WasmHeaderFiles Include="$(NativeBinDir)include\wasm\*.h" /> </ItemGroup> <Copy SourceFiles="$(NativeBinDir)dotnet.js; $(NativeBinDir)dotnet.d.ts; $(NativeBinDir)package.json; $(NativeBinDir)dotnet.wasm; $(NativeBinDir)dotnet.timezones.blat" DestinationFolder="$(MicrosoftNetCoreAppRuntimePackNativeDir)" SkipUnchangedFiles="true" /> <Copy SourceFiles="$(NativeBinDir)dotnet.js.symbols" DestinationFolder="$(MicrosoftNetCoreAppRuntimePackNativeDir)" SkipUnchangedFiles="true" /> <Copy SourceFiles="@(IcuDataFiles);@(ICULibNativeFiles)" DestinationFolder="$(MicrosoftNetCoreAppRuntimePackNativeDir)" SkipUnchangedFiles="true" /> <Copy SourceFiles="@(WasmSrcFiles)" DestinationFolder="$(MicrosoftNetCoreAppRuntimePackNativeDir)src" SkipUnchangedFiles="true" /> <Copy SourceFiles="@(WasmSrcFilesCjs)" DestinationFolder="$(MicrosoftNetCoreAppRuntimePackNativeDir)src\cjs" SkipUnchangedFiles="true" /> <Copy SourceFiles="@(WasmSrcFilesEs6)" DestinationFolder="$(MicrosoftNetCoreAppRuntimePackNativeDir)src\es6" SkipUnchangedFiles="true" /> <Copy SourceFiles="@(WasmHeaderFiles)" DestinationFolder="$(MicrosoftNetCoreAppRuntimePackNativeDir)include\wasm" SkipUnchangedFiles="true" /> </Target> <Target Name="InstallNpmPackages" Inputs="$(MonoProjectRoot)wasm/runtime/package.json" Outputs="$(MonoProjectRoot)wasm/runtime/node_modules/.npm-stamp" > <!-- install typescript and rollup --> <RunWithEmSdkEnv Condition="'$(ContinuousIntegrationBuild)' == 'true'" Command="npm ci" EmSdkPath="$(EMSDK_PATH)" IgnoreStandardErrorWarningFormat="true" WorkingDirectory="$(MonoProjectRoot)wasm/runtime/"/> <RunWithEmSdkEnv Condition="'$(ContinuousIntegrationBuild)' == 'true'" Command="npm audit" EmSdkPath="$(EMSDK_PATH)" IgnoreStandardErrorWarningFormat="true" WorkingDirectory="$(MonoProjectRoot)wasm/runtime/"/> <!-- npm install is faster on dev machine as it doesn't wipe node_modules folder --> <RunWithEmSdkEnv Condition="'$(ContinuousIntegrationBuild)' != 'true'" Command="npm install" EmSdkPath="$(EMSDK_PATH)" IgnoreStandardErrorWarningFormat="true" WorkingDirectory="$(MonoProjectRoot)wasm/runtime/"/> <Touch Files="$(MonoProjectRoot)wasm/runtime/node_modules/.npm-stamp" AlwaysCreate="true" /> </Target> <ItemGroup> <_RollupInputs Include="$(MonoProjectRoot)wasm/runtime/*.ts"/> <_RollupInputs Include="$(MonoProjectRoot)wasm/runtime/types/*.ts"/> <_RollupInputs Include="$(MonoProjectRoot)wasm/runtimetypes/*.d.ts"/> <_RollupInputs Include="$(MonoProjectRoot)wasm/runtime/*.json"/> <_RollupInputs Include="$(MonoProjectRoot)wasm/runtime/*.js"/> </ItemGroup> <Target Name="BuildWithRollup" Inputs="@(_RollupInputs)" Outputs="$(NativeBinDir).rollup-stamp" > <!-- code style check --> <RunWithEmSdkEnv Command="npm run lint" StandardOutputImportance="High" EmSdkPath="$(EMSDK_PATH)" WorkingDirectory="$(MonoProjectRoot)wasm/runtime/"/> <!-- compile typescript --> <RunWithEmSdkEnv Command="npm run rollup -- --environment Configuration:$(Configuration),NativeBinDir:$(NativeBinDir),ProductVersion:$(ProductVersion)" EmSdkPath="$(EMSDK_PATH)" IgnoreStandardErrorWarningFormat="true" WorkingDirectory="$(MonoProjectRoot)wasm/runtime/"/> <Copy SourceFiles="runtime/package.json;" DestinationFolder="$(NativeBinDir)" SkipUnchangedFiles="true" /> <!-- set version --> <RunWithEmSdkEnv Command="npm version $(PackageVersion)" EmSdkPath="$(EMSDK_PATH)" WorkingDirectory="$(NativeBinDir)"/> <Touch Files="$(NativeBinDir).rollup-stamp" AlwaysCreate="true" /> </Target> </Project>
<Project Sdk="Microsoft.Build.NoTargets"> <UsingTask TaskName="Microsoft.WebAssembly.Build.Tasks.RunWithEmSdkEnv" AssemblyFile="$(WasmAppBuilderTasksAssemblyPath)" /> <PropertyGroup> <!-- FIXME: clean up the duplication with libraries Directory.Build.props --> <PackageRID>browser-wasm</PackageRID> <NativeBinDir>$([MSBuild]::NormalizeDirectory('$(ArtifactsBinDir)', 'native', '$(NetCoreAppCurrent)-$(TargetOS)-$(Configuration)-$(TargetArchitecture)'))</NativeBinDir> <ICULibDir>$([MSBuild]::NormalizeDirectory('$(PkgMicrosoft_NETCore_Runtime_ICU_Transport)', 'runtimes', 'browser-wasm', 'native', 'lib'))</ICULibDir> <WasmEnableES6 Condition="'$(WasmEnableES6)' == ''">false</WasmEnableES6> <FilterSystemTimeZones Condition="'$(FilterSystemTimeZones)' == ''">false</FilterSystemTimeZones> <EmccCmd>emcc</EmccCmd> <WasmObjDir>$(ArtifactsObjDir)wasm</WasmObjDir> <_EmccDefaultsRspPath>$(NativeBinDir)src\emcc-default.rsp</_EmccDefaultsRspPath> <_EmccCompileRspPath>$(NativeBinDir)src\emcc-compile.rsp</_EmccCompileRspPath> <_EmccLinkRspPath>$(NativeBinDir)src\emcc-link.rsp</_EmccLinkRspPath> <WasmNativeStrip Condition="'$(ContinuousIntegrationBuild)' == 'true'">false</WasmNativeStrip> </PropertyGroup> <Target Name="CheckEnv"> <Error Condition="'$(TargetArchitecture)' != 'wasm'" Text="Expected TargetArchitecture==wasm, got '$(TargetArchitecture)'"/> <Error Condition="'$(TargetOS)' != 'Browser'" Text="Expected TargetOS==Browser, got '$(TargetOS)'"/> <Error Condition="'$(EMSDK_PATH)' == ''" Text="The EMSDK_PATH environment variable should be set pointing to the emscripten SDK root dir."/> </Target> <ItemGroup> <PackageReference Include="Microsoft.NETCore.Runtime.ICU.Transport" PrivateAssets="all" Version="$(MicrosoftNETCoreRuntimeICUTransportVersion)" GeneratePathProperty="true" /> <PackageReference Include="System.Runtime.TimeZoneData" PrivateAssets="all" Version="$(SystemRuntimeTimeZoneDataVersion)" GeneratePathProperty="true" /> </ItemGroup> <UsingTask TaskName="PInvokeTableGenerator" AssemblyFile="$(WasmAppBuilderTasksAssemblyPath)"/> <Target Name="BuildPInvokeTable" DependsOnTargets="CheckEnv;ResolveLibrariesFromLocalBuild"> <PropertyGroup> <WasmPInvokeTablePath>$(ArtifactsObjDir)wasm\pinvoke-table.h</WasmPInvokeTablePath> </PropertyGroup> <ItemGroup> <WasmPInvokeModule Include="libSystem.Native" /> <WasmPInvokeModule Include="libSystem.IO.Compression.Native" /> <WasmPInvokeModule Include="libSystem.Globalization.Native" /> <WasmPInvokeAssembly Include="@(LibrariesRuntimeFiles)" Condition="'%(Extension)' == '.dll' and '%(IsNative)' != 'true'" /> </ItemGroup> <!-- Retrieve CoreLib's targetpath via GetTargetPath as it isn't binplaced yet. --> <MSBuild Projects="$(CoreLibProject)" Targets="GetTargetPath"> <Output TaskParameter="TargetOutputs" ItemName="WasmPInvokeAssembly" /> </MSBuild> <MakeDir Directories="$(ArtifactsObjDir)wasm" /> <PInvokeTableGenerator Modules="@(WasmPInvokeModule)" Assemblies="@(WasmPInvokeAssembly)" OutputPath="$(WasmPInvokeTablePath)" /> </Target> <UsingTask TaskName="GenerateWasmBundle" AssemblyFile="$(WasmBuildTasksAssemblyPath)"/> <Target Name="BundleTimeZones"> <PropertyGroup> <TimeZonesDataPath>$(NativeBinDir)dotnet.timezones.blat</TimeZonesDataPath> </PropertyGroup> <GenerateWasmBundle InputDirectory="$([MSBuild]::NormalizePath('$(PkgSystem_Runtime_TimeZoneData)', 'contentFiles', 'any', 'any', 'data'))" OutputFileName="$(TimeZonesDataPath)" /> </Target> <Target Name="GenerateEmccPropsAndRspFiles"> <!-- Generate emcc-props.json --> <RunWithEmSdkEnv Command="$(EmccCmd) --version" ConsoleToMsBuild="true" EmSdkPath="$(EMSDK_PATH)" IgnoreStandardErrorWarningFormat="true"> <Output TaskParameter="ConsoleOutput" ItemName="_VersionLines" /> </RunWithEmSdkEnv> <!-- we want to get the first line from the output, which has the version. Rest of the lines are the license --> <ItemGroup> <_ReversedVersionLines Include="@(_VersionLines->Reverse())" /> </ItemGroup> <PropertyGroup> <_EmccVersionRaw>%(_ReversedVersionLines.Identity)</_EmccVersionRaw> <_EmccVersionRegexPattern>^ *emcc \([^\)]+\) *([0-9\.]+).*\(([^\)]+)\)$</_EmccVersionRegexPattern> <_EmccVersion>$([System.Text.RegularExpressions.Regex]::Match($(_EmccVersionRaw), $(_EmccVersionRegexPattern)).Groups[1].Value)</_EmccVersion> <_EmccVersionHash>$([System.Text.RegularExpressions.Regex]::Match($(_EmccVersionRaw), $(_EmccVersionRegexPattern)).Groups[2].Value)</_EmccVersionHash> </PropertyGroup> <Error Text="Failed to parse emcc version, and hash from the full version string: '$(_EmccVersionRaw)'" Condition="'$(_EmccVersion)' == '' or '$(_EmccVersionHash)' == ''" /> <PropertyGroup> <_EmccPropsJson> <![CDATA[ { "items": { "EmccProperties": [ { "identity": "RuntimeEmccVersion", "value": "$(_EmccVersion)" }, { "identity": "RuntimeEmccVersionRaw", "value": "$(_EmccVersionRaw)" }, { "identity": "RuntimeEmccVersionHash", "value": "$(_EmccVersionHash)" } ] } } ]]> </_EmccPropsJson> </PropertyGroup> <WriteLinesToFile File="$(NativeBinDir)src\emcc-props.json" Lines="$(_EmccPropsJson)" Overwrite="true" WriteOnlyWhenDifferent="true" /> <ItemGroup> <_EmccLinkFlags Include="-s EXPORT_ES6=1" Condition="'$(WasmEnableES6)' == 'true'" /> <_EmccLinkFlags Include="-s ALLOW_MEMORY_GROWTH=1" /> <_EmccLinkFlags Include="-s NO_EXIT_RUNTIME=1" /> <_EmccLinkFlags Include="-s FORCE_FILESYSTEM=1" /> <_EmccLinkFlags Include="-s EXPORTED_RUNTIME_METHODS=&quot;['FS','print','ccall','cwrap','setValue','getValue','UTF8ToString','UTF8ArrayToString','FS_createPath','FS_createDataFile','removeRunDependency','addRunDependency', 'FS_readFile']&quot;" /> <!-- _htons,_ntohs,__get_daylight,__get_timezone,__get_tzname are exported temporarily, until the issue is fixed in emscripten, https://github.com/dotnet/runtime/issues/64724 --> <_EmccLinkFlags Include="-s EXPORTED_FUNCTIONS=_free,_malloc,_memalign,_memset" Condition="$([MSBuild]::VersionGreaterThan('$(_EmccVersion)', '3.0'))" /> <_EmccLinkFlags Include="-s EXPORTED_FUNCTIONS=_free,_malloc,_htons,_ntohs,__get_daylight,__get_timezone,__get_tzname,_memalign" Condition="$([MSBuild]::VersionLessThan('$(_EmccVersion)', '3.0'))" /> <_EmccLinkFlags Include="--source-map-base http://example.com" /> <_EmccLinkFlags Include="-s STRICT_JS=1" /> <_EmccLinkFlags Include="-s EXPORT_NAME=&quot;'createDotnetRuntime'&quot;" /> <_EmccLinkFlags Include="-s MODULARIZE=1"/> <_EmccLinkFlags Include="-Wl,--allow-undefined"/> <_EmccLinkFlags Include="-s ENVIRONMENT=&quot;web,webview,worker,node,shell&quot;" /> </ItemGroup> <ItemGroup Condition="'$(OS)' != 'Windows_NT'"> <_EmccLinkFlags Include="--profiling-funcs" /> <_EmccFlags Include="@(_EmccCommonFlags)" /> </ItemGroup> <ItemGroup Condition="'$(OS)' == 'Windows_NT'"> <_EmccFlags Include="@(_EmccCommonFlags)" /> </ItemGroup> <WriteLinesToFile File="$(_EmccDefaultsRspPath)" Lines="@(_EmccFlags)" WriteOnlyWhenDifferent="true" Overwrite="true" /> <WriteLinesToFile File="$(_EmccCompileRspPath)" Lines="@(_EmccCompileFlags)" WriteOnlyWhenDifferent="true" Overwrite="true" /> <WriteLinesToFile File="$(_EmccLinkRspPath)" Lines="@(_EmccLinkFlags)" WriteOnlyWhenDifferent="true" Overwrite="true" /> </Target> <!-- This is a documented target that is invoked by developers in their innerloop work. --> <Target Name="BuildWasmRuntimes" AfterTargets="Build" DependsOnTargets="GenerateEmccPropsAndRspFiles;BuildPInvokeTable;BundleTimeZones;InstallNpmPackages;BuildWithRollup"> <ItemGroup> <ICULibNativeFiles Include="$(ICULibDir)/libicuuc.a; $(ICULibDir)/libicui18n.a" /> <ICULibFiles Include="$(ICULibDir)/*.dat" /> </ItemGroup> <PropertyGroup> <PInvokeTableFile>$(ArtifactsObjDir)wasm/pinvoke-table.h</PInvokeTableFile> <CMakeConfigurationEmccFlags Condition="'$(Configuration)' == 'Debug'">-g -Os -s -DDEBUG=1 -DENABLE_AOT_PROFILER=1</CMakeConfigurationEmccFlags> <CMakeConfigurationEmccFlags Condition="'$(Configuration)' == 'Release'">-Oz</CMakeConfigurationEmccFlags> <CMakeConfigurationLinkFlags Condition="'$(Configuration)' == 'Debug'" >$(CMakeConfigurationEmccFlags)</CMakeConfigurationLinkFlags> <CMakeConfigurationLinkFlags Condition="'$(Configuration)' == 'Release'">-O2</CMakeConfigurationLinkFlags> <CMakeConfigurationLinkFlags >$(CMakeConfigurationLinkFlags) --emit-symbol-map</CMakeConfigurationLinkFlags> <CMakeConfigurationEmsdkPath Condition="'$(Configuration)' == 'Release'"> -DEMSDK_PATH=&quot;$(EMSDK_PATH.TrimEnd('\/'))&quot;</CMakeConfigurationEmsdkPath> <CMakeBuildRuntimeConfigureCmd>emcmake cmake $(MSBuildThisFileDirectory)runtime</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DCMAKE_BUILD_TYPE=$(Configuration)</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DCONFIGURATION_EMCC_FLAGS=&quot;$(CMakeConfigurationEmccFlags)&quot;</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DCONFIGURATION_LINK_FLAGS=&quot;$(CMakeConfigurationLinkFlags)&quot;</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DMONO_INCLUDES=&quot;$(MonoArtifactsPath)include/mono-2.0&quot;</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DMONO_OBJ_INCLUDES=&quot;$(MonoObjDir.TrimEnd('\/'))&quot;</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DICU_LIB_DIR=&quot;$(ICULibDir.TrimEnd('\/'))&quot;</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DMONO_ARTIFACTS_DIR=&quot;$(MonoArtifactsPath.TrimEnd('\/'))&quot;</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) -DNATIVE_BIN_DIR=&quot;$(NativeBinDir.TrimEnd('\/'))&quot;</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd>$(CMakeBuildRuntimeConfigureCmd) $(CMakeConfigurationEmsdkPath)</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd Condition="'$(OS)' == 'Windows_NT'">call &quot;$(RepositoryEngineeringDir)native\init-vs-env.cmd&quot; &amp;&amp; call &quot;$([MSBuild]::NormalizePath('$(EMSDK_PATH)', 'emsdk_env.bat'))&quot; &amp;&amp; $(CMakeBuildRuntimeConfigureCmd)</CMakeBuildRuntimeConfigureCmd> <CMakeBuildRuntimeConfigureCmd Condition="'$(OS)' != 'Windows_NT'">bash -c 'source $(EMSDK_PATH)/emsdk_env.sh 2>&amp;1 &amp;&amp; $(CMakeBuildRuntimeConfigureCmd)'</CMakeBuildRuntimeConfigureCmd> <CMakeOptions Condition="'$(MonoVerboseBuild)' != ''">-v</CMakeOptions> <CMakeBuildRuntimeCmd>cmake --build . --config $(Configuration) $(CmakeOptions)</CMakeBuildRuntimeCmd> <CMakeBuildRuntimeCmd Condition="'$(OS)' == 'Windows_NT'">call &quot;$(RepositoryEngineeringDir)native\init-vs-env.cmd&quot; &amp;&amp; call &quot;$([MSBuild]::NormalizePath('$(EMSDK_PATH)', 'emsdk_env.bat'))&quot; &amp;&amp; $(CMakeBuildRuntimeCmd)</CMakeBuildRuntimeCmd> <CMakeBuildRuntimeCmd Condition="'$(OS)' != 'Windows_NT'">bash -c 'source $(EMSDK_PATH)/emsdk_env.sh 2>&amp;1 &amp;&amp; $(CMakeBuildRuntimeCmd)'</CMakeBuildRuntimeCmd> </PropertyGroup> <Copy SourceFiles="$(PInvokeTableFile)" DestinationFolder="$(MonoObjDir)" SkipUnchangedFiles="true" /> <Copy SourceFiles="runtime/driver.c; runtime/pinvoke.c; runtime/corebindings.c; $(SharedNativeRoot)libs\System.Native\pal_random.lib.js;" DestinationFolder="$(NativeBinDir)src" SkipUnchangedFiles="true" /> <Copy SourceFiles="runtime/cjs/dotnet.cjs.pre.js; runtime/cjs/dotnet.cjs.lib.js; runtime/cjs/dotnet.cjs.post.js; runtime/cjs/dotnet.cjs.extpost.js;" DestinationFolder="$(NativeBinDir)src/cjs" SkipUnchangedFiles="true" /> <Copy SourceFiles="runtime/es6/dotnet.es6.pre.js; runtime/es6/dotnet.es6.lib.js; runtime/es6/dotnet.es6.post.js;" DestinationFolder="$(NativeBinDir)src/es6" SkipUnchangedFiles="true" /> <Copy SourceFiles="runtime\pinvoke.h" DestinationFolder="$(NativeBinDir)include\wasm" SkipUnchangedFiles="true" /> <Copy SourceFiles="@(ICULibFiles); @(ICULibNativeFiles);" DestinationFolder="$(NativeBinDir)" SkipUnchangedFiles="true" /> <Exec Command="$(CMakeBuildRuntimeConfigureCmd)" WorkingDirectory="$(NativeBinDir)" /> <Exec Command="$(CMakeBuildRuntimeCmd)" WorkingDirectory="$(NativeBinDir)" /> <ItemGroup> <IcuDataFiles Include="$(NativeBinDir)*.dat" /> <WasmSrcFiles Include="$(NativeBinDir)src\*.c; $(NativeBinDir)src\*.js; $(_EmccDefaultsRspPath); $(_EmccCompileRspPath); $(_EmccLinkRspPath); $(NativeBinDir)src\emcc-props.json" /> <WasmSrcFilesCjs Include="$(NativeBinDir)src\cjs\*.js;" /> <WasmSrcFilesEs6 Include="$(NativeBinDir)src\es6\*.js;" /> <WasmHeaderFiles Include="$(NativeBinDir)include\wasm\*.h" /> </ItemGroup> <Copy SourceFiles="$(NativeBinDir)dotnet.js; $(NativeBinDir)dotnet.d.ts; $(NativeBinDir)package.json; $(NativeBinDir)dotnet.wasm; $(NativeBinDir)dotnet.timezones.blat" DestinationFolder="$(MicrosoftNetCoreAppRuntimePackNativeDir)" SkipUnchangedFiles="true" /> <Copy SourceFiles="$(NativeBinDir)dotnet.js.symbols" DestinationFolder="$(MicrosoftNetCoreAppRuntimePackNativeDir)" SkipUnchangedFiles="true" /> <Copy SourceFiles="@(IcuDataFiles);@(ICULibNativeFiles)" DestinationFolder="$(MicrosoftNetCoreAppRuntimePackNativeDir)" SkipUnchangedFiles="true" /> <Copy SourceFiles="@(WasmSrcFiles)" DestinationFolder="$(MicrosoftNetCoreAppRuntimePackNativeDir)src" SkipUnchangedFiles="true" /> <Copy SourceFiles="@(WasmSrcFilesCjs)" DestinationFolder="$(MicrosoftNetCoreAppRuntimePackNativeDir)src\cjs" SkipUnchangedFiles="true" /> <Copy SourceFiles="@(WasmSrcFilesEs6)" DestinationFolder="$(MicrosoftNetCoreAppRuntimePackNativeDir)src\es6" SkipUnchangedFiles="true" /> <Copy SourceFiles="@(WasmHeaderFiles)" DestinationFolder="$(MicrosoftNetCoreAppRuntimePackNativeDir)include\wasm" SkipUnchangedFiles="true" /> </Target> <Target Name="InstallNpmPackages" Inputs="$(MonoProjectRoot)wasm/runtime/package.json" Outputs="$(MonoProjectRoot)wasm/runtime/node_modules/.npm-stamp" > <!-- install typescript and rollup --> <RunWithEmSdkEnv Condition="'$(ContinuousIntegrationBuild)' == 'true'" Command="npm ci" EmSdkPath="$(EMSDK_PATH)" IgnoreStandardErrorWarningFormat="true" WorkingDirectory="$(MonoProjectRoot)wasm/runtime/"/> <RunWithEmSdkEnv Condition="'$(ContinuousIntegrationBuild)' == 'true'" Command="npm audit" EmSdkPath="$(EMSDK_PATH)" IgnoreStandardErrorWarningFormat="true" WorkingDirectory="$(MonoProjectRoot)wasm/runtime/"/> <!-- npm install is faster on dev machine as it doesn't wipe node_modules folder --> <RunWithEmSdkEnv Condition="'$(ContinuousIntegrationBuild)' != 'true'" Command="npm install" EmSdkPath="$(EMSDK_PATH)" IgnoreStandardErrorWarningFormat="true" WorkingDirectory="$(MonoProjectRoot)wasm/runtime/"/> <Touch Files="$(MonoProjectRoot)wasm/runtime/node_modules/.npm-stamp" AlwaysCreate="true" /> </Target> <ItemGroup> <_RollupInputs Include="$(MonoProjectRoot)wasm/runtime/*.ts"/> <_RollupInputs Include="$(MonoProjectRoot)wasm/runtime/types/*.ts"/> <_RollupInputs Include="$(MonoProjectRoot)wasm/runtimetypes/*.d.ts"/> <_RollupInputs Include="$(MonoProjectRoot)wasm/runtime/*.json"/> <_RollupInputs Include="$(MonoProjectRoot)wasm/runtime/*.js"/> </ItemGroup> <Target Name="BuildWithRollup" Inputs="@(_RollupInputs)" Outputs="$(NativeBinDir).rollup-stamp" > <!-- code style check --> <RunWithEmSdkEnv Command="npm run lint" StandardOutputImportance="High" EmSdkPath="$(EMSDK_PATH)" WorkingDirectory="$(MonoProjectRoot)wasm/runtime/"/> <!-- compile typescript --> <RunWithEmSdkEnv Command="npm run rollup -- --environment Configuration:$(Configuration),NativeBinDir:$(NativeBinDir),ProductVersion:$(ProductVersion)" EmSdkPath="$(EMSDK_PATH)" IgnoreStandardErrorWarningFormat="true" WorkingDirectory="$(MonoProjectRoot)wasm/runtime/"/> <Copy SourceFiles="runtime/package.json;" DestinationFolder="$(NativeBinDir)" SkipUnchangedFiles="true" /> <!-- set version --> <RunWithEmSdkEnv Command="npm version $(PackageVersion)" EmSdkPath="$(EMSDK_PATH)" WorkingDirectory="$(NativeBinDir)"/> <Touch Files="$(NativeBinDir).rollup-stamp" AlwaysCreate="true" /> </Target> </Project>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/pal/tests/palsuite/c_runtime/islower/test1/test1.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*===================================================================== ** ** Source: test1.c ** ** Purpose: Tests the PAL implementation of the islower function ** Check that a number of characters return the correct ** values for whether they are lower case or not. ** ** **===================================================================*/ #include <palsuite.h> struct testCase { int CorrectResult; int character; }; PALTEST(c_runtime_islower_test1_paltest_islower_test1, "c_runtime/islower/test1/paltest_islower_test1") { int result; int i; struct testCase testCases[] = { {1, 'a'}, /* Basic cases */ {1, 'z'}, {0, 'B'}, /* Lower case */ {0, '?'}, /* Characters without case */ {0, 230}, {0, '5'} }; if (PAL_Initialize(argc, argv)) { return FAIL; } /* Loop through each case. Check to see if each is lower case or not. */ for(i = 0; i < sizeof(testCases) / sizeof(struct testCase); i++) { result = islower(testCases[i].character); /* The return value is 'non-zero' for success. This if condition * will still work if that non-zero isn't just 1 */ if ( ((testCases[i].CorrectResult == 1) && (result == 0)) || ( (testCases[i].CorrectResult == 0) && (result != 0) )) { Fail("ERROR: islower returned %i instead of %i for " "character %c.\n", result, testCases[i].CorrectResult, testCases[i].character); } } PAL_Terminate(); return PASS; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*===================================================================== ** ** Source: test1.c ** ** Purpose: Tests the PAL implementation of the islower function ** Check that a number of characters return the correct ** values for whether they are lower case or not. ** ** **===================================================================*/ #include <palsuite.h> struct testCase { int CorrectResult; int character; }; PALTEST(c_runtime_islower_test1_paltest_islower_test1, "c_runtime/islower/test1/paltest_islower_test1") { int result; int i; struct testCase testCases[] = { {1, 'a'}, /* Basic cases */ {1, 'z'}, {0, 'B'}, /* Lower case */ {0, '?'}, /* Characters without case */ {0, 230}, {0, '5'} }; if (PAL_Initialize(argc, argv)) { return FAIL; } /* Loop through each case. Check to see if each is lower case or not. */ for(i = 0; i < sizeof(testCases) / sizeof(struct testCase); i++) { result = islower(testCases[i].character); /* The return value is 'non-zero' for success. This if condition * will still work if that non-zero isn't just 1 */ if ( ((testCases[i].CorrectResult == 1) && (result == 0)) || ( (testCases[i].CorrectResult == 0) && (result != 0) )) { Fail("ERROR: islower returned %i instead of %i for " "character %c.\n", result, testCases[i].CorrectResult, testCases[i].character); } } PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/HardwareIntrinsics/X86/AvxVnni/Program.AvxVnni.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { static Program() { TestList = new Dictionary<string, Action>() { ["MultiplyWideningAndAdd.Byte"] = MultiplyWideningAndAddByte, ["MultiplyWideningAndAdd.Int16"] = MultiplyWideningAndAddInt16, ["MultiplyWideningAndAddSaturate.Byte"] = MultiplyWideningAndAddSaturateByte, ["MultiplyWideningAndAddSaturate.Int16"] = MultiplyWideningAndAddSaturateInt16, }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { static Program() { TestList = new Dictionary<string, Action>() { ["MultiplyWideningAndAdd.Byte"] = MultiplyWideningAndAddByte, ["MultiplyWideningAndAdd.Int16"] = MultiplyWideningAndAddInt16, ["MultiplyWideningAndAddSaturate.Byte"] = MultiplyWideningAndAddSaturateByte, ["MultiplyWideningAndAddSaturate.Int16"] = MultiplyWideningAndAddSaturateInt16, }; } } }
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/GC/Scenarios/GCSimulator/GCSimulator_264.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestExecutionArguments>-t 3 -tp 0 -dz 17 -sdz 8500 -dc 10000 -sdc 5000 -lt 4 -dp 0.4 -dw 0.0</CLRTestExecutionArguments> <IsGCSimulatorTest>true</IsGCSimulatorTest> <CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GCSimulator.cs" /> <Compile Include="lifetimefx.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestExecutionArguments>-t 3 -tp 0 -dz 17 -sdz 8500 -dc 10000 -sdc 5000 -lt 4 -dp 0.4 -dw 0.0</CLRTestExecutionArguments> <IsGCSimulatorTest>true</IsGCSimulatorTest> <CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GCSimulator.cs" /> <Compile Include="lifetimefx.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,360
Add tests for `comhost` with managed host
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-08T21:34:54Z
2022-03-10T04:52:18Z
f091e5585a6c2798ea15174261338b2f186c6be4
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained). This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing: cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Net.Http.Json/tests/FunctionalTests/JsonContentTests.netcoreapp.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Net.Http.Headers; using System.Net.Test.Common; using System.Runtime.CompilerServices; using System.Text; using System.Text.Json; using System.Threading.Tasks; using Xunit; namespace System.Net.Http.Json.Functional.Tests { public class JsonContentTests_Sync : JsonContentTestsBase { protected override Task<HttpResponseMessage> SendAsync(HttpClient client, HttpRequestMessage request) => Task.Run(() => client.Send(request)); [Fact] public void JsonContent_CopyTo_Succeeds() { Person person = Person.Create(); using JsonContent content = JsonContent.Create(person); using MemoryStream stream = new MemoryStream(); // HttpContent.CopyTo internally calls overriden JsonContent.SerializeToStream, which is the targeted method of this test. content.CopyTo(stream, context: null, cancellationToken: default); stream.Seek(0, SeekOrigin.Begin); using StreamReader reader = new StreamReader(stream); string json = reader.ReadToEnd(); Assert.Equal(person.Serialize(JsonOptions.DefaultSerializerOptions), json); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Net.Http.Headers; using System.Net.Test.Common; using System.Runtime.CompilerServices; using System.Text; using System.Text.Json; using System.Threading.Tasks; using Xunit; namespace System.Net.Http.Json.Functional.Tests { public class JsonContentTests_Sync : JsonContentTestsBase { protected override Task<HttpResponseMessage> SendAsync(HttpClient client, HttpRequestMessage request) => Task.Run(() => client.Send(request)); [Fact] public void JsonContent_CopyTo_Succeeds() { Person person = Person.Create(); using JsonContent content = JsonContent.Create(person); using MemoryStream stream = new MemoryStream(); // HttpContent.CopyTo internally calls overriden JsonContent.SerializeToStream, which is the targeted method of this test. content.CopyTo(stream, context: null, cancellationToken: default); stream.Seek(0, SeekOrigin.Begin); using StreamReader reader = new StreamReader(stream); string json = reader.ReadToEnd(); Assert.Equal(person.Serialize(JsonOptions.DefaultSerializerOptions), json); } } }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/pipelines/coreclr/templates/build-perf-maui-apps.yml
parameters: osGroup: '' osSubgroup: '' archType: '' buildConfig: '' runtimeFlavor: '' helixQueues: '' targetRid: '' nameSuffix: '' platform: '' shouldContinueOnError: '' rootFolder: '' includeRootFolder: '' displayName: '' artifactName: '' archiveExtension: '' archiveType: '' tarCompression: '' steps: # Uncomment to reenable package replacement #- task: DownloadPipelineArtifact@2 # displayName: Download runtime packages # inputs: # artifact: 'IntermediateArtifacts' # path: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks # patterns: | # IntermediateArtifacts/MonoRuntimePacks/Shipping/Microsoft.NETCore.App.Runtime.Mono.android-!(*.symbols).nupkg # IntermediateArtifacts/MonoRuntimePacks/Shipping/Microsoft.NETCore.App.Runtime.Mono.ios-!(*.symbols).nupkg # IntermediateArtifacts/MonoRuntimePacks/Shipping/Microsoft.NETCore.App.Runtime.Mono.iossimulator-!(*.symbols).nupkg # IntermediateArtifacts/MonoRuntimePacks/Shipping/Microsoft.NETCore.App.Runtime.Mono.maccatalyst-!(*.symbols).nupkg # # Other artifacts to include once they are being built # # EX. IntermediateArtifacts/MonoRuntimePacks/Shipping/Microsoft.NETCore.App.Runtime.Mono.maccatalyst-*.nupkg #- task: CopyFiles@2 # displayName: Flatten packages # inputs: # sourceFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks # contents: '*/Shipping/*.nupkg' # cleanTargetFolder: false # targetFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks # flattenFolders: true #- script: | # for file in *.nupkg # do # mv -v "$file" "${file%.nupkg}.zip" # done # displayName: Change nupkgs to zips # workingDirectory: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks ##Unzip the nuget packages to make the actual runtimes accessible #- task: ExtractFiles@1 # displayName: Extract android-arm runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-arm.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-arm # overwriteExistingFiles: true # cleanDestinationFolder: false #- task: ExtractFiles@1 # displayName: Extract android-arm64 runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-arm64.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-arm64 # overwriteExistingFiles: true # cleanDestinationFolder: false #- task: ExtractFiles@1 # displayName: Extract android-x86 runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-x86.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-x86 # overwriteExistingFiles: true # cleanDestinationFolder: false #- task: ExtractFiles@1 # displayName: Extract android-x64 runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-x64.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-x64 # overwriteExistingFiles: true # cleanDestinationFolder: false #- task: ExtractFiles@1 # displayName: Extract ios-arm runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.ios-arm.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.ios-arm # overwriteExistingFiles: true # cleanDestinationFolder: false #- task: ExtractFiles@1 # displayName: Extract ios-arm64 runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.ios-arm64.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.ios-arm64 # overwriteExistingFiles: true # cleanDestinationFolder: false #- task: ExtractFiles@1 # displayName: Extract maccatalyst-x64 runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.maccatalyst-x64.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.maccatalyst-x64 # overwriteExistingFiles: true # cleanDestinationFolder: false #- task: ExtractFiles@1 # displayName: Extract iossimulator-x64 runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.iossimulator-x64.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.iossimulator-x64 # overwriteExistingFiles: true # cleanDestinationFolder: false # Get the current maui nuget config so all things can be found and darc based package sources are kept up to date. - script: | curl -o NuGet.config 'https://raw.githubusercontent.com/dotnet/maui/main/NuGet.config' curl -o dotnet-install.sh 'https://dotnet.microsoft.com/download/dotnet/scripts/v1/dotnet-install.sh' chmod -R a+rx . ./dotnet-install.sh --channel 6.0.2xx --quality daily --install-dir . ./dotnet --info ./dotnet workload install maui --from-rollback-file https://aka.ms/dotnet/maui/main.json --configfile NuGet.config displayName: Install MAUI workload workingDirectory: $(Build.SourcesDirectory) - script: | ./dotnet new maui -n MauiTesting cd MauiTesting cp $(Build.SourcesDirectory)/src/tests/Common/maui/MauiScenario.props ./Directory.Build.props cp $(Build.SourcesDirectory)/src/tests/Common/maui/MauiScenario.targets ./Directory.Build.targets cp $(Build.SourcesDirectory)/NuGet.config ./NuGet.config displayName: Setup MAUI Project workingDirectory: $(Build.SourcesDirectory) - script: | chmod -R a+r . # Restore is split out because of https://github.com/dotnet/sdk/issues/21877, can be removed with --no-restore once fixed ../dotnet restore ../dotnet publish -bl:MauiAndroid.binlog -f net6.0-android -c Release -r android-arm64 --no-restore --self-contained mv ./bin/Release/net6.0-android/android-arm64/com.companyname.mauitesting-Signed.apk ./MauiAndroidDefault.apk displayName: Build MAUI Android workingDirectory: $(Build.SourcesDirectory)/MauiTesting # This step pulls the product version from the used Microsoft.Maui.dll file properties and saves it for upload with the maui test counter. # We pull from this file as we did not find another place to reliably get the version information pre or post build. - powershell: | $RetrievedMauiVersion = Get-ChildItem .\obj\Release\net6.0-android\android-arm64\linked\Microsoft.Maui.dll | Select-Object -ExpandProperty VersionInfo | Select-Object ProductVersion | Select-Object -ExpandProperty ProductVersion $RetrievedMauiVersion Write-Host "##vso[task.setvariable variable=mauiVersion;isOutput=true]$RetrievedMauiVersion" name: getMauiVersion displayName: Get and Save MAUI Version workingDirectory: $(Build.SourcesDirectory)/MauiTesting - script: | chmod -R a+r . ../dotnet build -bl:MauiiOS.binlog -f net6.0-ios -c Release mv ./bin/Release/net6.0-ios/iossimulator-x64/MauiTesting.app ./MauiiOSDefault.app displayName: Build MAUI iOS workingDirectory: $(Build.SourcesDirectory)/MauiTesting - script: | chmod -R a+r . ../dotnet publish -bl:MauiMacCatalyst.binlog -f net6.0-maccatalyst -c Release mv ./bin/Release/net6.0-maccatalyst/maccatalyst-x64/MauiTesting.app ./MauiMacCatalystDefault.app displayName: Build MAUI MacCatalyst workingDirectory: $(Build.SourcesDirectory)/MauiTesting - task: PublishBuildArtifacts@1 displayName: 'Publish MauiAndroid binlog' condition: always() inputs: pathtoPublish: $(Build.SourcesDirectory)/MauiTesting/MauiAndroid.binlog artifactName: ${{ parameters.artifactName }} - task: PublishBuildArtifacts@1 displayName: 'Publish MauiiOS binlog' condition: always() inputs: pathtoPublish: $(Build.SourcesDirectory)/MauiTesting/MauiiOS.binlog artifactName: ${{ parameters.artifactName }} - task: PublishBuildArtifacts@1 displayName: 'Publish MauiMacCatalyst binlog' condition: always() inputs: pathtoPublish: $(Build.SourcesDirectory)/MauiTesting/MauiMacCatalyst.binlog artifactName: ${{ parameters.artifactName }} - template: /eng/pipelines/common/upload-artifact-step.yml parameters: rootFolder: $(Build.SourcesDirectory)/MauiTesting/MauiAndroidDefault.apk includeRootFolder: true displayName: Maui Android App artifactName: MauiAndroidApp archiveExtension: '.tar.gz' archiveType: tar tarCompression: gz - template: /eng/pipelines/common/upload-artifact-step.yml parameters: rootFolder: $(Build.SourcesDirectory)/MauiTesting/MauiiOSDefault.app includeRootFolder: true displayName: Maui iOS App artifactName: MauiiOSDefault archiveExtension: '.tar.gz' archiveType: tar tarCompression: gz - template: /eng/pipelines/common/upload-artifact-step.yml parameters: rootFolder: $(Build.SourcesDirectory)/MauiTesting/MauiMacCatalystDefault.app includeRootFolder: true displayName: Maui MacCatalyst App artifactName: MauiMacCatalystDefault archiveExtension: '.tar.gz' archiveType: tar tarCompression: gz - script: rm -r -f ./bin workingDirectory: $(Build.SourcesDirectory)/MauiTesting displayName: Clean bin directory condition: succeededOrFailed() - template: /eng/pipelines/common/upload-artifact-step.yml parameters: osGroup: ${{ parameters.osGroup }} osSubgroup: ${{ parameters.osSubgroup }} archType: ${{ parameters.archType }} buildConfig: ${{ parameters.buildConfig }} runtimeFlavor: ${{ parameters.runtimeFlavor }} helixQueues: ${{ parameters.helixQueues }} targetRid: ${{ parameters.targetRid }} nameSuffix: ${{ parameters.nameSuffix }} platform: ${{ parameters.platform }} shouldContinueOnError: ${{ parameters.shouldContinueOnError }} rootFolder: ${{ parameters.rootFolder }} includeRootFolder: ${{ parameters.includeRootFolder }} displayName: ${{ parameters.displayName }} artifactName: ${{ parameters.artifactName }} archiveExtension: ${{ parameters.archiveExtension }} archiveType: ${{ parameters.archiveType }} tarCompression: ${{ parameters.tarCompression }}
parameters: osGroup: '' osSubgroup: '' archType: '' buildConfig: '' runtimeFlavor: '' helixQueues: '' targetRid: '' nameSuffix: '' platform: '' shouldContinueOnError: '' rootFolder: '' includeRootFolder: '' displayName: '' artifactName: '' archiveExtension: '' archiveType: '' tarCompression: '' steps: # Uncomment to reenable package replacement #- task: DownloadPipelineArtifact@2 # displayName: Download runtime packages # inputs: # artifact: 'IntermediateArtifacts' # path: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks # patterns: | # IntermediateArtifacts/MonoRuntimePacks/Shipping/Microsoft.NETCore.App.Runtime.Mono.android-!(*.symbols).nupkg # IntermediateArtifacts/MonoRuntimePacks/Shipping/Microsoft.NETCore.App.Runtime.Mono.ios-!(*.symbols).nupkg # IntermediateArtifacts/MonoRuntimePacks/Shipping/Microsoft.NETCore.App.Runtime.Mono.iossimulator-!(*.symbols).nupkg # IntermediateArtifacts/MonoRuntimePacks/Shipping/Microsoft.NETCore.App.Runtime.Mono.maccatalyst-!(*.symbols).nupkg # # Other artifacts to include once they are being built # # EX. IntermediateArtifacts/MonoRuntimePacks/Shipping/Microsoft.NETCore.App.Runtime.Mono.maccatalyst-*.nupkg #- task: CopyFiles@2 # displayName: Flatten packages # inputs: # sourceFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks # contents: '*/Shipping/*.nupkg' # cleanTargetFolder: false # targetFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks # flattenFolders: true #- script: | # for file in *.nupkg # do # mv -v "$file" "${file%.nupkg}.zip" # done # displayName: Change nupkgs to zips # workingDirectory: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks ##Unzip the nuget packages to make the actual runtimes accessible #- task: ExtractFiles@1 # displayName: Extract android-arm runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-arm.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-arm # overwriteExistingFiles: true # cleanDestinationFolder: false #- task: ExtractFiles@1 # displayName: Extract android-arm64 runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-arm64.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-arm64 # overwriteExistingFiles: true # cleanDestinationFolder: false #- task: ExtractFiles@1 # displayName: Extract android-x86 runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-x86.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-x86 # overwriteExistingFiles: true # cleanDestinationFolder: false #- task: ExtractFiles@1 # displayName: Extract android-x64 runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-x64.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.android-x64 # overwriteExistingFiles: true # cleanDestinationFolder: false #- task: ExtractFiles@1 # displayName: Extract ios-arm runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.ios-arm.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.ios-arm # overwriteExistingFiles: true # cleanDestinationFolder: false #- task: ExtractFiles@1 # displayName: Extract ios-arm64 runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.ios-arm64.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.ios-arm64 # overwriteExistingFiles: true # cleanDestinationFolder: false #- task: ExtractFiles@1 # displayName: Extract maccatalyst-x64 runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.maccatalyst-x64.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.maccatalyst-x64 # overwriteExistingFiles: true # cleanDestinationFolder: false #- task: ExtractFiles@1 # displayName: Extract iossimulator-x64 runtime # inputs: # archiveFilePatterns: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.iossimulator-x64.*.zip # destinationFolder: $(Build.SourcesDirectory)/MauiTesting/ArtifactPacks/Microsoft.NETCore.App.Runtime.Mono.iossimulator-x64 # overwriteExistingFiles: true # cleanDestinationFolder: false # Get the current maui nuget config so all things can be found and darc based package sources are kept up to date. - script: | curl -o NuGet.config 'https://raw.githubusercontent.com/dotnet/maui/main/NuGet.config' curl -o dotnet-install.sh 'https://dotnet.microsoft.com/download/dotnet/scripts/v1/dotnet-install.sh' chmod -R a+rx . ./dotnet-install.sh --channel 6.0.2xx --quality daily --install-dir . ./dotnet --info ./dotnet workload install maui --from-rollback-file https://aka.ms/dotnet/maui/main.json --configfile NuGet.config displayName: Install MAUI workload workingDirectory: $(Build.SourcesDirectory) - script: $(Build.SourcesDirectory)/eng/testing/performance/create-provisioning-profile.sh displayName: Create iOS code signing and provisioning profile - script: | ./dotnet new maui -n MauiTesting cd MauiTesting cp $(Build.SourcesDirectory)/src/tests/Common/maui/MauiScenario.props ./Directory.Build.props cp $(Build.SourcesDirectory)/src/tests/Common/maui/MauiScenario.targets ./Directory.Build.targets cp $(Build.SourcesDirectory)/NuGet.config ./NuGet.config displayName: Setup MAUI Project workingDirectory: $(Build.SourcesDirectory) - script: | chmod -R a+r . # Restore is split out because of https://github.com/dotnet/sdk/issues/21877, can be removed with --no-restore once fixed ../dotnet restore ../dotnet publish -bl:MauiAndroid.binlog -f net6.0-android -c Release -r android-arm64 --no-restore --self-contained mv ./bin/Release/net6.0-android/android-arm64/com.companyname.mauitesting-Signed.apk ./MauiAndroidDefault.apk displayName: Build MAUI Android workingDirectory: $(Build.SourcesDirectory)/MauiTesting # This step pulls the product version from the used Microsoft.Maui.dll file properties and saves it for upload with the maui test counter. # We pull from this file as we did not find another place to reliably get the version information pre or post build. - powershell: | $RetrievedMauiVersion = Get-ChildItem .\obj\Release\net6.0-android\android-arm64\linked\Microsoft.Maui.dll | Select-Object -ExpandProperty VersionInfo | Select-Object ProductVersion | Select-Object -ExpandProperty ProductVersion $RetrievedMauiVersion Write-Host "##vso[task.setvariable variable=mauiVersion;isOutput=true]$RetrievedMauiVersion" name: getMauiVersion displayName: Get and Save MAUI Version workingDirectory: $(Build.SourcesDirectory)/MauiTesting - script: | chmod -R a+r . # remove net6.0-maccatalyst to work around https://github.com/dotnet/sdk/issues/21877 cp MauiTesting.csproj MauiTesting.csproj.bak sed -i'' -e 's/net6.0-ios;net6.0-maccatalyst/net6.0-ios/g' MauiTesting.csproj ../dotnet publish -bl:MauiiOS.binlog -f net6.0-ios --self-contained -r ios-arm64 -c Release /p:_RequireCodeSigning=false mv ./bin/Release/net6.0-ios/ios-arm64/publish/MauiTesting.ipa ./MauiiOSDefault.ipa cp MauiTesting.csproj.bak MauiTesting.csproj displayName: Build MAUI iOS workingDirectory: $(Build.SourcesDirectory)/MauiTesting - script: | chmod -R a+r . ../dotnet publish -bl:MauiMacCatalyst.binlog -f net6.0-maccatalyst -c Release mv ./bin/Release/net6.0-maccatalyst/maccatalyst-x64/MauiTesting.app ./MauiMacCatalystDefault.app displayName: Build MAUI MacCatalyst workingDirectory: $(Build.SourcesDirectory)/MauiTesting - task: PublishBuildArtifacts@1 displayName: 'Publish MauiAndroid binlog' condition: always() inputs: pathtoPublish: $(Build.SourcesDirectory)/MauiTesting/MauiAndroid.binlog artifactName: ${{ parameters.artifactName }} - task: PublishBuildArtifacts@1 displayName: 'Publish MauiiOS binlog' condition: always() inputs: pathtoPublish: $(Build.SourcesDirectory)/MauiTesting/MauiiOS.binlog artifactName: ${{ parameters.artifactName }} - task: PublishBuildArtifacts@1 displayName: 'Publish MauiMacCatalyst binlog' condition: always() inputs: pathtoPublish: $(Build.SourcesDirectory)/MauiTesting/MauiMacCatalyst.binlog artifactName: ${{ parameters.artifactName }} - template: /eng/pipelines/common/upload-artifact-step.yml parameters: rootFolder: $(Build.SourcesDirectory)/MauiTesting/MauiAndroidDefault.apk includeRootFolder: true displayName: Maui Android App artifactName: MauiAndroidApp archiveExtension: '.tar.gz' archiveType: tar tarCompression: gz - template: /eng/pipelines/common/upload-artifact-step.yml parameters: rootFolder: $(Build.SourcesDirectory)/MauiTesting/MauiiOSDefault.ipa includeRootFolder: true displayName: Maui iOS IPA artifactName: MauiiOSDefaultIPA archiveExtension: '.tar.gz' archiveType: tar tarCompression: gz - template: /eng/pipelines/common/upload-artifact-step.yml parameters: rootFolder: $(Build.SourcesDirectory)/MauiTesting/MauiMacCatalystDefault.app includeRootFolder: true displayName: Maui MacCatalyst App artifactName: MauiMacCatalystDefault archiveExtension: '.tar.gz' archiveType: tar tarCompression: gz - script: rm -r -f ./bin workingDirectory: $(Build.SourcesDirectory)/MauiTesting displayName: Clean bin directory condition: succeededOrFailed() - template: /eng/pipelines/common/upload-artifact-step.yml parameters: osGroup: ${{ parameters.osGroup }} osSubgroup: ${{ parameters.osSubgroup }} archType: ${{ parameters.archType }} buildConfig: ${{ parameters.buildConfig }} runtimeFlavor: ${{ parameters.runtimeFlavor }} helixQueues: ${{ parameters.helixQueues }} targetRid: ${{ parameters.targetRid }} nameSuffix: ${{ parameters.nameSuffix }} platform: ${{ parameters.platform }} shouldContinueOnError: ${{ parameters.shouldContinueOnError }} rootFolder: ${{ parameters.rootFolder }} includeRootFolder: ${{ parameters.includeRootFolder }} displayName: ${{ parameters.displayName }} artifactName: ${{ parameters.artifactName }} archiveExtension: ${{ parameters.archiveExtension }} archiveType: ${{ parameters.archiveType }} tarCompression: ${{ parameters.tarCompression }}
1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/pipelines/coreclr/templates/perf-job.yml
parameters: buildConfig: '' archType: '' osGroup: '' osSubgroup: '' container: '' runtimeVariant: '' framework: net7.0 # Specify the appropriate framework when running release branches (ie net6.0 for release/6.0) liveLibrariesBuildConfig: '' variables: {} runtimeType: 'coreclr' pool: '' codeGenType: 'JIT' projectFile: '' runKind: '' runJobTemplate: '/eng/pipelines/coreclr/templates/run-performance-job.yml' additionalSetupParameters: '' logicalMachine: '' pgoRunType: '' javascriptEngine: 'NoJS' iOSLlvmBuild: 'False' ### Perf job ### Each perf job depends on a corresponding build job with the same ### buildConfig and archType. jobs: - template: ${{ parameters.runJobTemplate }} parameters: # Compute job name from template parameters jobName: ${{ format('perfbuild_{0}{1}_{2}_{3}_{4}_{5}_{6}_{7}_{8}_{9}_{10}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig, parameters.runtimeType, parameters.codeGenType, parameters.runKind, parameters.logicalMachine, parameters.javascriptEngine, parameters.pgoRunType, parameters.iosLlvmBuild) }} displayName: ${{ format('Performance {0}{1} {2} {3} {4} {5} {6} {7} {8} {9} {10}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig, parameters.runtimeType, parameters.codeGenType, parameters.runKind, parameters.logicalMachine, parameters.javascriptEngine, parameters.pgoRunType, parameters.iosLlvmBuild) }} pool: ${{ parameters.pool }} buildConfig: ${{ parameters.buildConfig }} archType: ${{ parameters.archType }} osGroup: ${{ parameters.osGroup }} osSubgroup: ${{ parameters.osSubgroup }} runtimeVariant: ${{ parameters.runtimeVariant }} liveLibrariesBuildConfig: ${{ parameters.liveLibrariesBuildConfig }} runtimeType: ${{ parameters.runtimeType }} codeGenType: ${{ parameters.codeGenType }} projectFile: ${{ parameters.projectFile }} runKind: ${{ parameters.runKind }} additionalSetupParameters: ${{ parameters.additionalSetupParameters }} container: ${{ parameters.container }} logicalmachine: ${{ parameters.logicalmachine }} pgoRunType: ${{ parameters.pgoRunType }} javascriptEngine: ${{ parameters.javascriptEngine }} iosLlvmBuild: ${{ parameters.iosLlvmBuild }} # Test job depends on the corresponding build job dependsOn: - ${{ if not(in(parameters.runtimeType, 'AndroidMono', 'iOSMono')) }}: - ${{ format('coreclr_{0}_product_build_{1}{2}_{3}_{4}', parameters.runtimeVariant, parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig) }} - ${{ if ne(parameters.liveLibrariesBuildConfig, '') }}: - ${{ format('libraries_build_{0}{1}_{2}_{3}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveLibrariesBuildConfig) }} - ${{ if and(eq(parameters.runtimeType, 'mono'), ne(parameters.codeGenType, 'AOT')) }}: - ${{ format('mono_{0}_product_build_{1}{2}_{3}_{4}', parameters.runtimeVariant, parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig) }} - ${{ if eq(parameters.runtimeType, 'wasm')}}: - ${{ format('build_{0}{1}_{2}_{3}_{4}_{5}', 'Browser', '', 'wasm', 'Linux', parameters.buildConfig, parameters.runtimeType) }} - ${{ if and(eq(parameters.codeGenType, 'AOT'), ne(parameters.runtimeType, 'wasm'))}}: - ${{ format('build_{0}{1}_{2}_{3}_{4}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig, parameters.codeGenType) }} - ${{ if eq(parameters.runtimeType, 'AndroidMono')}}: - ${{ 'build_Android_arm64_release_AndroidMono' }} - ${{ 'Build_iOS_arm64_release_MACiOSAndroidMaui' }} - ${{ if eq(parameters.runtimeType, 'iOSMono')}}: - ${{ 'build_iOS_arm64_release_iOSMono' }} - ${{ 'Build_iOS_arm64_release_MACiOSAndroidMaui' }} ${{ if and(eq(parameters.osGroup, 'windows'), not(in(parameters.runtimeType, 'AndroidMono', 'iOSMono'))) }}: ${{ if eq(parameters.runtimeType, 'mono') }}: extraSetupParameters: -Architecture ${{ parameters.archType }} -MonoDotnet $(Build.SourcesDirectory)\.dotnet-mono ${{ if eq(parameters.runtimeType, 'coreclr') }}: extraSetupParameters: -CoreRootDirectory $(Build.SourcesDirectory)\artifacts\tests\coreclr\${{ parameters.osGroup }}.${{ parameters.archType }}.Release\Tests\Core_Root -Architecture ${{ parameters.archType }} ${{ if and(ne(parameters.osGroup, 'windows'), not(in(parameters.runtimeType, 'AndroidMono', 'iOSMono'))) }}: ${{ if and(eq(parameters.runtimeType, 'mono'), ne(parameters.codeGenType, 'AOT')) }}: extraSetupParameters: --architecture ${{ parameters.archType }} --monodotnet $(Build.SourcesDirectory)/.dotnet-mono ${{ if and(eq(parameters.runtimeType, 'wasm'), ne(parameters.codeGenType, 'AOT')) }}: extraSetupParameters: --architecture ${{ parameters.archType }} --wasm $(librariesDownloadDir)/bin/wasm --javascriptengine ${{ parameters.javascriptEngine }} ${{ if and(eq(parameters.runtimeType, 'wasm'), eq(parameters.codeGenType, 'AOT')) }}: extraSetupParameters: --architecture ${{ parameters.archType }} --wasm $(librariesDownloadDir)/bin/wasm --wasmaot --javascriptengine ${{ parameters.javascriptEngine }} ${{ if and(eq(parameters.codeGenType, 'AOT'), ne(parameters.runtimeType, 'wasm')) }}: extraSetupParameters: --architecture ${{ parameters.archType }} --monoaot $(librariesDownloadDir)/bin/aot ${{ if and(eq(parameters.runtimeType, 'coreclr'), ne(parameters.osSubGroup, '_musl')) }}: extraSetupParameters: --corerootdirectory $(Build.SourcesDirectory)/artifacts/tests/coreclr/${{ parameters.osGroup }}.${{ parameters.archType }}.Release/Tests/Core_Root --architecture ${{ parameters.archType }} ${{ if and(eq(parameters.runtimeType, 'coreclr'), eq(parameters.osSubGroup, '_musl')) }}: extraSetupParameters: --corerootdirectory $(Build.SourcesDirectory)/artifacts/tests/coreclr/${{ parameters.osGroup }}.${{ parameters.archType }}.Release/Tests/Core_Root --architecture ${{ parameters.archType }} --alpine ${{ if eq(parameters.runtimeType, 'AndroidMono') }}: extraSetupParameters: -Architecture ${{ parameters.archType }} -AndroidMono ${{ if eq(parameters.runtimeType, 'iosMono') }}: extraSetupParameters: -Architecture ${{ parameters.archType }} -iOSMono -iOSLlvmBuild:$${{ parameters.iOSLlvmBuild }} variables: ${{ parameters.variables }} frameworks: - ${{ parameters.framework }} steps: # Extra steps that will be passed to the performance template and run before sending the job to helix (all of which is done in the template) # Optionally download live-built libraries - ${{ if ne(parameters.liveLibrariesBuildConfig, '') }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(librariesDownloadDir) cleanUnpackFolder: false artifactFileName: '$(librariesBuildArtifactName)$(archiveExtension)' artifactName: '$(librariesBuildArtifactName)' displayName: 'live-built libraries' # Download coreclr - ${{ if not(in(parameters.runtimeType, 'AndroidMono', 'iOSMono')) }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(buildProductRootFolderPath) artifactFileName: '$(buildProductArtifactName)$(archiveExtension)' artifactName: '$(buildProductArtifactName)' displayName: 'Coreclr product build' # Download mono - ${{ if and(eq(parameters.runtimeType, 'mono'), ne(parameters.codeGenType, 'AOT')) }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(librariesDownloadDir)/bin/mono/$(osGroup).$(archType).$(buildConfigUpper) cleanUnpackFolder: false artifactFileName: 'MonoProduct__${{ parameters.runtimeVariant }}_$(osGroup)_$(archType)_$(buildConfig)$(archiveExtension)' artifactName: 'MonoProduct__${{ parameters.runtimeVariant }}_$(osGroup)_$(archType)_$(buildConfig)' displayName: 'Mono runtime' # Download wasm - ${{ if eq(parameters.runtimeType, 'wasm') }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(librariesDownloadDir)/BrowserWasm artifactFileName: BrowserWasm.zip artifactName: BrowserWasm displayName: BrowserWasm - script: "mkdir $(librariesDownloadDir)/bin/wasm;unzip -o $(librariesDownloadDir)/BrowserWasm/artifacts/packages/Release/Shipping/Microsoft.NETCore.App.Runtime.Mono.browser-wasm.7.0.0-ci.nupkg data/* runtimes/* -d $(librariesDownloadDir)/bin/wasm;cp src/mono/wasm/test-main.js $(librariesDownloadDir)/bin/wasm/test-main.js;find $(librariesDownloadDir)/bin/wasm -type f -exec chmod 664 {} \\;" displayName: "Create wasm directory (Linux)" # Download mono AOT - ${{ if and(eq(parameters.codeGenType, 'AOT'), ne(parameters.runtimeType, 'wasm')) }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(librariesDownloadDir)/LinuxMonoAOT artifactFileName: LinuxMonoAOT${{ parameters.archType }}.tar.gz artifactName: LinuxMonoAOT${{ parameters.archType }} displayName: AOT Mono Artifacts - script: "mkdir -p $(librariesDownloadDir)/bin/aot/sgen;mkdir -p $(librariesDownloadDir)/bin/aot/pack;cp -r $(librariesDownloadDir)/LinuxMonoAOT/artifacts/obj/mono/Linux.${{ parameters.archType }}.Release/mono/* $(librariesDownloadDir)/bin/aot/sgen;cp -r $(librariesDownloadDir)/LinuxMonoAOT/artifacts/bin/microsoft.netcore.app.runtime.linux-${{ parameters.archType }}/Release/* $(librariesDownloadDir)/bin/aot/pack" displayName: "Create aot directory (Linux)" # Download AndroidMono and MauiAndroid - ${{ if eq(parameters.runtimeType, 'AndroidMono')}}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory)/androidHelloWorld cleanUnpackFolder: false artifactFileName: 'AndroidMonoarm64.tar.gz' artifactName: 'AndroidMonoarm64' displayName: 'Mono Android HelloWorld' - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory) cleanUnpackFolder: false artifactFileName: 'MauiAndroidApp.tar.gz' artifactName: 'MauiAndroidApp' displayName: 'Maui Android App' # Download iOSMono tests and MauiiOS/MacCatalyst - ${{ if eq(parameters.runtimeType, 'iOSMono') }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory)/iosHelloWorld/nollvm cleanUnpackFolder: false artifactFileName: 'iOSSampleAppNoLLVM.tar.gz' artifactName: 'iOSSampleAppNoLLVM' displayName: 'iOS Sample App NoLLVM' - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory)/iosHelloWorld/llvm cleanUnpackFolder: false artifactFileName: 'iOSSampleAppLLVM.tar.gz' artifactName: 'iOSSampleAppLLVM' displayName: 'iOS Sample App LLVM' - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory)/MauiiOSDefault cleanUnpackFolder: false artifactFileName: 'MauiiOSDefault.tar.gz' artifactName: 'MauiiOSDefault' displayName: 'Maui iOS App' - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory)/MauiMacCatalystDefault cleanUnpackFolder: false artifactFileName: 'MauiMacCatalystDefault.tar.gz' artifactName: 'MauiMacCatalystDefault' displayName: 'Maui MacCatalyst App' # Create Core_Root - script: $(Build.SourcesDirectory)/src/tests/build$(scriptExt) $(buildConfig) $(archType) generatelayoutonly $(librariesOverrideArg) displayName: Create Core_Root condition: and(succeeded(), ne(variables.runtimeFlavorName, 'Mono')) # Copy the runtime directory into the testhost folder to include OOBs. - script: "build.cmd -subset libs.pretest -configuration release -ci -arch $(archType) -testscope innerloop /p:RuntimeArtifactsPath=$(librariesDownloadDir)\\bin\\mono\\$(osGroup).$(archType).$(buildConfigUpper) /p:RuntimeFlavor=mono;xcopy $(Build.SourcesDirectory)\\artifacts\\bin\\runtime\\$(_Framework)-$(osGroup)-$(buildConfigUpper)-$(archType)\\* $(Build.SourcesDirectory)\\artifacts\\bin\\testhost\\$(_Framework)-$(osGroup)-$(buildConfigUpper)-$(archType)\\shared\\Microsoft.NETCore.App\\7.0.0 /E /I /Y;xcopy $(Build.SourcesDirectory)\\artifacts\\bin\\testhost\\$(_Framework)-$(osGroup)-$(buildConfigUpper)-$(archType)\\* $(Build.SourcesDirectory)\\.dotnet-mono /E /I /Y;copy $(Build.SourcesDirectory)\\artifacts\\bin\\coreclr\\$(osGroup).$(archType).$(buildConfigUpper)\\corerun.exe $(Build.SourcesDirectory)\\.dotnet-mono\\shared\\Microsoft.NETCore.App\\7.0.0\\corerun.exe" displayName: "Create mono dotnet (Windows)" condition: and(and(succeeded(), eq(variables.runtimeFlavorName, 'Mono')), eq(variables.osGroup, 'windows'), not(in('${{ parameters.runtimeType }}', 'AndroidMono', 'iOSMono'))) - script: "mkdir $(Build.SourcesDirectory)/.dotnet-mono;./build.sh -subset libs.pretest -configuration release -ci -arch $(archType) -testscope innerloop /p:RuntimeArtifactsPath=$(librariesDownloadDir)/bin/mono/$(osGroup).$(archType).$(buildConfigUpper) /p:RuntimeFlavor=mono;cp $(Build.SourcesDirectory)/artifacts/bin/runtime/$(_Framework)-$(osGroup)-$(buildConfigUpper)-$(archType)/* $(Build.SourcesDirectory)/artifacts/bin/testhost/$(_Framework)-$(osGroup)-$(buildConfigUpper)-$(archType)/shared/Microsoft.NETCore.App/7.0.0 -rf;cp $(Build.SourcesDirectory)/artifacts/bin/testhost/$(_Framework)-$(osGroup)-$(buildConfigUpper)-$(archType)/* $(Build.SourcesDirectory)/.dotnet-mono -r;cp $(Build.SourcesDirectory)/artifacts/bin/coreclr/$(osGroup).$(archType).$(buildConfigUpper)/corerun $(Build.SourcesDirectory)/.dotnet-mono/shared/Microsoft.NETCore.App/7.0.0/corerun" displayName: "Create mono dotnet (Linux)" condition: and(and(succeeded(), eq(variables.runtimeFlavorName, 'Mono')), ne(variables.osGroup, 'windows'), not(in('${{ parameters.runtimeType }}', 'AndroidMono', 'iOSMono')))
parameters: buildConfig: '' archType: '' osGroup: '' osSubgroup: '' container: '' runtimeVariant: '' framework: net7.0 # Specify the appropriate framework when running release branches (ie net6.0 for release/6.0) liveLibrariesBuildConfig: '' variables: {} runtimeType: 'coreclr' pool: '' codeGenType: 'JIT' projectFile: '' runKind: '' runJobTemplate: '/eng/pipelines/coreclr/templates/run-performance-job.yml' additionalSetupParameters: '' logicalMachine: '' pgoRunType: '' javascriptEngine: 'NoJS' iOSLlvmBuild: 'False' ### Perf job ### Each perf job depends on a corresponding build job with the same ### buildConfig and archType. jobs: - template: ${{ parameters.runJobTemplate }} parameters: # Compute job name from template parameters jobName: ${{ format('perfbuild_{0}{1}_{2}_{3}_{4}_{5}_{6}_{7}_{8}_{9}_{10}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig, parameters.runtimeType, parameters.codeGenType, parameters.runKind, parameters.logicalMachine, parameters.javascriptEngine, parameters.pgoRunType, parameters.iosLlvmBuild) }} displayName: ${{ format('Performance {0}{1} {2} {3} {4} {5} {6} {7} {8} {9} {10}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig, parameters.runtimeType, parameters.codeGenType, parameters.runKind, parameters.logicalMachine, parameters.javascriptEngine, parameters.pgoRunType, parameters.iosLlvmBuild) }} pool: ${{ parameters.pool }} buildConfig: ${{ parameters.buildConfig }} archType: ${{ parameters.archType }} osGroup: ${{ parameters.osGroup }} osSubgroup: ${{ parameters.osSubgroup }} runtimeVariant: ${{ parameters.runtimeVariant }} liveLibrariesBuildConfig: ${{ parameters.liveLibrariesBuildConfig }} runtimeType: ${{ parameters.runtimeType }} codeGenType: ${{ parameters.codeGenType }} projectFile: ${{ parameters.projectFile }} runKind: ${{ parameters.runKind }} additionalSetupParameters: ${{ parameters.additionalSetupParameters }} container: ${{ parameters.container }} logicalmachine: ${{ parameters.logicalmachine }} pgoRunType: ${{ parameters.pgoRunType }} javascriptEngine: ${{ parameters.javascriptEngine }} iosLlvmBuild: ${{ parameters.iosLlvmBuild }} # Test job depends on the corresponding build job dependsOn: - ${{ if not(in(parameters.runtimeType, 'AndroidMono', 'iOSMono')) }}: - ${{ format('coreclr_{0}_product_build_{1}{2}_{3}_{4}', parameters.runtimeVariant, parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig) }} - ${{ if ne(parameters.liveLibrariesBuildConfig, '') }}: - ${{ format('libraries_build_{0}{1}_{2}_{3}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveLibrariesBuildConfig) }} - ${{ if and(eq(parameters.runtimeType, 'mono'), ne(parameters.codeGenType, 'AOT')) }}: - ${{ format('mono_{0}_product_build_{1}{2}_{3}_{4}', parameters.runtimeVariant, parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig) }} - ${{ if eq(parameters.runtimeType, 'wasm')}}: - ${{ format('build_{0}{1}_{2}_{3}_{4}_{5}', 'Browser', '', 'wasm', 'Linux', parameters.buildConfig, parameters.runtimeType) }} - ${{ if and(eq(parameters.codeGenType, 'AOT'), ne(parameters.runtimeType, 'wasm'))}}: - ${{ format('build_{0}{1}_{2}_{3}_{4}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig, parameters.codeGenType) }} - ${{ if eq(parameters.runtimeType, 'AndroidMono')}}: - ${{ 'build_Android_arm64_release_AndroidMono' }} - ${{ 'Build_iOS_arm64_release_MACiOSAndroidMaui' }} - ${{ if eq(parameters.runtimeType, 'iOSMono')}}: - ${{ 'build_iOS_arm64_release_iOSMono' }} - ${{ 'Build_iOS_arm64_release_MACiOSAndroidMaui' }} ${{ if and(eq(parameters.osGroup, 'windows'), not(in(parameters.runtimeType, 'AndroidMono', 'iOSMono'))) }}: ${{ if eq(parameters.runtimeType, 'mono') }}: extraSetupParameters: -Architecture ${{ parameters.archType }} -MonoDotnet $(Build.SourcesDirectory)\.dotnet-mono ${{ if eq(parameters.runtimeType, 'coreclr') }}: extraSetupParameters: -CoreRootDirectory $(Build.SourcesDirectory)\artifacts\tests\coreclr\${{ parameters.osGroup }}.${{ parameters.archType }}.Release\Tests\Core_Root -Architecture ${{ parameters.archType }} ${{ if and(ne(parameters.osGroup, 'windows'), not(in(parameters.runtimeType, 'AndroidMono', 'iOSMono'))) }}: ${{ if and(eq(parameters.runtimeType, 'mono'), ne(parameters.codeGenType, 'AOT')) }}: extraSetupParameters: --architecture ${{ parameters.archType }} --monodotnet $(Build.SourcesDirectory)/.dotnet-mono ${{ if and(eq(parameters.runtimeType, 'wasm'), ne(parameters.codeGenType, 'AOT')) }}: extraSetupParameters: --architecture ${{ parameters.archType }} --wasm $(librariesDownloadDir)/bin/wasm --javascriptengine ${{ parameters.javascriptEngine }} ${{ if and(eq(parameters.runtimeType, 'wasm'), eq(parameters.codeGenType, 'AOT')) }}: extraSetupParameters: --architecture ${{ parameters.archType }} --wasm $(librariesDownloadDir)/bin/wasm --wasmaot --javascriptengine ${{ parameters.javascriptEngine }} ${{ if and(eq(parameters.codeGenType, 'AOT'), ne(parameters.runtimeType, 'wasm')) }}: extraSetupParameters: --architecture ${{ parameters.archType }} --monoaot $(librariesDownloadDir)/bin/aot ${{ if and(eq(parameters.runtimeType, 'coreclr'), ne(parameters.osSubGroup, '_musl')) }}: extraSetupParameters: --corerootdirectory $(Build.SourcesDirectory)/artifacts/tests/coreclr/${{ parameters.osGroup }}.${{ parameters.archType }}.Release/Tests/Core_Root --architecture ${{ parameters.archType }} ${{ if and(eq(parameters.runtimeType, 'coreclr'), eq(parameters.osSubGroup, '_musl')) }}: extraSetupParameters: --corerootdirectory $(Build.SourcesDirectory)/artifacts/tests/coreclr/${{ parameters.osGroup }}.${{ parameters.archType }}.Release/Tests/Core_Root --architecture ${{ parameters.archType }} --alpine ${{ if eq(parameters.runtimeType, 'AndroidMono') }}: extraSetupParameters: -Architecture ${{ parameters.archType }} -AndroidMono ${{ if eq(parameters.runtimeType, 'iosMono') }}: extraSetupParameters: -Architecture ${{ parameters.archType }} -iOSMono -iOSLlvmBuild:$${{ parameters.iOSLlvmBuild }} variables: ${{ parameters.variables }} frameworks: - ${{ parameters.framework }} steps: # Extra steps that will be passed to the performance template and run before sending the job to helix (all of which is done in the template) # Optionally download live-built libraries - ${{ if ne(parameters.liveLibrariesBuildConfig, '') }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(librariesDownloadDir) cleanUnpackFolder: false artifactFileName: '$(librariesBuildArtifactName)$(archiveExtension)' artifactName: '$(librariesBuildArtifactName)' displayName: 'live-built libraries' # Download coreclr - ${{ if not(in(parameters.runtimeType, 'AndroidMono', 'iOSMono')) }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(buildProductRootFolderPath) artifactFileName: '$(buildProductArtifactName)$(archiveExtension)' artifactName: '$(buildProductArtifactName)' displayName: 'Coreclr product build' # Download mono - ${{ if and(eq(parameters.runtimeType, 'mono'), ne(parameters.codeGenType, 'AOT')) }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(librariesDownloadDir)/bin/mono/$(osGroup).$(archType).$(buildConfigUpper) cleanUnpackFolder: false artifactFileName: 'MonoProduct__${{ parameters.runtimeVariant }}_$(osGroup)_$(archType)_$(buildConfig)$(archiveExtension)' artifactName: 'MonoProduct__${{ parameters.runtimeVariant }}_$(osGroup)_$(archType)_$(buildConfig)' displayName: 'Mono runtime' # Download wasm - ${{ if eq(parameters.runtimeType, 'wasm') }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(librariesDownloadDir)/BrowserWasm artifactFileName: BrowserWasm.zip artifactName: BrowserWasm displayName: BrowserWasm - script: "mkdir $(librariesDownloadDir)/bin/wasm;unzip -o $(librariesDownloadDir)/BrowserWasm/artifacts/packages/Release/Shipping/Microsoft.NETCore.App.Runtime.Mono.browser-wasm.7.0.0-ci.nupkg data/* runtimes/* -d $(librariesDownloadDir)/bin/wasm;cp src/mono/wasm/test-main.js $(librariesDownloadDir)/bin/wasm/test-main.js;find $(librariesDownloadDir)/bin/wasm -type f -exec chmod 664 {} \\;" displayName: "Create wasm directory (Linux)" # Download mono AOT - ${{ if and(eq(parameters.codeGenType, 'AOT'), ne(parameters.runtimeType, 'wasm')) }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(librariesDownloadDir)/LinuxMonoAOT artifactFileName: LinuxMonoAOT${{ parameters.archType }}.tar.gz artifactName: LinuxMonoAOT${{ parameters.archType }} displayName: AOT Mono Artifacts - script: "mkdir -p $(librariesDownloadDir)/bin/aot/sgen;mkdir -p $(librariesDownloadDir)/bin/aot/pack;cp -r $(librariesDownloadDir)/LinuxMonoAOT/artifacts/obj/mono/Linux.${{ parameters.archType }}.Release/mono/* $(librariesDownloadDir)/bin/aot/sgen;cp -r $(librariesDownloadDir)/LinuxMonoAOT/artifacts/bin/microsoft.netcore.app.runtime.linux-${{ parameters.archType }}/Release/* $(librariesDownloadDir)/bin/aot/pack" displayName: "Create aot directory (Linux)" # Download AndroidMono and MauiAndroid - ${{ if eq(parameters.runtimeType, 'AndroidMono')}}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory)/androidHelloWorld cleanUnpackFolder: false artifactFileName: 'AndroidMonoarm64.tar.gz' artifactName: 'AndroidMonoarm64' displayName: 'Mono Android HelloWorld' - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory) cleanUnpackFolder: false artifactFileName: 'MauiAndroidApp.tar.gz' artifactName: 'MauiAndroidApp' displayName: 'Maui Android App' # Download iOSMono tests and MauiiOS/MacCatalyst - ${{ if eq(parameters.runtimeType, 'iOSMono') }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory)/iosHelloWorld/nollvm cleanUnpackFolder: false artifactFileName: 'iOSSampleAppNoLLVM.tar.gz' artifactName: 'iOSSampleAppNoLLVM' displayName: 'iOS Sample App NoLLVM' - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory)/iosHelloWorld/llvm cleanUnpackFolder: false artifactFileName: 'iOSSampleAppLLVM.tar.gz' artifactName: 'iOSSampleAppLLVM' displayName: 'iOS Sample App LLVM' - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory)/MauiiOSDefaultIPA cleanUnpackFolder: false artifactFileName: 'MauiiOSDefaultIPA.tar.gz' artifactName: 'MauiiOSDefaultIPA' displayName: 'Maui iOS IPA' - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory)/MauiMacCatalystDefault cleanUnpackFolder: false artifactFileName: 'MauiMacCatalystDefault.tar.gz' artifactName: 'MauiMacCatalystDefault' displayName: 'Maui MacCatalyst App' # Create Core_Root - script: $(Build.SourcesDirectory)/src/tests/build$(scriptExt) $(buildConfig) $(archType) generatelayoutonly $(librariesOverrideArg) displayName: Create Core_Root condition: and(succeeded(), ne(variables.runtimeFlavorName, 'Mono')) # Copy the runtime directory into the testhost folder to include OOBs. - script: "build.cmd -subset libs.pretest -configuration release -ci -arch $(archType) -testscope innerloop /p:RuntimeArtifactsPath=$(librariesDownloadDir)\\bin\\mono\\$(osGroup).$(archType).$(buildConfigUpper) /p:RuntimeFlavor=mono;xcopy $(Build.SourcesDirectory)\\artifacts\\bin\\runtime\\$(_Framework)-$(osGroup)-$(buildConfigUpper)-$(archType)\\* $(Build.SourcesDirectory)\\artifacts\\bin\\testhost\\$(_Framework)-$(osGroup)-$(buildConfigUpper)-$(archType)\\shared\\Microsoft.NETCore.App\\7.0.0 /E /I /Y;xcopy $(Build.SourcesDirectory)\\artifacts\\bin\\testhost\\$(_Framework)-$(osGroup)-$(buildConfigUpper)-$(archType)\\* $(Build.SourcesDirectory)\\.dotnet-mono /E /I /Y;copy $(Build.SourcesDirectory)\\artifacts\\bin\\coreclr\\$(osGroup).$(archType).$(buildConfigUpper)\\corerun.exe $(Build.SourcesDirectory)\\.dotnet-mono\\shared\\Microsoft.NETCore.App\\7.0.0\\corerun.exe" displayName: "Create mono dotnet (Windows)" condition: and(and(succeeded(), eq(variables.runtimeFlavorName, 'Mono')), eq(variables.osGroup, 'windows'), not(in('${{ parameters.runtimeType }}', 'AndroidMono', 'iOSMono'))) - script: "mkdir $(Build.SourcesDirectory)/.dotnet-mono;./build.sh -subset libs.pretest -configuration release -ci -arch $(archType) -testscope innerloop /p:RuntimeArtifactsPath=$(librariesDownloadDir)/bin/mono/$(osGroup).$(archType).$(buildConfigUpper) /p:RuntimeFlavor=mono;cp $(Build.SourcesDirectory)/artifacts/bin/runtime/$(_Framework)-$(osGroup)-$(buildConfigUpper)-$(archType)/* $(Build.SourcesDirectory)/artifacts/bin/testhost/$(_Framework)-$(osGroup)-$(buildConfigUpper)-$(archType)/shared/Microsoft.NETCore.App/7.0.0 -rf;cp $(Build.SourcesDirectory)/artifacts/bin/testhost/$(_Framework)-$(osGroup)-$(buildConfigUpper)-$(archType)/* $(Build.SourcesDirectory)/.dotnet-mono -r;cp $(Build.SourcesDirectory)/artifacts/bin/coreclr/$(osGroup).$(archType).$(buildConfigUpper)/corerun $(Build.SourcesDirectory)/.dotnet-mono/shared/Microsoft.NETCore.App/7.0.0/corerun" displayName: "Create mono dotnet (Linux)" condition: and(and(succeeded(), eq(variables.runtimeFlavorName, 'Mono')), ne(variables.osGroup, 'windows'), not(in('${{ parameters.runtimeType }}', 'AndroidMono', 'iOSMono')))
1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/testing/performance/ios_scenarios.proj
<Project Sdk="Microsoft.DotNet.Helix.Sdk" DefaultTargets="Test"> <PropertyGroup Condition="'$(AGENT_OS)' != 'Windows_NT'"> <Python>python3</Python> <HelixPreCommands>$(HelixPreCommands);chmod +x $HELIX_WORKITEM_PAYLOAD/SOD/SizeOnDisk</HelixPreCommands> </PropertyGroup> <ItemGroup> <HelixCorrelationPayload Include="$(CorrelationPayloadDirectory)"> <PayloadDirectory>%(Identity)</PayloadDirectory> </HelixCorrelationPayload> </ItemGroup> <PropertyGroup> <LlvmPath>nollvm</LlvmPath> <LlvmPath Condition="'$(iOSLlvmBuild)' == 'True'">llvm</LlvmPath> </PropertyGroup> <PropertyGroup Condition="'$(AGENT_OS)' == 'Windows_NT'"> <ScenarioDirectory>%HELIX_CORRELATION_PAYLOAD%\performance\src\scenarios\</ScenarioDirectory> </PropertyGroup> <PropertyGroup Condition="'$(AGENT_OS)' != 'Windows_NT'"> <ScenarioDirectory>$HELIX_CORRELATION_PAYLOAD/performance/src/scenarios/</ScenarioDirectory> </PropertyGroup> <ItemGroup> <HelixWorkItem Include="SOD - iOS HelloWorld .app Size"> <PayloadDirectory>$(WorkItemDirectory)</PayloadDirectory> <PreCommands>cd $(ScenarioDirectory)helloios;xcopy %HELIX_CORRELATION_PAYLOAD%\iosHelloWorld\$(LlvmPath) .\app\/e;$(Python) pre.py</PreCommands> <Command>$(Python) test.py sod --scenario-name &quot;%(Identity)&quot;</Command> <PostCommands>$(Python) post.py</PostCommands> </HelixWorkItem> <HelixWorkItem Include="SOD - Maui iOS .app Size" Condition="'$(iOSLlvmBuild)' == 'False'"> <PayloadDirectory>$(WorkItemDirectory)</PayloadDirectory> <PreCommands>cd $(ScenarioDirectory)mauiios;xcopy %HELIX_CORRELATION_PAYLOAD%\MauiiOSDefault .\app\/e;$(Python) pre.py</PreCommands> <Command>$(Python) test.py sod --scenario-name &quot;%(Identity)&quot;</Command> <PostCommands>$(Python) post.py</PostCommands> </HelixWorkItem> <HelixWorkItem Include="SOD - Maui MacCatalyst .app Size" Condition="'$(iOSLlvmBuild)' == 'False'"> <PayloadDirectory>$(WorkItemDirectory)</PayloadDirectory> <PreCommands>cd $(ScenarioDirectory)mauiios;xcopy %HELIX_CORRELATION_PAYLOAD%\MauiMacCatalystDefault .\app\/e;$(Python) pre.py</PreCommands> <Command>$(Python) test.py sod --scenario-name &quot;%(Identity)&quot;</Command> <PostCommands>$(Python) post.py</PostCommands> </HelixWorkItem> </ItemGroup> </Project>
<Project Sdk="Microsoft.DotNet.Helix.Sdk" DefaultTargets="Test"> <PropertyGroup Condition="'$(AGENT_OS)' != 'Windows_NT'"> <Python>python3</Python> <HelixPreCommands>$(HelixPreCommands);chmod +x $HELIX_WORKITEM_PAYLOAD/SOD/SizeOnDisk</HelixPreCommands> </PropertyGroup> <ItemGroup> <HelixCorrelationPayload Include="$(CorrelationPayloadDirectory)"> <PayloadDirectory>%(Identity)</PayloadDirectory> </HelixCorrelationPayload> </ItemGroup> <PropertyGroup> <LlvmPath>nollvm</LlvmPath> <LlvmPath Condition="'$(iOSLlvmBuild)' == 'True'">llvm</LlvmPath> </PropertyGroup> <PropertyGroup Condition="'$(AGENT_OS)' == 'Windows_NT'"> <ScenarioDirectory>%HELIX_CORRELATION_PAYLOAD%\performance\src\scenarios\</ScenarioDirectory> </PropertyGroup> <PropertyGroup Condition="'$(AGENT_OS)' != 'Windows_NT'"> <ScenarioDirectory>$HELIX_CORRELATION_PAYLOAD/performance/src/scenarios/</ScenarioDirectory> </PropertyGroup> <ItemGroup> <HelixWorkItem Include="SOD - iOS HelloWorld .app Size"> <PayloadDirectory>$(WorkItemDirectory)</PayloadDirectory> <PreCommands>cd $(ScenarioDirectory)helloios;xcopy %HELIX_CORRELATION_PAYLOAD%\iosHelloWorld\$(LlvmPath) .\app/e/i;$(Python) pre.py --name app</PreCommands> <Command>$(Python) test.py sod --scenario-name &quot;%(Identity)&quot;</Command> <PostCommands>$(Python) post.py</PostCommands> </HelixWorkItem> <HelixWorkItem Include="SOD - Maui iOS IPA Size" Condition="'$(iOSLlvmBuild)' == 'False'"> <PayloadDirectory>$(WorkItemDirectory)</PayloadDirectory> <PreCommands>cd $(ScenarioDirectory)mauiios;copy %HELIX_CORRELATION_PAYLOAD%\MauiiOSDefaultIPA\MauiiOSDefault.ipa .;$(Python) pre.py --name MauiiOSDefault.ipa</PreCommands> <Command>$(Python) test.py sod --scenario-name &quot;%(Identity)&quot;</Command> <PostCommands>$(Python) post.py</PostCommands> </HelixWorkItem> <HelixWorkItem Include="SOD - Maui iOS IPA Size Unzipped" Condition="'$(iOSLlvmBuild)' == 'False'"> <PayloadDirectory>$(WorkItemDirectory)</PayloadDirectory> <PreCommands>cd $(ScenarioDirectory)mauiios;copy %HELIX_CORRELATION_PAYLOAD%\MauiiOSDefaultIPA\MauiiOSDefault.ipa .;$(Python) pre.py --unzip --name MauiiOSDefault.ipa</PreCommands> <Command>$(Python) test.py sod --scenario-name &quot;%(Identity)&quot;</Command> <PostCommands>$(Python) post.py</PostCommands> </HelixWorkItem> <HelixWorkItem Include="SOD - Maui MacCatalyst .app Size" Condition="'$(iOSLlvmBuild)' == 'False'"> <PayloadDirectory>$(WorkItemDirectory)</PayloadDirectory> <PreCommands>cd $(ScenarioDirectory)mauiios;xcopy %HELIX_CORRELATION_PAYLOAD%\MauiMacCatalystDefault .\app/e/i;$(Python) pre.py --name app</PreCommands> <Command>$(Python) test.py sod --scenario-name &quot;%(Identity)&quot;</Command> <PostCommands>$(Python) post.py</PostCommands> </HelixWorkItem> </ItemGroup> </Project>
1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/testing/performance/performance-setup.ps1
Param( [string] $SourceDirectory=$env:BUILD_SOURCESDIRECTORY, [string] $CoreRootDirectory, [string] $BaselineCoreRootDirectory, [string] $Architecture="x64", [string] $Framework="net5.0", [string] $CompilationMode="Tiered", [string] $Repository=$env:BUILD_REPOSITORY_NAME, [string] $Branch=$env:BUILD_SOURCEBRANCH, [string] $CommitSha=$env:BUILD_SOURCEVERSION, [string] $BuildNumber=$env:BUILD_BUILDNUMBER, [string] $RunCategories="Libraries Runtime", [string] $Csproj="src\benchmarks\micro\MicroBenchmarks.csproj", [string] $Kind="micro", [switch] $LLVM, [switch] $MonoInterpreter, [switch] $MonoAOT, [switch] $Internal, [switch] $Compare, [string] $MonoDotnet="", [string] $Configurations="CompilationMode=$CompilationMode RunKind=$Kind", [string] $LogicalMachine="", [switch] $AndroidMono, [switch] $iOSMono, [switch] $NoPGO, [switch] $DynamicPGO, [switch] $FullPGO, [switch] $iOSLlvmBuild, [string] $MauiVersion ) $RunFromPerformanceRepo = ($Repository -eq "dotnet/performance") -or ($Repository -eq "dotnet-performance") $UseCoreRun = ($CoreRootDirectory -ne [string]::Empty) $UseBaselineCoreRun = ($BaselineCoreRootDirectory -ne [string]::Empty) $PayloadDirectory = (Join-Path $SourceDirectory "Payload") $PerformanceDirectory = (Join-Path $PayloadDirectory "performance") $WorkItemDirectory = (Join-Path $SourceDirectory "workitem") $ExtraBenchmarkDotNetArguments = "--iterationCount 1 --warmupCount 0 --invocationCount 1 --unrollFactor 1 --strategy ColdStart --stopOnFirstError true" $Creator = $env:BUILD_DEFINITIONNAME $PerfLabArguments = "" $HelixSourcePrefix = "pr" $Queue = "" if ($Internal) { switch ($LogicalMachine) { "perftiger" { $Queue = "Windows.10.Amd64.19H1.Tiger.Perf" } "perfowl" { $Queue = "Windows.10.Amd64.20H2.Owl.Perf" } "perfsurf" { $Queue = "Windows.10.Arm64.Perf.Surf" } "perfpixel4a" { $Queue = "Windows.10.Amd64.Pixel.Perf" } Default { $Queue = "Windows.10.Amd64.19H1.Tiger.Perf" } } $PerfLabArguments = "--upload-to-perflab-container" $ExtraBenchmarkDotNetArguments = "" $Creator = "" $HelixSourcePrefix = "official" } else { $Queue = "Windows.10.Amd64.ClientRS4.DevEx.15.8.Open" } if($MonoInterpreter) { $ExtraBenchmarkDotNetArguments = "--category-exclusion-filter NoInterpreter" } if($MonoDotnet -ne "") { $Configurations += " LLVM=$LLVM MonoInterpreter=$MonoInterpreter MonoAOT=$MonoAOT" if($ExtraBenchmarkDotNetArguments -eq "") { #FIX ME: We need to block these tests as they don't run on mono for now $ExtraBenchmarkDotNetArguments = "--exclusion-filter *Perf_Image* *Perf_NamedPipeStream*" } else { #FIX ME: We need to block these tests as they don't run on mono for now $ExtraBenchmarkDotNetArguments += " --exclusion-filter *Perf_Image* *Perf_NamedPipeStream*" } } if($NoPGO) { $Configurations += " PGOType=nopgo" } elseif($DynamicPGO) { $Configurations += " PGOType=dynamicpgo" } elseif($FullPGO) { $Configurations += " PGOType=fullpgo" } if ($iOSMono) { $Configurations += " iOSLlvmBuild=$iOSLlvmBuild" } # FIX ME: This is a workaround until we get this from the actual pipeline $CleanedBranchName = "main" if($Branch.Contains("refs/heads/release")) { $CleanedBranchName = $Branch.replace('refs/heads/', '') } $CommonSetupArguments="--channel $CleanedBranchName --queue $Queue --build-number $BuildNumber --build-configs $Configurations --architecture $Architecture" $SetupArguments = "--repository https://github.com/$Repository --branch $Branch --get-perf-hash --commit-sha $CommitSha $CommonSetupArguments" if($NoPGO) { $SetupArguments = "$SetupArguments --no-pgo" } elseif($DynamicPGO) { $SetupArguments = "$SetupArguments --dynamic-pgo" } elseif($FullPGO) { $SetupArguments = "$SetupArguments --full-pgo" } if ($RunFromPerformanceRepo) { $SetupArguments = "--perf-hash $CommitSha $CommonSetupArguments" robocopy $SourceDirectory $PerformanceDirectory /E /XD $PayloadDirectory $SourceDirectory\artifacts $SourceDirectory\.git } else { git clone --branch main --depth 1 --quiet https://github.com/dotnet/performance $PerformanceDirectory } if($MonoDotnet -ne "") { $UsingMono = "true" $MonoDotnetPath = (Join-Path $PayloadDirectory "dotnet-mono") Move-Item -Path $MonoDotnet -Destination $MonoDotnetPath } if ($UseCoreRun) { $NewCoreRoot = (Join-Path $PayloadDirectory "Core_Root") Move-Item -Path $CoreRootDirectory -Destination $NewCoreRoot } if ($UseBaselineCoreRun) { $NewBaselineCoreRoot = (Join-Path $PayloadDirectory "Baseline_Core_Root") Move-Item -Path $BaselineCoreRootDirectory -Destination $NewBaselineCoreRoot } if($MauiVersion -ne "") { $SetupArguments = "$SetupArguments --maui-version $MauiVersion" } if ($AndroidMono) { if(!(Test-Path $WorkItemDirectory)) { mkdir $WorkItemDirectory } Copy-Item -path "$SourceDirectory\androidHelloWorld\HelloAndroid.apk" $PayloadDirectory -Verbose Copy-Item -path "$SourceDirectory\MauiAndroidDefault.apk" $PayloadDirectory -Verbose $SetupArguments = $SetupArguments -replace $Architecture, 'arm64' } if ($iOSMono) { if(!(Test-Path $WorkItemDirectory)) { mkdir $WorkItemDirectory } if($iOSLlvmBuild) { Copy-Item -path "$SourceDirectory\iosHelloWorld\llvm" $PayloadDirectory\iosHelloWorld\llvm -Recurse } else { Copy-Item -path "$SourceDirectory\iosHelloWorld\nollvm" $PayloadDirectory\iosHelloWorld\nollvm -Recurse Copy-Item -path "$SourceDirectory\MauiiOSDefault" $PayloadDirectory\MauiiOSDefault -Recurse Copy-Item -path "$SourceDirectory\MauiMacCatalystDefault" $PayloadDirectory\MauiMacCatalystDefault -Recurse } $SetupArguments = $SetupArguments -replace $Architecture, 'arm64' } $DocsDir = (Join-Path $PerformanceDirectory "docs") robocopy $DocsDir $WorkItemDirectory # Set variables that we will need to have in future steps $ci = $true . "$PSScriptRoot\..\..\common\pipeline-logging-functions.ps1" # Directories Write-PipelineSetVariable -Name 'PayloadDirectory' -Value "$PayloadDirectory" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'PerformanceDirectory' -Value "$PerformanceDirectory" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'WorkItemDirectory' -Value "$WorkItemDirectory" -IsMultiJobVariable $false # Script Arguments Write-PipelineSetVariable -Name 'Python' -Value "py -3" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'ExtraBenchmarkDotNetArguments' -Value "$ExtraBenchmarkDotNetArguments" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'SetupArguments' -Value "$SetupArguments" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'PerfLabArguments' -Value "$PerfLabArguments" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'BDNCategories' -Value "$RunCategories" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'TargetCsproj' -Value "$Csproj" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'Kind' -Value "$Kind" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'Architecture' -Value "$Architecture" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'UseCoreRun' -Value "$UseCoreRun" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'UseBaselineCoreRun' -Value "$UseBaselineCoreRun" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'RunFromPerfRepo' -Value "$RunFromPerformanceRepo" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'Compare' -Value "$Compare" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'MonoDotnet' -Value "$UsingMono" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'iOSLlvmBuild' -Value "$iOSLlvmBuild" -IsMultiJobVariable $false # Helix Arguments Write-PipelineSetVariable -Name 'Creator' -Value "$Creator" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'Queue' -Value "$Queue" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'HelixSourcePrefix' -Value "$HelixSourcePrefix" -IsMultiJobVariable $false Write-PipelineSetVariable -Name '_BuildConfig' -Value "$Architecture.$Kind.$Framework" -IsMultiJobVariable $false exit 0
Param( [string] $SourceDirectory=$env:BUILD_SOURCESDIRECTORY, [string] $CoreRootDirectory, [string] $BaselineCoreRootDirectory, [string] $Architecture="x64", [string] $Framework="net5.0", [string] $CompilationMode="Tiered", [string] $Repository=$env:BUILD_REPOSITORY_NAME, [string] $Branch=$env:BUILD_SOURCEBRANCH, [string] $CommitSha=$env:BUILD_SOURCEVERSION, [string] $BuildNumber=$env:BUILD_BUILDNUMBER, [string] $RunCategories="Libraries Runtime", [string] $Csproj="src\benchmarks\micro\MicroBenchmarks.csproj", [string] $Kind="micro", [switch] $LLVM, [switch] $MonoInterpreter, [switch] $MonoAOT, [switch] $Internal, [switch] $Compare, [string] $MonoDotnet="", [string] $Configurations="CompilationMode=$CompilationMode RunKind=$Kind", [string] $LogicalMachine="", [switch] $AndroidMono, [switch] $iOSMono, [switch] $NoPGO, [switch] $DynamicPGO, [switch] $FullPGO, [switch] $iOSLlvmBuild, [string] $MauiVersion ) $RunFromPerformanceRepo = ($Repository -eq "dotnet/performance") -or ($Repository -eq "dotnet-performance") $UseCoreRun = ($CoreRootDirectory -ne [string]::Empty) $UseBaselineCoreRun = ($BaselineCoreRootDirectory -ne [string]::Empty) $PayloadDirectory = (Join-Path $SourceDirectory "Payload") $PerformanceDirectory = (Join-Path $PayloadDirectory "performance") $WorkItemDirectory = (Join-Path $SourceDirectory "workitem") $ExtraBenchmarkDotNetArguments = "--iterationCount 1 --warmupCount 0 --invocationCount 1 --unrollFactor 1 --strategy ColdStart --stopOnFirstError true" $Creator = $env:BUILD_DEFINITIONNAME $PerfLabArguments = "" $HelixSourcePrefix = "pr" $Queue = "" if ($Internal) { switch ($LogicalMachine) { "perftiger" { $Queue = "Windows.10.Amd64.19H1.Tiger.Perf" } "perfowl" { $Queue = "Windows.10.Amd64.20H2.Owl.Perf" } "perfsurf" { $Queue = "Windows.10.Arm64.Perf.Surf" } "perfpixel4a" { $Queue = "Windows.10.Amd64.Pixel.Perf" } Default { $Queue = "Windows.10.Amd64.19H1.Tiger.Perf" } } $PerfLabArguments = "--upload-to-perflab-container" $ExtraBenchmarkDotNetArguments = "" $Creator = "" $HelixSourcePrefix = "official" } else { $Queue = "Windows.10.Amd64.ClientRS4.DevEx.15.8.Open" } if($MonoInterpreter) { $ExtraBenchmarkDotNetArguments = "--category-exclusion-filter NoInterpreter" } if($MonoDotnet -ne "") { $Configurations += " LLVM=$LLVM MonoInterpreter=$MonoInterpreter MonoAOT=$MonoAOT" if($ExtraBenchmarkDotNetArguments -eq "") { #FIX ME: We need to block these tests as they don't run on mono for now $ExtraBenchmarkDotNetArguments = "--exclusion-filter *Perf_Image* *Perf_NamedPipeStream*" } else { #FIX ME: We need to block these tests as they don't run on mono for now $ExtraBenchmarkDotNetArguments += " --exclusion-filter *Perf_Image* *Perf_NamedPipeStream*" } } if($NoPGO) { $Configurations += " PGOType=nopgo" } elseif($DynamicPGO) { $Configurations += " PGOType=dynamicpgo" } elseif($FullPGO) { $Configurations += " PGOType=fullpgo" } if ($iOSMono) { $Configurations += " iOSLlvmBuild=$iOSLlvmBuild" } # FIX ME: This is a workaround until we get this from the actual pipeline $CleanedBranchName = "main" if($Branch.Contains("refs/heads/release")) { $CleanedBranchName = $Branch.replace('refs/heads/', '') } $CommonSetupArguments="--channel $CleanedBranchName --queue $Queue --build-number $BuildNumber --build-configs $Configurations --architecture $Architecture" $SetupArguments = "--repository https://github.com/$Repository --branch $Branch --get-perf-hash --commit-sha $CommitSha $CommonSetupArguments" if($NoPGO) { $SetupArguments = "$SetupArguments --no-pgo" } elseif($DynamicPGO) { $SetupArguments = "$SetupArguments --dynamic-pgo" } elseif($FullPGO) { $SetupArguments = "$SetupArguments --full-pgo" } if ($RunFromPerformanceRepo) { $SetupArguments = "--perf-hash $CommitSha $CommonSetupArguments" robocopy $SourceDirectory $PerformanceDirectory /E /XD $PayloadDirectory $SourceDirectory\artifacts $SourceDirectory\.git } else { git clone --branch main --depth 1 --quiet https://github.com/dotnet/performance $PerformanceDirectory } if($MonoDotnet -ne "") { $UsingMono = "true" $MonoDotnetPath = (Join-Path $PayloadDirectory "dotnet-mono") Move-Item -Path $MonoDotnet -Destination $MonoDotnetPath } if ($UseCoreRun) { $NewCoreRoot = (Join-Path $PayloadDirectory "Core_Root") Move-Item -Path $CoreRootDirectory -Destination $NewCoreRoot } if ($UseBaselineCoreRun) { $NewBaselineCoreRoot = (Join-Path $PayloadDirectory "Baseline_Core_Root") Move-Item -Path $BaselineCoreRootDirectory -Destination $NewBaselineCoreRoot } if($MauiVersion -ne "") { $SetupArguments = "$SetupArguments --maui-version $MauiVersion" } if ($AndroidMono) { if(!(Test-Path $WorkItemDirectory)) { mkdir $WorkItemDirectory } Copy-Item -path "$SourceDirectory\androidHelloWorld\HelloAndroid.apk" $PayloadDirectory -Verbose Copy-Item -path "$SourceDirectory\MauiAndroidDefault.apk" $PayloadDirectory -Verbose $SetupArguments = $SetupArguments -replace $Architecture, 'arm64' } if ($iOSMono) { if(!(Test-Path $WorkItemDirectory)) { mkdir $WorkItemDirectory } if($iOSLlvmBuild) { Copy-Item -path "$SourceDirectory\iosHelloWorld\llvm" $PayloadDirectory\iosHelloWorld\llvm -Recurse } else { Copy-Item -path "$SourceDirectory\iosHelloWorld\nollvm" $PayloadDirectory\iosHelloWorld\nollvm -Recurse Copy-Item -path "$SourceDirectory\MauiiOSDefaultIPA" $PayloadDirectory\MauiiOSDefaultIPA -Recurse Copy-Item -path "$SourceDirectory\MauiMacCatalystDefault\MauiMacCatalystDefault.app" $PayloadDirectory\MauiMacCatalystDefault -Recurse } $SetupArguments = $SetupArguments -replace $Architecture, 'arm64' } $DocsDir = (Join-Path $PerformanceDirectory "docs") robocopy $DocsDir $WorkItemDirectory # Set variables that we will need to have in future steps $ci = $true . "$PSScriptRoot\..\..\common\pipeline-logging-functions.ps1" # Directories Write-PipelineSetVariable -Name 'PayloadDirectory' -Value "$PayloadDirectory" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'PerformanceDirectory' -Value "$PerformanceDirectory" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'WorkItemDirectory' -Value "$WorkItemDirectory" -IsMultiJobVariable $false # Script Arguments Write-PipelineSetVariable -Name 'Python' -Value "py -3" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'ExtraBenchmarkDotNetArguments' -Value "$ExtraBenchmarkDotNetArguments" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'SetupArguments' -Value "$SetupArguments" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'PerfLabArguments' -Value "$PerfLabArguments" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'BDNCategories' -Value "$RunCategories" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'TargetCsproj' -Value "$Csproj" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'Kind' -Value "$Kind" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'Architecture' -Value "$Architecture" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'UseCoreRun' -Value "$UseCoreRun" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'UseBaselineCoreRun' -Value "$UseBaselineCoreRun" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'RunFromPerfRepo' -Value "$RunFromPerformanceRepo" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'Compare' -Value "$Compare" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'MonoDotnet' -Value "$UsingMono" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'iOSLlvmBuild' -Value "$iOSLlvmBuild" -IsMultiJobVariable $false # Helix Arguments Write-PipelineSetVariable -Name 'Creator' -Value "$Creator" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'Queue' -Value "$Queue" -IsMultiJobVariable $false Write-PipelineSetVariable -Name 'HelixSourcePrefix' -Value "$HelixSourcePrefix" -IsMultiJobVariable $false Write-PipelineSetVariable -Name '_BuildConfig' -Value "$Architecture.$Kind.$Framework" -IsMultiJobVariable $false exit 0
1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/libraries/Common/tests/System/Net/Prerequisites/Deployment/setup_firewall.ps1
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the MIT license. #Requires -RunAsAdministrator # Firewall configuration $script:firewallGroup = "Libraries Testing" $script:firewallRules = @( @{Name = "LibariesNet - HTTP 80"; Port = 80}, @{Name = "LibrariesNet - HTTP 443"; Port = 443} ) Function InstallServerFirewall { Write-Host -ForegroundColor Cyan "Installing Firewall rules." foreach ($rule in $script:firewallRules) { Write-Host -ForegroundColor DarkGray "`t" $rule.Name New-NetFirewallRule -DisplayName $rule.Name -Group $script:firewallGroup -Direction Inbound -Protocol TCP -LocalPort $rule.Port -Action Allow | Out-Null } } Function RemoveServerFirewall { Write-Host -ForegroundColor Cyan "Removing Firewall rules." foreach ($rule in $script:firewallRules) { Write-Host -ForegroundColor DarkGray "`t" $rule.Name Remove-NetFirewallRule -DisplayName $rule.Name | Out-Null } }
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the MIT license. #Requires -RunAsAdministrator # Firewall configuration $script:firewallGroup = "Libraries Testing" $script:firewallRules = @( @{Name = "LibariesNet - HTTP 80"; Port = 80}, @{Name = "LibrariesNet - HTTP 443"; Port = 443} ) Function InstallServerFirewall { Write-Host -ForegroundColor Cyan "Installing Firewall rules." foreach ($rule in $script:firewallRules) { Write-Host -ForegroundColor DarkGray "`t" $rule.Name New-NetFirewallRule -DisplayName $rule.Name -Group $script:firewallGroup -Direction Inbound -Protocol TCP -LocalPort $rule.Port -Action Allow | Out-Null } } Function RemoveServerFirewall { Write-Host -ForegroundColor Cyan "Removing Firewall rules." foreach ($rule in $script:firewallRules) { Write-Host -ForegroundColor DarkGray "`t" $rule.Name Remove-NetFirewallRule -DisplayName $rule.Name | Out-Null } }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/libraries/System.IO.Ports/pkg/runtime.native.System.IO.Ports.proj
<Project Sdk="Microsoft.Build.NoTargets"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <IsPackable>true</IsPackable> <!-- Reference the outputs for the dependency nodes calculation. --> <NoTargetsDoNotReferenceOutputAssemblies>false</NoTargetsDoNotReferenceOutputAssemblies> <!-- This is a meta package and doesn't contain any libs. --> <NoWarn>$(NoWarn);NU5128</NoWarn> </PropertyGroup> <ItemGroup> <!-- Listing the runtime specific packages to populate the dependencies section. Not building these references to avoid unintentional Build/Pack invocations. They are filtered in the traversal build in oob-all.csproj based on the OutputRid. --> <ProjectReference Include="$(MSBuildThisFileDirectory)*.proj" Exclude="$(MSBuildProjectFile)" BuildReference="false" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.Build.NoTargets"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <IsPackable>true</IsPackable> <!-- Reference the outputs for the dependency nodes calculation. --> <NoTargetsDoNotReferenceOutputAssemblies>false</NoTargetsDoNotReferenceOutputAssemblies> <!-- This is a meta package and doesn't contain any libs. --> <NoWarn>$(NoWarn);NU5128</NoWarn> </PropertyGroup> <ItemGroup> <!-- Listing the runtime specific packages to populate the dependencies section. Not building these references to avoid unintentional Build/Pack invocations. They are filtered in the traversal build in oob-all.csproj based on the OutputRid. --> <ProjectReference Include="$(MSBuildThisFileDirectory)*.proj" Exclude="$(MSBuildProjectFile)" BuildReference="false" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/common/darc-init.ps1
param ( $darcVersion = $null, $versionEndpoint = 'https://maestro-prod.westus2.cloudapp.azure.com/api/assets/darc-version?api-version=2019-01-16', $verbosity = 'minimal', $toolpath = $null ) . $PSScriptRoot\tools.ps1 function InstallDarcCli ($darcVersion, $toolpath) { $darcCliPackageName = 'microsoft.dotnet.darc' $dotnetRoot = InitializeDotNetCli -install:$true $dotnet = "$dotnetRoot\dotnet.exe" $toolList = & "$dotnet" tool list -g if ($toolList -like "*$darcCliPackageName*") { & "$dotnet" tool uninstall $darcCliPackageName -g } # If the user didn't explicitly specify the darc version, # query the Maestro API for the correct version of darc to install. if (-not $darcVersion) { $darcVersion = $(Invoke-WebRequest -Uri $versionEndpoint -UseBasicParsing).Content } $arcadeServicesSource = 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json' Write-Host "Installing Darc CLI version $darcVersion..." Write-Host 'You may need to restart your command window if this is the first dotnet tool you have installed.' if (-not $toolpath) { Write-Host "'$dotnet' tool install $darcCliPackageName --version $darcVersion --add-source '$arcadeServicesSource' -v $verbosity -g" & "$dotnet" tool install $darcCliPackageName --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity -g }else { Write-Host "'$dotnet' tool install $darcCliPackageName --version $darcVersion --add-source '$arcadeServicesSource' -v $verbosity --tool-path '$toolpath'" & "$dotnet" tool install $darcCliPackageName --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity --tool-path "$toolpath" } } try { InstallDarcCli $darcVersion $toolpath } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Category 'Darc' -Message $_ ExitWithExitCode 1 }
param ( $darcVersion = $null, $versionEndpoint = 'https://maestro-prod.westus2.cloudapp.azure.com/api/assets/darc-version?api-version=2019-01-16', $verbosity = 'minimal', $toolpath = $null ) . $PSScriptRoot\tools.ps1 function InstallDarcCli ($darcVersion, $toolpath) { $darcCliPackageName = 'microsoft.dotnet.darc' $dotnetRoot = InitializeDotNetCli -install:$true $dotnet = "$dotnetRoot\dotnet.exe" $toolList = & "$dotnet" tool list -g if ($toolList -like "*$darcCliPackageName*") { & "$dotnet" tool uninstall $darcCliPackageName -g } # If the user didn't explicitly specify the darc version, # query the Maestro API for the correct version of darc to install. if (-not $darcVersion) { $darcVersion = $(Invoke-WebRequest -Uri $versionEndpoint -UseBasicParsing).Content } $arcadeServicesSource = 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json' Write-Host "Installing Darc CLI version $darcVersion..." Write-Host 'You may need to restart your command window if this is the first dotnet tool you have installed.' if (-not $toolpath) { Write-Host "'$dotnet' tool install $darcCliPackageName --version $darcVersion --add-source '$arcadeServicesSource' -v $verbosity -g" & "$dotnet" tool install $darcCliPackageName --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity -g }else { Write-Host "'$dotnet' tool install $darcCliPackageName --version $darcVersion --add-source '$arcadeServicesSource' -v $verbosity --tool-path '$toolpath'" & "$dotnet" tool install $darcCliPackageName --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity --tool-path "$toolpath" } } try { InstallDarcCli $darcVersion $toolpath } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Category 'Darc' -Message $_ ExitWithExitCode 1 }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/pipelines/coreclr/ci.yml
trigger: batch: true branches: include: - release/*.* paths: include: - '*' - src/libraries/System.Private.CoreLib/* exclude: - .github/* - docs/* - CODE-OF-CONDUCT.md - CONTRIBUTING.md - LICENSE.TXT - PATENTS.TXT - README.md - SECURITY.md - THIRD-PARTY-NOTICES.TXT - src/installer/* - src/libraries/* - eng/pipelines/installer/* - eng/pipelines/libraries/* - eng/pipelines/runtime.yml schedules: - cron: "0 9,18,1 * * *" # run at 9:00, 18:00 and 01:00 (UTC) which is 2:00, 11:00 and 18:00 (PST). displayName: runtime-coreclr-outerloop default schedule branches: include: - main always: false # run only if there were changes since the last successful scheduled run. jobs: # # Debug builds # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/coreclr/templates/build-job.yml buildConfig: debug platforms: - Linux_arm - Linux_arm64 - Linux_musl_arm64 - Linux_musl_x64 - Linux_x64 - OSX_arm64 - OSX_x64 - windows_arm - windows_arm64 jobParameters: testGroup: outerloop # # Checked builds # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/coreclr/templates/build-job.yml buildConfig: checked platformGroup: all platforms: # It is too early to include OSX_arm64 in platform group all # Adding it here will enable it also - OSX_arm64 jobParameters: testGroup: outerloop # # Release builds # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/coreclr/templates/build-job.yml buildConfig: release platforms: - Linux_arm - Linux_musl_arm64 - Linux_x64 - OSX_arm64 - OSX_x64 - windows_x86 jobParameters: testGroup: outerloop # # Release library builds # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/libraries/build-job.yml buildConfig: Release platformGroup: all platforms: # It is too early to include OSX_arm64 in platform group all # Adding it here will enable it also - OSX_arm64 jobParameters: isOfficialBuild: false liveRuntimeBuildConfig: checked # # Checked test builds # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/build-test-job.yml buildConfig: checked platforms: - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 testGroup: outerloop # # Checked JIT test runs # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml buildConfig: checked platformGroup: all platforms: # It is too early to include OSX_arm64 in platform group all # Adding it here will enable it to also run this test - OSX_arm64 helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: testGroup: outerloop liveLibrariesBuildConfig: Release # # Checked R2R test runs # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml buildConfig: checked platforms: - Linux_arm64 - Linux_musl_x64 - Linux_musl_arm64 - Linux_x64 - OSX_x64 - windows_x64 - windows_x86 - windows_arm - windows_arm64 helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: testGroup: outerloop readyToRun: true crossgen2: true displayNameArgs: R2R_CG2 liveLibrariesBuildConfig: Release # # Formatting # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/coreclr/templates/format-job.yml platforms: - Linux_x64 - windows_x64
trigger: batch: true branches: include: - release/*.* paths: include: - '*' - src/libraries/System.Private.CoreLib/* exclude: - .github/* - docs/* - CODE-OF-CONDUCT.md - CONTRIBUTING.md - LICENSE.TXT - PATENTS.TXT - README.md - SECURITY.md - THIRD-PARTY-NOTICES.TXT - src/installer/* - src/libraries/* - eng/pipelines/installer/* - eng/pipelines/libraries/* - eng/pipelines/runtime.yml schedules: - cron: "0 9,18,1 * * *" # run at 9:00, 18:00 and 01:00 (UTC) which is 2:00, 11:00 and 18:00 (PST). displayName: runtime-coreclr-outerloop default schedule branches: include: - main always: false # run only if there were changes since the last successful scheduled run. jobs: # # Debug builds # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/coreclr/templates/build-job.yml buildConfig: debug platforms: - Linux_arm - Linux_arm64 - Linux_musl_arm64 - Linux_musl_x64 - Linux_x64 - OSX_arm64 - OSX_x64 - windows_arm - windows_arm64 jobParameters: testGroup: outerloop # # Checked builds # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/coreclr/templates/build-job.yml buildConfig: checked platformGroup: all platforms: # It is too early to include OSX_arm64 in platform group all # Adding it here will enable it also - OSX_arm64 jobParameters: testGroup: outerloop # # Release builds # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/coreclr/templates/build-job.yml buildConfig: release platforms: - Linux_arm - Linux_musl_arm64 - Linux_x64 - OSX_arm64 - OSX_x64 - windows_x86 jobParameters: testGroup: outerloop # # Release library builds # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/libraries/build-job.yml buildConfig: Release platformGroup: all platforms: # It is too early to include OSX_arm64 in platform group all # Adding it here will enable it also - OSX_arm64 jobParameters: isOfficialBuild: false liveRuntimeBuildConfig: checked # # Checked test builds # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/build-test-job.yml buildConfig: checked platforms: - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 testGroup: outerloop # # Checked JIT test runs # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml buildConfig: checked platformGroup: all platforms: # It is too early to include OSX_arm64 in platform group all # Adding it here will enable it to also run this test - OSX_arm64 helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: testGroup: outerloop liveLibrariesBuildConfig: Release # # Checked R2R test runs # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml buildConfig: checked platforms: - Linux_arm64 - Linux_musl_x64 - Linux_musl_arm64 - Linux_x64 - OSX_x64 - windows_x64 - windows_x86 - windows_arm - windows_arm64 helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: testGroup: outerloop readyToRun: true crossgen2: true displayNameArgs: R2R_CG2 liveLibrariesBuildConfig: Release # # Formatting # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/coreclr/templates/format-job.yml platforms: - Linux_x64 - windows_x64
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/pipelines/mono/templates/xplat-pipeline-job.yml
parameters: buildConfig: '' archType: '' osGroup: '' osSubgroup: '' name: '' helixType: '(unspecified)' container: '' liveLibrariesBuildConfig: '' strategy: '' pool: '' runtimeVariant: '' liveRuntimeBuildConfig: 'release' # arcade-specific parameters condition: true continueOnError: false dependsOn: '' dependOnEvaluatePaths: false displayName: '' timeoutInMinutes: '' enableMicrobuild: '' gatherAssetManifests: false variables: {} ## any extra variables to add to the defaults defined below jobs: - template: /eng/pipelines/common/templates/runtimes/xplat-job.yml parameters: buildConfig: ${{ parameters.buildConfig }} archType: ${{ parameters.archType }} osGroup: ${{ parameters.osGroup }} osSubgroup: ${{ parameters.osSubgroup }} name: ${{ parameters.name }} helixType: ${{ parameters.helixType }} container: ${{ parameters.container }} strategy: ${{ parameters.strategy }} pool: ${{ parameters.pool }} runtimeVariant: ${{ parameters.runtimeVariant }} # arcade-specific parameters condition: and(succeeded(), ${{ parameters.condition }}) continueOnError: ${{ parameters.continueOnError }} dependsOn: ${{ parameters.dependsOn }} dependOnEvaluatePaths: ${{ parameters.dependOnEvaluatePaths }} displayName: ${{ parameters.displayName }} timeoutInMinutes: ${{ parameters.timeoutInMinutes }} enableMicrobuild: ${{ parameters.enableMicrobuild }} gatherAssetManifests: ${{ parameters.gatherAssetManifests }} variables: - name: coreClrProductArtifactName value: 'CoreCLRProduct___$(osGroup)$(osSubgroup)_$(archType)_${{ parameters.liveRuntimeBuildConfig }}' - name: coreClrProductRootFolderPath value: '$(Build.SourcesDirectory)/artifacts/bin/coreclr/$(osGroup).$(archType).$(liveRuntimeBuildConfigUpper)' - name: buildProductArtifactName value: 'MonoProduct__${{ parameters.runtimeVariant }}_$(osGroup)$(osSubgroup)_$(archType)_$(buildConfig)' # minijit and monointerpreter do not use seperate product builds. - ${{ if or(eq(parameters.runtimeVariant, 'minijit'), eq(parameters.runtimeVariant, 'monointerpreter')) }}: - name : buildProductArtifactName value : 'MonoProduct___$(osGroup)$(osSubgroup)_$(archType)_$(buildConfig)' - ${{ if eq(parameters.runtimeVariant, 'llvmfullaot') }}: - name : buildProductArtifactName value : 'MonoProduct__llvmaot_$(osGroup)$(osSubgroup)_$(archType)_$(buildConfig)' - name: binTestsPath value: '$(Build.SourcesDirectory)/artifacts/tests/coreclr' - name: buildProductRootFolderPath value: '$(Build.SourcesDirectory)/artifacts/bin/mono/$(osGroup).$(archType).$(buildConfigUpper)' - name: managedTestArtifactRootFolderPath value: '$(binTestsPath)/$(osGroup).$(archType).$(buildConfigUpper)' - name: managedGenericTestArtifactName value: 'MonoManagedTestArtifacts_AnyOS_AnyCPU_$(buildConfig)' - name: microsoftNetSdkIlFolderPath value: '$(Build.SourcesDirectory)/.packages/microsoft.net.sdk.il' - name: microsoftNetSdkIlArtifactName value: 'MicrosoftNetSdkIlPackage_AnyOS_AnyCPU_$(buildConfig)' - name: monoRepoRoot value: '$(Build.SourcesDirectory)/src/mono' - name: nativeTestArtifactName value: 'CoreCLRNativeTestArtifacts_$(osGroup)$(osSubgroup)_$(archType)_$(buildConfig)' - name: nativeTestArtifactRootFolderPath value: '$(binTestsPath)/obj/$(osGroup).$(archType).$(buildConfigUpper)' - name: workloadPackagesPath value: $(Build.SourcesDirectory)/artifacts/workloadPackages - name: workloadArtifactsPath value: $(Build.SourcesDirectory)/artifacts/workloads - name: liveRuntimeBuildConfigUpper ${{ if eq(parameters.liveRuntimeBuildConfig, 'release') }}: value: 'Release' ${{ if eq(parameters.liveRuntimeBuildConfig, 'checked') }}: value: 'Checked' ${{ if eq(parameters.liveRuntimeBuildConfig, 'debug') }}: value: 'Debug' - name: priorityArg value: '' - librariesBuildArtifactName: '' - librariesOverrideArg: '' - librariesDownloadDir: '' - ${{ if ne(parameters.liveLibrariesBuildConfig, '') }}: - librariesBuildArtifactName: ${{ format('libraries_bin_{0}{1}_{2}_{3}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveLibrariesBuildConfig) }} - librariesDownloadDir: $(Build.SourcesDirectory)/artifacts - librariesOverrideArg: ' /p:LibrariesConfiguration=${{ parameters.liveLibrariesBuildConfig }}' - ${{ each variable in parameters.variables }}: - ${{insert}}: ${{ variable }} steps: ${{ parameters.steps }}
parameters: buildConfig: '' archType: '' osGroup: '' osSubgroup: '' name: '' helixType: '(unspecified)' container: '' liveLibrariesBuildConfig: '' strategy: '' pool: '' runtimeVariant: '' liveRuntimeBuildConfig: 'release' # arcade-specific parameters condition: true continueOnError: false dependsOn: '' dependOnEvaluatePaths: false displayName: '' timeoutInMinutes: '' enableMicrobuild: '' gatherAssetManifests: false variables: {} ## any extra variables to add to the defaults defined below jobs: - template: /eng/pipelines/common/templates/runtimes/xplat-job.yml parameters: buildConfig: ${{ parameters.buildConfig }} archType: ${{ parameters.archType }} osGroup: ${{ parameters.osGroup }} osSubgroup: ${{ parameters.osSubgroup }} name: ${{ parameters.name }} helixType: ${{ parameters.helixType }} container: ${{ parameters.container }} strategy: ${{ parameters.strategy }} pool: ${{ parameters.pool }} runtimeVariant: ${{ parameters.runtimeVariant }} # arcade-specific parameters condition: and(succeeded(), ${{ parameters.condition }}) continueOnError: ${{ parameters.continueOnError }} dependsOn: ${{ parameters.dependsOn }} dependOnEvaluatePaths: ${{ parameters.dependOnEvaluatePaths }} displayName: ${{ parameters.displayName }} timeoutInMinutes: ${{ parameters.timeoutInMinutes }} enableMicrobuild: ${{ parameters.enableMicrobuild }} gatherAssetManifests: ${{ parameters.gatherAssetManifests }} variables: - name: coreClrProductArtifactName value: 'CoreCLRProduct___$(osGroup)$(osSubgroup)_$(archType)_${{ parameters.liveRuntimeBuildConfig }}' - name: coreClrProductRootFolderPath value: '$(Build.SourcesDirectory)/artifacts/bin/coreclr/$(osGroup).$(archType).$(liveRuntimeBuildConfigUpper)' - name: buildProductArtifactName value: 'MonoProduct__${{ parameters.runtimeVariant }}_$(osGroup)$(osSubgroup)_$(archType)_$(buildConfig)' # minijit and monointerpreter do not use seperate product builds. - ${{ if or(eq(parameters.runtimeVariant, 'minijit'), eq(parameters.runtimeVariant, 'monointerpreter')) }}: - name : buildProductArtifactName value : 'MonoProduct___$(osGroup)$(osSubgroup)_$(archType)_$(buildConfig)' - ${{ if eq(parameters.runtimeVariant, 'llvmfullaot') }}: - name : buildProductArtifactName value : 'MonoProduct__llvmaot_$(osGroup)$(osSubgroup)_$(archType)_$(buildConfig)' - name: binTestsPath value: '$(Build.SourcesDirectory)/artifacts/tests/coreclr' - name: buildProductRootFolderPath value: '$(Build.SourcesDirectory)/artifacts/bin/mono/$(osGroup).$(archType).$(buildConfigUpper)' - name: managedTestArtifactRootFolderPath value: '$(binTestsPath)/$(osGroup).$(archType).$(buildConfigUpper)' - name: managedGenericTestArtifactName value: 'MonoManagedTestArtifacts_AnyOS_AnyCPU_$(buildConfig)' - name: microsoftNetSdkIlFolderPath value: '$(Build.SourcesDirectory)/.packages/microsoft.net.sdk.il' - name: microsoftNetSdkIlArtifactName value: 'MicrosoftNetSdkIlPackage_AnyOS_AnyCPU_$(buildConfig)' - name: monoRepoRoot value: '$(Build.SourcesDirectory)/src/mono' - name: nativeTestArtifactName value: 'CoreCLRNativeTestArtifacts_$(osGroup)$(osSubgroup)_$(archType)_$(buildConfig)' - name: nativeTestArtifactRootFolderPath value: '$(binTestsPath)/obj/$(osGroup).$(archType).$(buildConfigUpper)' - name: workloadPackagesPath value: $(Build.SourcesDirectory)/artifacts/workloadPackages - name: workloadArtifactsPath value: $(Build.SourcesDirectory)/artifacts/workloads - name: liveRuntimeBuildConfigUpper ${{ if eq(parameters.liveRuntimeBuildConfig, 'release') }}: value: 'Release' ${{ if eq(parameters.liveRuntimeBuildConfig, 'checked') }}: value: 'Checked' ${{ if eq(parameters.liveRuntimeBuildConfig, 'debug') }}: value: 'Debug' - name: priorityArg value: '' - librariesBuildArtifactName: '' - librariesOverrideArg: '' - librariesDownloadDir: '' - ${{ if ne(parameters.liveLibrariesBuildConfig, '') }}: - librariesBuildArtifactName: ${{ format('libraries_bin_{0}{1}_{2}_{3}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveLibrariesBuildConfig) }} - librariesDownloadDir: $(Build.SourcesDirectory)/artifacts - librariesOverrideArg: ' /p:LibrariesConfiguration=${{ parameters.liveLibrariesBuildConfig }}' - ${{ each variable in parameters.variables }}: - ${{insert}}: ${{ variable }} steps: ${{ parameters.steps }}
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/pipelines/common/variables.yml
variables: # These values enable longer delays, configurable number of retries, and special understanding of TCP hang-up # See https://github.com/NuGet/Home/issues/11027 for details - name: NUGET_ENABLE_EXPERIMENTAL_HTTP_RETRY value: true - name: NUGET_EXPERIMENTAL_MAX_NETWORK_TRY_COUNT value: 6 - name: NUGET_EXPERIMENTAL_NETWORK_RETRY_DELAY_MILLISECONDS value: 1000 - name: isOfficialBuild value: ${{ and(eq(variables['System.TeamProject'], 'internal'), eq(variables['Build.DefinitionName'], 'dotnet-runtime-official')) }} - name: isRollingBuild value: ${{ ne(variables['Build.Reason'], 'PullRequest') }} - name: isExtraPlatformsBuild value: ${{ eq(variables['Build.DefinitionName'], 'runtime-extra-platforms') }} - name: isNotExtraPlatformsBuild value: ${{ ne(variables['Build.DefinitionName'], 'runtime-extra-platforms') }} - name: isWasmOnlyBuild value: ${{ eq(variables['Build.DefinitionName'], 'runtime-wasm') }} - name: isRunSmokeTestsOnly value: ${{ and(ne(variables['Build.DefinitionName'], 'runtime-extra-platforms'), ne(variables['Build.DefinitionName'], 'runtime-wasm')) }} - name: isNotSpecificPlatformOnlyBuild value: ${{ ne(variables['Build.DefinitionName'], 'runtime-wasm') }} # We only run evaluate paths on runtime, runtime-staging and runtime-community pipelines on PRs # keep in sync with /eng/pipelines/common/xplat-setup.yml - name: dependOnEvaluatePaths value: ${{ and(eq(variables['Build.Reason'], 'PullRequest'), in(variables['Build.DefinitionName'], 'runtime', 'runtime-staging', 'runtime-community', 'runtime-extra-platforms')) }} - name: debugOnPrReleaseOnRolling ${{ if ne(variables['Build.Reason'], 'PullRequest') }}: value: Release ${{ if eq(variables['Build.Reason'], 'PullRequest') }}: value: Debug
variables: # These values enable longer delays, configurable number of retries, and special understanding of TCP hang-up # See https://github.com/NuGet/Home/issues/11027 for details - name: NUGET_ENABLE_EXPERIMENTAL_HTTP_RETRY value: true - name: NUGET_EXPERIMENTAL_MAX_NETWORK_TRY_COUNT value: 6 - name: NUGET_EXPERIMENTAL_NETWORK_RETRY_DELAY_MILLISECONDS value: 1000 - name: isOfficialBuild value: ${{ and(eq(variables['System.TeamProject'], 'internal'), eq(variables['Build.DefinitionName'], 'dotnet-runtime-official')) }} - name: isRollingBuild value: ${{ ne(variables['Build.Reason'], 'PullRequest') }} - name: isExtraPlatformsBuild value: ${{ eq(variables['Build.DefinitionName'], 'runtime-extra-platforms') }} - name: isNotExtraPlatformsBuild value: ${{ ne(variables['Build.DefinitionName'], 'runtime-extra-platforms') }} - name: isWasmOnlyBuild value: ${{ eq(variables['Build.DefinitionName'], 'runtime-wasm') }} - name: isRunSmokeTestsOnly value: ${{ and(ne(variables['Build.DefinitionName'], 'runtime-extra-platforms'), ne(variables['Build.DefinitionName'], 'runtime-wasm')) }} - name: isNotSpecificPlatformOnlyBuild value: ${{ ne(variables['Build.DefinitionName'], 'runtime-wasm') }} # We only run evaluate paths on runtime, runtime-staging and runtime-community pipelines on PRs # keep in sync with /eng/pipelines/common/xplat-setup.yml - name: dependOnEvaluatePaths value: ${{ and(eq(variables['Build.Reason'], 'PullRequest'), in(variables['Build.DefinitionName'], 'runtime', 'runtime-staging', 'runtime-community', 'runtime-extra-platforms')) }} - name: debugOnPrReleaseOnRolling ${{ if ne(variables['Build.Reason'], 'PullRequest') }}: value: Release ${{ if eq(variables['Build.Reason'], 'PullRequest') }}: value: Debug
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/pipelines/libraries/outerloop.yml
trigger: none schedules: - cron: "0 11 * * *" # 11 AM UTC => 3 AM PST displayName: Outerloop scheduled build branches: include: - main - release/*.* variables: - template: variables.yml jobs: # # CoreCLR Build # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/coreclr/templates/build-job.yml buildConfig: release platforms: - ${{ if eq(variables['includeWindowsOuterloop'], true) }}: - windows_x64 - windows_x86 - ${{ if eq(variables['includeLinuxOuterloop'], true) }}: - Linux_x64 - Linux_musl_x64 - ${{ if eq(variables['isRollingBuild'], true) }}: - Linux_arm - Linux_arm64 - Linux_musl_arm64 - ${{ if eq(variables['includeOsxOuterloop'], true) }}: - OSX_arm64 - OSX_x64 jobParameters: testGroup: innerloop # # Libraries Build # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/libraries/build-job.yml buildConfig: Release platforms: - ${{ if eq(variables['includeWindowsOuterloop'], true) }}: - windows_x86 - ${{ if eq(variables['isRollingBuild'], true) }}: - windows_x64 - ${{ if eq(variables['includeLinuxOuterloop'], true) }}: - ${{ if eq(variables['isRollingBuild'], true) }}: - Linux_x64 - Linux_arm - Linux_arm64 - Linux_musl_x64 - Linux_musl_arm64 - ${{ if and(eq(variables['includeOsxOuterloop'], true), eq(variables['isRollingBuild'], true)) }}: - OSX_arm64 - OSX_x64 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: isOfficialBuild: ${{ variables['isOfficialBuild'] }} includeAllPlatforms: ${{ variables['isRollingBuild'] }} runTests: true testScope: outerloop liveRuntimeBuildConfig: release - ${{ if eq(variables['isRollingBuild'], false) }}: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/libraries/build-job.yml buildConfig: Debug platforms: - ${{ if eq(variables['includeWindowsOuterloop'], true) }}: - windows_x64 - ${{ if eq(variables['includeLinuxOuterloop'], true) }}: - Linux_x64 - Linux_musl_x64 - ${{ if eq(variables['includeOsxOuterloop'], true) }}: - OSX_arm64 - OSX_x64 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: isOfficialBuild: ${{ variables['isOfficialBuild'] }} includeAllPlatforms: ${{ variables['isRollingBuild'] }} runTests: true testScope: outerloop liveRuntimeBuildConfig: release - ${{ if eq(variables['includeWindowsOuterloop'], true) }}: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/libraries/build-job.yml buildConfig: Release platforms: - windows_x86 - ${{ if eq(variables['isRollingBuild'], true) }}: - windows_x64 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: isOfficialBuild: ${{ variables['isOfficialBuild'] }} includeAllPlatforms: ${{ variables['isRollingBuild'] }} framework: net48 runTests: true testScope: outerloop
trigger: none schedules: - cron: "0 11 * * *" # 11 AM UTC => 3 AM PST displayName: Outerloop scheduled build branches: include: - main - release/*.* variables: - template: variables.yml jobs: # # CoreCLR Build # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/coreclr/templates/build-job.yml buildConfig: release platforms: - ${{ if eq(variables['includeWindowsOuterloop'], true) }}: - windows_x64 - windows_x86 - ${{ if eq(variables['includeLinuxOuterloop'], true) }}: - Linux_x64 - Linux_musl_x64 - ${{ if eq(variables['isRollingBuild'], true) }}: - Linux_arm - Linux_arm64 - Linux_musl_arm64 - ${{ if eq(variables['includeOsxOuterloop'], true) }}: - OSX_arm64 - OSX_x64 jobParameters: testGroup: innerloop # # Libraries Build # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/libraries/build-job.yml buildConfig: Release platforms: - ${{ if eq(variables['includeWindowsOuterloop'], true) }}: - windows_x86 - ${{ if eq(variables['isRollingBuild'], true) }}: - windows_x64 - ${{ if eq(variables['includeLinuxOuterloop'], true) }}: - ${{ if eq(variables['isRollingBuild'], true) }}: - Linux_x64 - Linux_arm - Linux_arm64 - Linux_musl_x64 - Linux_musl_arm64 - ${{ if and(eq(variables['includeOsxOuterloop'], true), eq(variables['isRollingBuild'], true)) }}: - OSX_arm64 - OSX_x64 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: isOfficialBuild: ${{ variables['isOfficialBuild'] }} includeAllPlatforms: ${{ variables['isRollingBuild'] }} runTests: true testScope: outerloop liveRuntimeBuildConfig: release - ${{ if eq(variables['isRollingBuild'], false) }}: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/libraries/build-job.yml buildConfig: Debug platforms: - ${{ if eq(variables['includeWindowsOuterloop'], true) }}: - windows_x64 - ${{ if eq(variables['includeLinuxOuterloop'], true) }}: - Linux_x64 - Linux_musl_x64 - ${{ if eq(variables['includeOsxOuterloop'], true) }}: - OSX_arm64 - OSX_x64 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: isOfficialBuild: ${{ variables['isOfficialBuild'] }} includeAllPlatforms: ${{ variables['isRollingBuild'] }} runTests: true testScope: outerloop liveRuntimeBuildConfig: release - ${{ if eq(variables['includeWindowsOuterloop'], true) }}: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/libraries/build-job.yml buildConfig: Release platforms: - windows_x86 - ${{ if eq(variables['isRollingBuild'], true) }}: - windows_x64 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: isOfficialBuild: ${{ variables['isOfficialBuild'] }} includeAllPlatforms: ${{ variables['isRollingBuild'] }} framework: net48 runTests: true testScope: outerloop
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/common/templates/steps/publish-logs.yml
parameters: StageLabel: '' JobLabel: '' steps: - task: Powershell@2 displayName: Prepare Binlogs to Upload inputs: targetType: inline script: | New-Item -ItemType Directory $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ Move-Item -Path $(Build.SourcesDirectory)/artifacts/log/Debug/* $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ continueOnError: true condition: always() - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)/PostBuildLogs' PublishLocation: Container ArtifactName: PostBuildLogs continueOnError: true condition: always()
parameters: StageLabel: '' JobLabel: '' steps: - task: Powershell@2 displayName: Prepare Binlogs to Upload inputs: targetType: inline script: | New-Item -ItemType Directory $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ Move-Item -Path $(Build.SourcesDirectory)/artifacts/log/Debug/* $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ continueOnError: true condition: always() - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)/PostBuildLogs' PublishLocation: Container ArtifactName: PostBuildLogs continueOnError: true condition: always()
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/pipelines/common/templates/wasm-library-aot-tests.yml
parameters: alwaysRun: false extraBuildArgs: '' extraHelixArgs: '' isExtraPlatformsBuild: false nameSuffix: '' platforms: [] runAOT: false runSmokeOnlyArg: '' jobs: # # Build for Browser/wasm, with EnableAggressiveTrimming=true # - template: /eng/pipelines/common/templates/wasm-library-tests.yml parameters: platforms: ${{ parameters.platforms }} nameSuffix: ${{ parameters.nameSuffix }} isExtraPlatforms: ${{ parameters.isExtraPlatformsBuild }} extraBuildArgs: /p:EnableAggressiveTrimming=true /p:BuildAOTTestsOnHelix=true /p:RunAOTCompilation=${{ parameters.runAOT }} ${{ parameters.extraBuildArgs }} extraHelixArgs: /p:NeedsToBuildWasmAppsOnHelix=true ${{ parameters.extraHelixArgs }} alwaysRun: ${{ parameters.alwaysRun }} runSmokeOnlyArg: $(_runSmokeTestsOnlyArg)
parameters: alwaysRun: false extraBuildArgs: '' extraHelixArgs: '' isExtraPlatformsBuild: false nameSuffix: '' platforms: [] runAOT: false runSmokeOnlyArg: '' jobs: # # Build for Browser/wasm, with EnableAggressiveTrimming=true # - template: /eng/pipelines/common/templates/wasm-library-tests.yml parameters: platforms: ${{ parameters.platforms }} nameSuffix: ${{ parameters.nameSuffix }} isExtraPlatforms: ${{ parameters.isExtraPlatformsBuild }} extraBuildArgs: /p:EnableAggressiveTrimming=true /p:BuildAOTTestsOnHelix=true /p:RunAOTCompilation=${{ parameters.runAOT }} ${{ parameters.extraBuildArgs }} extraHelixArgs: /p:NeedsToBuildWasmAppsOnHelix=true ${{ parameters.extraHelixArgs }} alwaysRun: ${{ parameters.alwaysRun }} runSmokeOnlyArg: $(_runSmokeTestsOnlyArg)
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/pipelines/coreclr/templates/superpmi-send-to-helix.yml
# Please remember to update the documentation if you make changes to these parameters! parameters: HelixSource: 'pr/default' # required -- sources must start with pr/, official/, prodcon/, or agent/ HelixType: 'tests/default/' # required -- Helix telemetry which identifies what type of data this is; should include "test" for clarity and must end in '/' HelixBuild: $(Build.BuildNumber) # required -- the build number Helix will use to identify this -- automatically set to the AzDO build number HelixTargetQueues: '' # required -- semicolon delimited list of Helix queues to test on; see https://helix.dot.net/ for a list of queues HelixAccessToken: '' # required -- access token to make Helix API requests; should be provided by the appropriate variable group HelixPreCommands: '' # optional -- commands to run before Helix work item execution HelixPostCommands: '' # optional -- commands to run after Helix work item execution WorkItemDirectory: '' # optional -- a payload directory to zip up and send to Helix; requires WorkItemCommand; incompatible with XUnitProjects CorrelationPayloadDirectory: '' # optional -- a directory to zip up and send to Helix as a correlation payload IncludeDotNetCli: false # optional -- true will download a version of the .NET CLI onto the Helix machine as a correlation payload; requires DotNetCliPackageType and DotNetCliVersion DotNetCliPackageType: '' # optional -- either 'sdk' or 'runtime'; determines whether the sdk or runtime will be sent to Helix; see https://raw.githubusercontent.com/dotnet/core/master/release-notes/releases.json DotNetCliVersion: '' # optional -- version of the CLI to send to Helix; based on this: https://raw.githubusercontent.com/dotnet/core/master/release-notes/releases.json EnableXUnitReporter: false # optional -- true enables XUnit result reporting to Mission Control WaitForWorkItemCompletion: true # optional -- true will make the task wait until work items have been completed and fail the build if work items fail. False is "fire and forget." Creator: '' # optional -- if the build is external, use this to specify who is sending the job DisplayNamePrefix: 'Send job to Helix' # optional -- rename the beginning of the displayName of the steps in AzDO condition: succeeded() # optional -- condition for step to execute; defaults to succeeded() continueOnError: false # optional -- determines whether to continue the build if the step errors; defaults to false BuildConfig: 'checked' # optional -- Mostly, superpmi will be run on checked builds InputArtifacts: '' CollectionType: '' CollectionName: '' ProjectFile: '' steps: - template: /eng/pipelines/common/templates/runtimes/send-to-helix-inner-step.yml parameters: osGroup: ${{ parameters.osGroup }} sendParams: $(Build.SourcesDirectory)/src/coreclr/scripts/${{ parameters.ProjectFile }} /restore /t:Test /bl:$(Build.SourcesDirectory)/artifacts/log/$(BuildConfig)/SendToHelix.binlog displayName: ${{ parameters.DisplayNamePrefix }} condition: ${{ parameters.condition }} shouldContinueOnError: ${{ parameters.continueOnError }} environment: MchFileTag: $(MchFileTag) BuildConfig: ${{ parameters.BuildConfig }} InputArtifacts: ${{ parameters.InputArtifacts }} CollectionType: ${{ parameters.CollectionType }} CollectionName: ${{ parameters.CollectionName }} HelixSource: ${{ parameters.HelixSource }} HelixType: ${{ parameters.HelixType }} HelixBuild: ${{ parameters.HelixBuild }} HelixTargetQueues: ${{ parameters.HelixTargetQueues }} HelixAccessToken: ${{ parameters.HelixAccessToken }} HelixPreCommands: ${{ parameters.HelixPreCommands }} HelixPostCommands: ${{ parameters.HelixPostCommands }} WorkItemDirectory: ${{ parameters.WorkItemDirectory }} CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} DotNetCliVersion: ${{ parameters.DotNetCliVersion }} EnableXUnitReporter: ${{ parameters.EnableXUnitReporter }} WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} Creator: ${{ parameters.Creator }} SYSTEM_ACCESSTOKEN: $(System.AccessToken)
# Please remember to update the documentation if you make changes to these parameters! parameters: HelixSource: 'pr/default' # required -- sources must start with pr/, official/, prodcon/, or agent/ HelixType: 'tests/default/' # required -- Helix telemetry which identifies what type of data this is; should include "test" for clarity and must end in '/' HelixBuild: $(Build.BuildNumber) # required -- the build number Helix will use to identify this -- automatically set to the AzDO build number HelixTargetQueues: '' # required -- semicolon delimited list of Helix queues to test on; see https://helix.dot.net/ for a list of queues HelixAccessToken: '' # required -- access token to make Helix API requests; should be provided by the appropriate variable group HelixPreCommands: '' # optional -- commands to run before Helix work item execution HelixPostCommands: '' # optional -- commands to run after Helix work item execution WorkItemDirectory: '' # optional -- a payload directory to zip up and send to Helix; requires WorkItemCommand; incompatible with XUnitProjects CorrelationPayloadDirectory: '' # optional -- a directory to zip up and send to Helix as a correlation payload IncludeDotNetCli: false # optional -- true will download a version of the .NET CLI onto the Helix machine as a correlation payload; requires DotNetCliPackageType and DotNetCliVersion DotNetCliPackageType: '' # optional -- either 'sdk' or 'runtime'; determines whether the sdk or runtime will be sent to Helix; see https://raw.githubusercontent.com/dotnet/core/master/release-notes/releases.json DotNetCliVersion: '' # optional -- version of the CLI to send to Helix; based on this: https://raw.githubusercontent.com/dotnet/core/master/release-notes/releases.json EnableXUnitReporter: false # optional -- true enables XUnit result reporting to Mission Control WaitForWorkItemCompletion: true # optional -- true will make the task wait until work items have been completed and fail the build if work items fail. False is "fire and forget." Creator: '' # optional -- if the build is external, use this to specify who is sending the job DisplayNamePrefix: 'Send job to Helix' # optional -- rename the beginning of the displayName of the steps in AzDO condition: succeeded() # optional -- condition for step to execute; defaults to succeeded() continueOnError: false # optional -- determines whether to continue the build if the step errors; defaults to false BuildConfig: 'checked' # optional -- Mostly, superpmi will be run on checked builds InputArtifacts: '' CollectionType: '' CollectionName: '' ProjectFile: '' steps: - template: /eng/pipelines/common/templates/runtimes/send-to-helix-inner-step.yml parameters: osGroup: ${{ parameters.osGroup }} sendParams: $(Build.SourcesDirectory)/src/coreclr/scripts/${{ parameters.ProjectFile }} /restore /t:Test /bl:$(Build.SourcesDirectory)/artifacts/log/$(BuildConfig)/SendToHelix.binlog displayName: ${{ parameters.DisplayNamePrefix }} condition: ${{ parameters.condition }} shouldContinueOnError: ${{ parameters.continueOnError }} environment: MchFileTag: $(MchFileTag) BuildConfig: ${{ parameters.BuildConfig }} InputArtifacts: ${{ parameters.InputArtifacts }} CollectionType: ${{ parameters.CollectionType }} CollectionName: ${{ parameters.CollectionName }} HelixSource: ${{ parameters.HelixSource }} HelixType: ${{ parameters.HelixType }} HelixBuild: ${{ parameters.HelixBuild }} HelixTargetQueues: ${{ parameters.HelixTargetQueues }} HelixAccessToken: ${{ parameters.HelixAccessToken }} HelixPreCommands: ${{ parameters.HelixPreCommands }} HelixPostCommands: ${{ parameters.HelixPostCommands }} WorkItemDirectory: ${{ parameters.WorkItemDirectory }} CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} DotNetCliVersion: ${{ parameters.DotNetCliVersion }} EnableXUnitReporter: ${{ parameters.EnableXUnitReporter }} WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} Creator: ${{ parameters.Creator }} SYSTEM_ACCESSTOKEN: $(System.AccessToken)
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/pipelines/libraries/helix.yml
parameters: runtimeFlavor: '' archType: '' buildConfig: '' creator: '' helixQueues: '' osGroup: '' targetRid: '' testRunNamePrefixSuffix: '' testScope: 'innerloop' # innerloop | outerloop | all interpreter: '' condition: always() extraHelixArguments: '' shouldContinueOnError: false scenarios: '' steps: - script: $(_msbuildCommand) $(_warnAsErrorParamHelixOverride) -restore $(Build.SourcesDirectory)/src/libraries/sendtohelix.proj /p:RuntimeFlavor=${{ parameters.runtimeFlavor }} /p:TargetArchitecture=${{ parameters.archType }} /p:TargetRuntimeIdentifier=${{ parameters.targetRid }} /p:Configuration=${{ parameters.buildConfig }} /p:TargetOS=${{ parameters.osGroup }} /p:MonoForceInterpreter=${{ parameters.interpreter }} /p:TestScope=${{ parameters.testScope }} /p:TestRunNamePrefixSuffix=${{ parameters.testRunNamePrefixSuffix }} /p:HelixBuild=$(Build.BuildNumber) ${{ parameters.extraHelixArguments }} /bl:$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/SendToHelix.binlog displayName: Send to Helix condition: and(succeeded(), ${{ parameters.condition }}) continueOnError: ${{ eq(parameters.shouldContinueOnError, true) }} env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) # We need to set this env var to publish helix results to Azure Dev Ops _Scenarios: ${{ join(',', parameters.scenarios) }} # Pass scenarios to MSBuild as env var to avoid need of escaping comma separated list ${{ if eq(variables['System.TeamProject'], 'internal') }}: HelixAccessToken: $(HelixApiAccessToken) HelixTargetQueues: ${{ replace(lower(join('+', parameters.helixQueues)), '.open', '') }} Creator: '' ${{ if eq(variables['System.TeamProject'], 'public') }}: HelixTargetQueues: ${{ join('+', parameters.helixQueues) }} Creator: ${{ parameters.creator }}
parameters: runtimeFlavor: '' archType: '' buildConfig: '' creator: '' helixQueues: '' osGroup: '' targetRid: '' testRunNamePrefixSuffix: '' testScope: 'innerloop' # innerloop | outerloop | all interpreter: '' condition: always() extraHelixArguments: '' shouldContinueOnError: false scenarios: '' steps: - script: $(_msbuildCommand) $(_warnAsErrorParamHelixOverride) -restore $(Build.SourcesDirectory)/src/libraries/sendtohelix.proj /p:RuntimeFlavor=${{ parameters.runtimeFlavor }} /p:TargetArchitecture=${{ parameters.archType }} /p:TargetRuntimeIdentifier=${{ parameters.targetRid }} /p:Configuration=${{ parameters.buildConfig }} /p:TargetOS=${{ parameters.osGroup }} /p:MonoForceInterpreter=${{ parameters.interpreter }} /p:TestScope=${{ parameters.testScope }} /p:TestRunNamePrefixSuffix=${{ parameters.testRunNamePrefixSuffix }} /p:HelixBuild=$(Build.BuildNumber) ${{ parameters.extraHelixArguments }} /bl:$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/SendToHelix.binlog displayName: Send to Helix condition: and(succeeded(), ${{ parameters.condition }}) continueOnError: ${{ eq(parameters.shouldContinueOnError, true) }} env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) # We need to set this env var to publish helix results to Azure Dev Ops _Scenarios: ${{ join(',', parameters.scenarios) }} # Pass scenarios to MSBuild as env var to avoid need of escaping comma separated list ${{ if eq(variables['System.TeamProject'], 'internal') }}: HelixAccessToken: $(HelixApiAccessToken) HelixTargetQueues: ${{ replace(lower(join('+', parameters.helixQueues)), '.open', '') }} Creator: '' ${{ if eq(variables['System.TeamProject'], 'public') }}: HelixTargetQueues: ${{ join('+', parameters.helixQueues) }} Creator: ${{ parameters.creator }}
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/common/templates/post-build/setup-maestro-vars.yml
parameters: BARBuildId: '' PromoteToChannelIds: '' steps: - ${{ if eq(coalesce(parameters.PromoteToChannelIds, 0), 0) }}: - task: DownloadBuildArtifacts@0 displayName: Download Release Configs inputs: buildType: current artifactName: ReleaseConfigs checkDownloadedFiles: true - task: PowerShell@2 name: setReleaseVars displayName: Set Release Configs Vars inputs: targetType: inline pwsh: true script: | try { if (!$Env:PromoteToMaestroChannels -or $Env:PromoteToMaestroChannels.Trim() -eq '') { $Content = Get-Content $(Build.StagingDirectory)/ReleaseConfigs/ReleaseConfigs.txt $BarId = $Content | Select -Index 0 $Channels = $Content | Select -Index 1 $IsStableBuild = $Content | Select -Index 2 $AzureDevOpsProject = $Env:System_TeamProject $AzureDevOpsBuildDefinitionId = $Env:System_DefinitionId $AzureDevOpsBuildId = $Env:Build_BuildId } else { $buildApiEndpoint = "${Env:MaestroApiEndPoint}/api/builds/${Env:BARBuildId}?api-version=${Env:MaestroApiVersion}" $apiHeaders = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]' $apiHeaders.Add('Accept', 'application/json') $apiHeaders.Add('Authorization',"Bearer ${Env:MAESTRO_API_TOKEN}") $buildInfo = try { Invoke-WebRequest -Method Get -Uri $buildApiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } $BarId = $Env:BARBuildId $Channels = $Env:PromoteToMaestroChannels -split "," $Channels = $Channels -join "][" $Channels = "[$Channels]" $IsStableBuild = $buildInfo.stable $AzureDevOpsProject = $buildInfo.azureDevOpsProject $AzureDevOpsBuildDefinitionId = $buildInfo.azureDevOpsBuildDefinitionId $AzureDevOpsBuildId = $buildInfo.azureDevOpsBuildId } Write-Host "##vso[task.setvariable variable=BARBuildId]$BarId" Write-Host "##vso[task.setvariable variable=TargetChannels]$Channels" Write-Host "##vso[task.setvariable variable=IsStableBuild]$IsStableBuild" Write-Host "##vso[task.setvariable variable=AzDOProjectName]$AzureDevOpsProject" Write-Host "##vso[task.setvariable variable=AzDOPipelineId]$AzureDevOpsBuildDefinitionId" Write-Host "##vso[task.setvariable variable=AzDOBuildId]$AzureDevOpsBuildId" } catch { Write-Host $_ Write-Host $_.Exception Write-Host $_.ScriptStackTrace exit 1 } env: MAESTRO_API_TOKEN: $(MaestroApiAccessToken) BARBuildId: ${{ parameters.BARBuildId }} PromoteToMaestroChannels: ${{ parameters.PromoteToChannelIds }}
parameters: BARBuildId: '' PromoteToChannelIds: '' steps: - ${{ if eq(coalesce(parameters.PromoteToChannelIds, 0), 0) }}: - task: DownloadBuildArtifacts@0 displayName: Download Release Configs inputs: buildType: current artifactName: ReleaseConfigs checkDownloadedFiles: true - task: PowerShell@2 name: setReleaseVars displayName: Set Release Configs Vars inputs: targetType: inline pwsh: true script: | try { if (!$Env:PromoteToMaestroChannels -or $Env:PromoteToMaestroChannels.Trim() -eq '') { $Content = Get-Content $(Build.StagingDirectory)/ReleaseConfigs/ReleaseConfigs.txt $BarId = $Content | Select -Index 0 $Channels = $Content | Select -Index 1 $IsStableBuild = $Content | Select -Index 2 $AzureDevOpsProject = $Env:System_TeamProject $AzureDevOpsBuildDefinitionId = $Env:System_DefinitionId $AzureDevOpsBuildId = $Env:Build_BuildId } else { $buildApiEndpoint = "${Env:MaestroApiEndPoint}/api/builds/${Env:BARBuildId}?api-version=${Env:MaestroApiVersion}" $apiHeaders = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]' $apiHeaders.Add('Accept', 'application/json') $apiHeaders.Add('Authorization',"Bearer ${Env:MAESTRO_API_TOKEN}") $buildInfo = try { Invoke-WebRequest -Method Get -Uri $buildApiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } $BarId = $Env:BARBuildId $Channels = $Env:PromoteToMaestroChannels -split "," $Channels = $Channels -join "][" $Channels = "[$Channels]" $IsStableBuild = $buildInfo.stable $AzureDevOpsProject = $buildInfo.azureDevOpsProject $AzureDevOpsBuildDefinitionId = $buildInfo.azureDevOpsBuildDefinitionId $AzureDevOpsBuildId = $buildInfo.azureDevOpsBuildId } Write-Host "##vso[task.setvariable variable=BARBuildId]$BarId" Write-Host "##vso[task.setvariable variable=TargetChannels]$Channels" Write-Host "##vso[task.setvariable variable=IsStableBuild]$IsStableBuild" Write-Host "##vso[task.setvariable variable=AzDOProjectName]$AzureDevOpsProject" Write-Host "##vso[task.setvariable variable=AzDOPipelineId]$AzureDevOpsBuildDefinitionId" Write-Host "##vso[task.setvariable variable=AzDOBuildId]$AzureDevOpsBuildId" } catch { Write-Host $_ Write-Host $_.Exception Write-Host $_.ScriptStackTrace exit 1 } env: MAESTRO_API_TOKEN: $(MaestroApiAccessToken) BARBuildId: ${{ parameters.BARBuildId }} PromoteToMaestroChannels: ${{ parameters.PromoteToChannelIds }}
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/pipelines/coreclr/jit-experimental.yml
trigger: none schedules: - cron: "0 22 * * 0,6" displayName: Sun at 2:00 PM (UTC-8:00) branches: include: - main always: true jobs: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/build-coreclr-and-libraries-job.yml buildConfig: checked platforms: - OSX_arm64 - OSX_x64 - Linux_arm64 - Linux_x64 - windows_arm64 - windows_x64 - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: jit-experimental - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/build-test-job.yml buildConfig: checked platforms: - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: jit-experimental - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml buildConfig: checked platforms: - OSX_arm64 - OSX_x64 - Linux_arm64 - Linux_x64 - windows_arm64 - windows_x64 helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: testGroup: jit-experimental liveLibrariesBuildConfig: Release
trigger: none schedules: - cron: "0 22 * * 0,6" displayName: Sun at 2:00 PM (UTC-8:00) branches: include: - main always: true jobs: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/build-coreclr-and-libraries-job.yml buildConfig: checked platforms: - OSX_arm64 - OSX_x64 - Linux_arm64 - Linux_x64 - windows_arm64 - windows_x64 - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: jit-experimental - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/build-test-job.yml buildConfig: checked platforms: - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: jit-experimental - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml buildConfig: checked platforms: - OSX_arm64 - OSX_x64 - Linux_arm64 - Linux_x64 - windows_arm64 - windows_x64 helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: testGroup: jit-experimental liveLibrariesBuildConfig: Release
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/coreclr/.nuget/Microsoft.NETCore.ILAsm/Microsoft.NETCore.ILAsm.proj
<Project Sdk="Microsoft.Build.Traversal"> <ItemGroup> <!-- identity project, runtime specific projects are included by props above --> <Project Include="$(MSBuildProjectName).pkgproj" /> </ItemGroup> <Import Project="$([MSBuild]::GetPathOfFileAbove(builds.targets))" /> </Project>
<Project Sdk="Microsoft.Build.Traversal"> <ItemGroup> <!-- identity project, runtime specific projects are included by props above --> <Project Include="$(MSBuildProjectName).pkgproj" /> </ItemGroup> <Import Project="$([MSBuild]::GetPathOfFileAbove(builds.targets))" /> </Project>
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/pipelines/coreclr/templates/perf-send-to-helix.yml
# Please remember to update the documentation if you make changes to these parameters! parameters: ProjectFile: '' # required -- project file that specifies the helix workitems HelixSource: 'pr/default' # required -- sources must start with pr/, official/, prodcon/, or agent/ HelixType: 'tests/default/' # required -- Helix telemetry which identifies what type of data this is; should include "test" for clarity and must end in '/' HelixBuild: $(Build.BuildNumber) # required -- the build number Helix will use to identify this -- automatically set to the AzDO build number HelixTargetQueues: '' # required -- semicolon delimited list of Helix queues to test on; see https://helix.dot.net/ for a list of queues HelixAccessToken: '' # required -- access token to make Helix API requests; should be provided by the appropriate variable group HelixPreCommands: '' # optional -- commands to run before Helix work item execution HelixPostCommands: '' # optional -- commands to run after Helix work item execution WorkItemDirectory: '' # optional -- a payload directory to zip up and send to Helix; requires WorkItemCommand; incompatible with XUnitProjects CorrelationPayloadDirectory: '' # optional -- a directory to zip up and send to Helix as a correlation payload IncludeDotNetCli: false # optional -- true will download a version of the .NET CLI onto the Helix machine as a correlation payload; requires DotNetCliPackageType and DotNetCliVersion DotNetCliPackageType: '' # optional -- either 'sdk', 'runtime' or 'aspnetcore-runtime'; determines whether the sdk or runtime will be sent to Helix; see https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases.json DotNetCliVersion: '' # optional -- version of the CLI to send to Helix; based on this: https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases.json EnableXUnitReporter: false # optional -- true enables XUnit result reporting to Mission Control WaitForWorkItemCompletion: true # optional -- true will make the task wait until work items have been completed and fail the build if work items fail. False is "fire and forget." Creator: '' # optional -- if the build is external, use this to specify who is sending the job DisplayNamePrefix: 'Send job to Helix' # optional -- rename the beginning of the displayName of the steps in AzDO condition: succeeded() # optional -- condition for step to execute; defaults to succeeded() continueOnError: false # optional -- determines whether to continue the build if the step errors; defaults to false osGroup: '' # required -- operating system for the job steps: - template: /eng/pipelines/common/templates/runtimes/send-to-helix-inner-step.yml parameters: osGroup: ${{ parameters.osGroup }} sendParams: $(Build.SourcesDirectory)/eng/testing/performance/${{ parameters.ProjectFile }} /restore /t:Test /bl:$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/SendToHelix.binlog displayName: ${{ parameters.DisplayNamePrefix }} condition: ${{ parameters.condition }} shouldContinueOnError: ${{ parameters.continueOnError }} environment: BuildConfig: $(_BuildConfig) HelixSource: ${{ parameters.HelixSource }} HelixType: ${{ parameters.HelixType }} HelixBuild: ${{ parameters.HelixBuild }} HelixTargetQueues: ${{ parameters.HelixTargetQueues }} HelixAccessToken: ${{ parameters.HelixAccessToken }} HelixPreCommands: ${{ parameters.HelixPreCommands }} HelixPostCommands: ${{ parameters.HelixPostCommands }} WorkItemDirectory: ${{ parameters.WorkItemDirectory }} CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} DotNetCliVersion: ${{ parameters.DotNetCliVersion }} EnableXUnitReporter: ${{ parameters.EnableXUnitReporter }} WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} Creator: ${{ parameters.Creator }} SYSTEM_ACCESSTOKEN: $(System.AccessToken)
# Please remember to update the documentation if you make changes to these parameters! parameters: ProjectFile: '' # required -- project file that specifies the helix workitems HelixSource: 'pr/default' # required -- sources must start with pr/, official/, prodcon/, or agent/ HelixType: 'tests/default/' # required -- Helix telemetry which identifies what type of data this is; should include "test" for clarity and must end in '/' HelixBuild: $(Build.BuildNumber) # required -- the build number Helix will use to identify this -- automatically set to the AzDO build number HelixTargetQueues: '' # required -- semicolon delimited list of Helix queues to test on; see https://helix.dot.net/ for a list of queues HelixAccessToken: '' # required -- access token to make Helix API requests; should be provided by the appropriate variable group HelixPreCommands: '' # optional -- commands to run before Helix work item execution HelixPostCommands: '' # optional -- commands to run after Helix work item execution WorkItemDirectory: '' # optional -- a payload directory to zip up and send to Helix; requires WorkItemCommand; incompatible with XUnitProjects CorrelationPayloadDirectory: '' # optional -- a directory to zip up and send to Helix as a correlation payload IncludeDotNetCli: false # optional -- true will download a version of the .NET CLI onto the Helix machine as a correlation payload; requires DotNetCliPackageType and DotNetCliVersion DotNetCliPackageType: '' # optional -- either 'sdk', 'runtime' or 'aspnetcore-runtime'; determines whether the sdk or runtime will be sent to Helix; see https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases.json DotNetCliVersion: '' # optional -- version of the CLI to send to Helix; based on this: https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases.json EnableXUnitReporter: false # optional -- true enables XUnit result reporting to Mission Control WaitForWorkItemCompletion: true # optional -- true will make the task wait until work items have been completed and fail the build if work items fail. False is "fire and forget." Creator: '' # optional -- if the build is external, use this to specify who is sending the job DisplayNamePrefix: 'Send job to Helix' # optional -- rename the beginning of the displayName of the steps in AzDO condition: succeeded() # optional -- condition for step to execute; defaults to succeeded() continueOnError: false # optional -- determines whether to continue the build if the step errors; defaults to false osGroup: '' # required -- operating system for the job steps: - template: /eng/pipelines/common/templates/runtimes/send-to-helix-inner-step.yml parameters: osGroup: ${{ parameters.osGroup }} sendParams: $(Build.SourcesDirectory)/eng/testing/performance/${{ parameters.ProjectFile }} /restore /t:Test /bl:$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/SendToHelix.binlog displayName: ${{ parameters.DisplayNamePrefix }} condition: ${{ parameters.condition }} shouldContinueOnError: ${{ parameters.continueOnError }} environment: BuildConfig: $(_BuildConfig) HelixSource: ${{ parameters.HelixSource }} HelixType: ${{ parameters.HelixType }} HelixBuild: ${{ parameters.HelixBuild }} HelixTargetQueues: ${{ parameters.HelixTargetQueues }} HelixAccessToken: ${{ parameters.HelixAccessToken }} HelixPreCommands: ${{ parameters.HelixPreCommands }} HelixPostCommands: ${{ parameters.HelixPostCommands }} WorkItemDirectory: ${{ parameters.WorkItemDirectory }} CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} DotNetCliVersion: ${{ parameters.DotNetCliVersion }} EnableXUnitReporter: ${{ parameters.EnableXUnitReporter }} WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} Creator: ${{ parameters.Creator }} SYSTEM_ACCESSTOKEN: $(System.AccessToken)
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/libraries/Microsoft.Extensions.Logging.Console/tests/TrimmingTests/Microsoft.Extensions.Logging.Console.TrimmingTests.proj
<Project DefaultTargets="Build"> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props))" /> <PropertyGroup> <AdditionalProjectReferences>Microsoft.Extensions.Logging.Console</AdditionalProjectReferences> <SkipOnTestRuntimes>browser-wasm</SkipOnTestRuntimes> <!-- Justification: This depends on ConsoleLogger.Processor which requires System.Threading.Thread.Start() which throws PNSE on wasm. --> </PropertyGroup> <ItemGroup> <TestConsoleAppSourceFiles Include="AddConsoleFormatterTests.cs" /> </ItemGroup> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.targets))" /> </Project>
<Project DefaultTargets="Build"> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props))" /> <PropertyGroup> <AdditionalProjectReferences>Microsoft.Extensions.Logging.Console</AdditionalProjectReferences> <SkipOnTestRuntimes>browser-wasm</SkipOnTestRuntimes> <!-- Justification: This depends on ConsoleLogger.Processor which requires System.Threading.Thread.Start() which throws PNSE on wasm. --> </PropertyGroup> <ItemGroup> <TestConsoleAppSourceFiles Include="AddConsoleFormatterTests.cs" /> </ItemGroup> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.targets))" /> </Project>
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/libraries/Microsoft.Extensions.Options/tests/TrimmingTests/Microsoft.Extensions.Options.TrimmingTests.proj
<Project DefaultTargets="Build"> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props))" /> <PropertyGroup> <AdditionalProjectReferences> Microsoft.Extensions.Options; Microsoft.Extensions.DependencyInjection </AdditionalProjectReferences> </PropertyGroup> <ItemGroup> <TestConsoleAppSourceFiles Include="ConfigureTests.cs" /> </ItemGroup> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.targets))" /> </Project>
<Project DefaultTargets="Build"> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props))" /> <PropertyGroup> <AdditionalProjectReferences> Microsoft.Extensions.Options; Microsoft.Extensions.DependencyInjection </AdditionalProjectReferences> </PropertyGroup> <ItemGroup> <TestConsoleAppSourceFiles Include="ConfigureTests.cs" /> </ItemGroup> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.targets))" /> </Project>
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/tests/build.proj
<Project DefaultTargets="Build"> <Import Project="Common\dirs.proj" /> <Import Project="Directory.Build.targets" /> <Import Project="xunit-wrappers.targets" /> <PropertyGroup> <XunitTestBinBase Condition="'$(XunitTestBinBase)'==''" >$(BaseOutputPathWithConfig)</XunitTestBinBase> <XunitWrapperGeneratedCSDirBase>$(XunitTestBinBase)\TestWrappers\</XunitWrapperGeneratedCSDirBase> <MSBuildEnableAllPropertyFunctions>1</MSBuildEnableAllPropertyFunctions> <Language>C#</Language> <RuntimeIdentifier>$(OutputRid)</RuntimeIdentifier> </PropertyGroup> <ItemGroup> <DisabledTestDir Include="bin" /> <DisabledTestDir Include="Common" /> <DisabledTestDir Include="Tests" /> <DisabledTestDir Include="TestWrappers" /> <_SkipTestDir Include="@(DisabledTestDir)" /> </ItemGroup> <ItemGroup> <RestoreProjects Include="Common\test_dependencies_fs\test_dependencies.fsproj" /> <RestoreProjects Include="Common\test_dependencies\test_dependencies.csproj" /> <RestoreProjects Include="Common\CoreCLRTestLibrary\CoreCLRTestLibrary.csproj" /> <RestoreProjects Include="Common\XUnitWrapperGenerator\XUnitWrapperGenerator.csproj" /> <RestoreProjects Include="Common\XUnitWrapperLibrary\XUnitWrapperLibrary.csproj" /> <RestoreProjects Include="Common\XHarnessRunnerLibrary\XHarnessRunnerLibrary.csproj" /> <RestoreProjects Include="Common\external\external.csproj" /> <RestoreProjects Include="Common\ilasm\ilasm.ilproj" /> </ItemGroup> <ItemGroup> <TestBuildSteps Include="RestorePackages" /> <TestBuildSteps Include="ManagedBuild" /> <TestBuildSteps Include="CheckTestBuildStep" /> <TestBuildSteps Include="GenerateLayout" /> <TestBuildSteps Include="BuildTestWrappers" /> <TestBuildSteps Include="CrossgenFramework" /> <TestBuildSteps Include="CreateAndroidApps" /> <TestBuildSteps Include="CreateIosApps" /> <TestBuildSteps Include="BuildMonoAot" /> </ItemGroup> <Target Name="Rebuild" /> <Target Name="FindCmdDirectories" DependsOnTargets="GetListOfTestCmds"> <Error Condition="!Exists('$(XunitTestBinBase)')" Text="$(XunitTestBinBase) does not exist. Please run src\tests\build / src/tests/build.sh from the repo root at least once to get the tests built." /> <ItemGroup> <AllTestDirsNonCanonicalPaths Include="$([System.IO.Directory]::GetDirectories(`$(XunitTestBinBase)`))" /> <AllTestDirsPaths Include="@(AllTestDirsNonCanonicalPaths)" /> <AllTestDirsPaths Include="@(AllTestDirsNonCanonicalPaths)" > <Path>$([System.IO.Path]::GetFullPath(%(Identity)))</Path> </AllTestDirsPaths> <SkipTestDirsPaths Include="$([System.IO.Path]::GetFullPath('$(XunitTestBinBase)%(_SkipTestDir.Identity)'))" /> <NonExcludedTestDirectories Include="@(AllTestDirsPaths -> '%(Path)')" Exclude="@(SkipTestDirsPaths)" /> </ItemGroup> <ItemGroup Condition="'@(LegacyRunnableTestPaths)' != ''"> <TopLevelDirectories Include="@(NonExcludedTestDirectories)" /> <SecondLevel Include="$([System.IO.Directory]::GetDirectories(%(TopLevelDirectories.Identity)))" /> <SecondLevelDirectories Include="@(SecondLevel)"> <Path>$([System.IO.Path]::GetFullPath(%(LegacyRunnableTestPaths.Identity)))</Path> </SecondLevelDirectories> <TestDirectoriesWithDup Include="@(SecondLevelDirectories -> '%(Identity)')" Condition="$([System.String]::new('%(Path)').StartsWith('%(Identity)'))" /> </ItemGroup> <RemoveDuplicates Inputs="@(TestDirectoriesWithDup)"> <Output TaskParameter="Filtered" ItemName="TestDirectories"/> </RemoveDuplicates> </Target> <!-- Target to check the test build, to see if it looks ok. We've had several cases where a change inadvertently and drastically changes the set of tests that are built, and that change is unnoticed. The most common case is for a build of the Priority 1 tests to only build the Priority 0 tests. This target is run after a test build to verify that the basic number of tests that were built is basically what was expected. When this was written, there were about 2500 Priority 0 tests and about 10268 Priority 1 tests on Windows, 9976 on Ubuntu (it differs slightly based on platform). We currently check that the number of Priority 0 tests is greater than 2000 and less than 3000, and the number of Priority 1 tests is greater than 9000. --> <Target Name="CheckTestBuild" DependsOnTargets="GetListOfTestCmds"> <Error Condition="!Exists('$(XunitTestBinBase)')" Text="$(XunitTestBinBase) does not exist. Please run src\tests\build / src/tests/build.sh from the repo root at least once to get the tests built." /> <PropertyGroup> <TestCount>@(LegacyRunnableTestPaths->Count())</TestCount> </PropertyGroup> <Message Text="Found $(TestCount) built tests"/> <ItemGroup> <Error Condition="'$(CLRTestPriorityToBuild)' == '0' and '$(TestCount)' &lt;= 2000" Text="Unexpected test count. Expected &gt; 2000, found $(TestCount).'" /> <Error Condition="'$(CLRTestPriorityToBuild)' == '0' and '$(TestCount)' &gt;= 3000" Text="Unexpected test count. Expected &lt; 3000, found $(TestCount).'" /> <Error Condition="'$(CLRTestPriorityToBuild)' == '1' and '$(TestCount)' &lt;= 9000" Text="Unexpected test count. Expected &gt; 9000, found $(TestCount).'" /> <Error Condition="'$(CLRTestPriorityToBuild)' != '0' and '$(CLRTestPriorityToBuild)' != '1'" Text="Unknown priority $(CLRTestPriorityToBuild)" /> </ItemGroup> </Target> <Import Project="$(__Exclude)" Condition="'$(__Exclude)' != '' AND '$(XunitTestBinBase)' != ''" /> <PropertyGroup> <HaveExcludes>False</HaveExcludes> <HaveExcludes Condition="'$(__Exclude)' != ''">True</HaveExcludes> </PropertyGroup> <Target Name="MonoAotCompileTests" DependsOnTargets="GetListOfTestCmds;FindCmdDirectories"> <ItemGroup> <AllTestScripts Include="%(TestDirectories.Identity)\**\*.sh" /> <TestExclusions Include="@(ExcludeList->Metadata('FullPath'))" Condition="$(HaveExcludes)" /> <TestScripts Include="@(AllTestScripts)" Exclude="@(TestExclusions)" /> <TestAssemblyPaths Include="$([System.IO.Path]::ChangeExtension('%(TestScripts.Identity)', 'dll'))" /> <TestAssemblies Include="%(TestAssemblyPaths.Identity)" Condition="Exists(%(TestAssemblyPaths.Identity))" /> <TestDirsWithDuplicates Include="$([System.IO.Path]::GetDirectoryName('%(TestAssemblies.Identity)'))" /> </ItemGroup> <RemoveDuplicates Inputs="@(TestDirsWithDuplicates)"> <Output TaskParameter="Filtered" ItemName="TestDirs" /> </RemoveDuplicates> <ItemGroup> <TestsAndAssociatedAssemblies Include="%(TestDirs.Identity)/*.dll" /> <CoreRootDlls Include="$(CORE_ROOT)/*.dll" Exclude="$(CORE_ROOT)/xunit.performance.api.dll" /> <AllDlls Condition="'$(MonoFullAot)' == 'true'" Include="@(TestsAndAssociatedAssemblies);@(CoreRootDlls)" /> <AllDlls Condition="'$(MonoFullAot)' != 'true'" Include="@(TestsAndAssociatedAssemblies)" /> </ItemGroup> <PropertyGroup Condition="'$(CROSSCOMPILE)' == ''"> <AotCompiler Condition="'$(RunningOnUnix)' == 'true'">$(CORE_ROOT)/corerun</AotCompiler> <AotCompiler Condition="'$(RunningOnUnix)' != 'true'">$(CORE_ROOT)\corerun.exe</AotCompiler> <MonoLlvmPath>$(MonoBinDir)</MonoLlvmPath> </PropertyGroup> <PropertyGroup Condition="'$(CROSSCOMPILE)' != ''"> <AotCompiler>$(MonoBinDir)/cross/$(OutputRid)/mono-aot-cross</AotCompiler> <MonoLlvmPath>$(MonoBinDir)/cross/$(OutputRid)</MonoLlvmPath> </PropertyGroup> <ItemGroup> <MonoAotOption Condition="'$(MonoFullAot)' == 'true'" Include="full" /> <MonoAotOption Condition="'$(MonoFullAot)' == 'true'" Include="nimt-trampolines=2000" /> <MonoAotOption Condition="'$(MonoFullAot)' == 'true'" Include="ntrampolines=10000" /> <MonoAotOption Condition="'$(MonoFullAot)' == 'true'" Include="nrgctx-fetch-trampolines=256" /> <MonoAotOption Condition="'$(MonoFullAot)' == 'true'" Include="ngsharedvt-trampolines=4400" /> <MonoAotOption Condition="'$(MonoFullAot)' == 'true'" Include="nftnptr-arg-trampolines=4000" /> <MonoAotOption Condition="'$(MonoFullAot)' == 'true'" Include="nrgctx-trampolines=21000" /> <MonoAotOption Include="llvm" /> <MonoAotOption Include="llvm-path=$(MonoLlvmPath)" /> <MonoAotOption Condition="'$(__MonoToolPrefix)' != ''" Include="tool-prefix=$(__MonoToolPrefix)" /> </ItemGroup> <ItemGroup Condition="'$(TargetArchitecture)' == 'arm64'"> <MonoAotOption Include="mattr=crc" /> <MonoAotOption Include="mattr=crypto" /> </ItemGroup> <ItemGroup Condition="'$(TargetArchitecture)' == 'x64'"> <MonoAotOption Include="mattr=sse4.2" /> <MonoAotOption Include="mattr=popcnt" /> <MonoAotOption Include="mattr=lzcnt" /> <MonoAotOption Include="mattr=bmi" /> <MonoAotOption Include="mattr=bmi2" /> <MonoAotOption Include="mattr=pclmul" /> <MonoAotOption Include="mattr=aes" /> </ItemGroup> <PropertyGroup> <MonoAotOptions>@(MonoAotOption->'%(Identity)', ',')</MonoAotOptions> <MonoPath>$(CORE_ROOT)</MonoPath> </PropertyGroup> <Message Importance="High" Text="Mono AOT options: $(MonoAotOptions)" /> <Message Importance="High" Text="Mono AOT MONO_PATH: $(MonoPath)" /> <ItemGroup> <AotProject Include="../mono/msbuild/aot-compile.proj"> <Properties>_AotCompiler=$(AotCompiler);_TestDll=%(AllDlls.Identity);_MonoPath=$(MonoPath);_MonoAotOptions=$(MonoAotOptions)</Properties> </AotProject> </ItemGroup> <MSBuild Projects="@(AotProject)" Targets="AotCompile" Condition="@(AllDlls->Count()) &gt; 0" BuildInParallel="true" /> </Target> <UsingTask TaskName="AndroidAppBuilderTask" AssemblyFile="$(AndroidAppBuilderTasksAssemblyPath)" Condition="'$(RunWithAndroid)'=='true'"/> <Target Name="BuildAndroidApp"> <PropertyGroup> <RuntimeIdentifier>android-$(TargetArchitecture)</RuntimeIdentifier> <CMDDIR_Grandparent>$([System.IO.Path]::GetDirectoryName($([System.IO.Path]::GetDirectoryName($(_CMDDIR)))))</CMDDIR_Grandparent> <CategoryWithSlash>$([System.String]::Copy('$(_CMDDIR)').Replace("$(CMDDIR_Grandparent)/",""))</CategoryWithSlash> <Category>$([System.String]::Copy('$(CategoryWithSlash)').Replace('/','_'))</Category> <BuildDir>$(IntermediateOutputPath)\AndroidApps\$(Category)</BuildDir> <AppDir>$(BuildDir)\apk</AppDir> <FinalApkPath>$(XUnitTestBinBase)$(CategoryWithSlash)\$(Category).apk</FinalApkPath> <StripDebugSymbols>False</StripDebugSymbols> <RuntimeComponents>diagnostics_tracing</RuntimeComponents> <DiagnosticPorts>127.0.0.1:9000,nosuspend,listen</DiagnosticPorts> <StripDebugSymbols Condition="'$(Configuration)' == 'Release'">True</StripDebugSymbols> <MicrosoftNetCoreAppRuntimePackDir>$(ArtifactsBinDir)microsoft.netcore.app.runtime.android-$(TargetArchitecture)\$(Configuration)\runtimes\android-$(TargetArchitecture)\</MicrosoftNetCoreAppRuntimePackDir> <AndroidAbi Condition="'$(TargetArchitecture)' == 'arm64'">arm64-v8a</AndroidAbi> <AndroidAbi Condition="'$(TargetArchitecture)' == 'arm'">armeabi-v7a</AndroidAbi> <AndroidAbi Condition="'$(TargetArchitecture)' == 'x64'">x86_64</AndroidAbi> <AndroidAbi Condition="'$(TargetArchitecture)' == 'x86'">x86</AndroidAbi> <MonoInterp>false</MonoInterp> <MonoInterp Condition="'$(RuntimeVariant)' == 'monointerpreter'">true</MonoInterp> </PropertyGroup> <RemoveDir Directories="$(AppDir)" /> <MakeDir Directories="$(BuildDir)"/> <ItemGroup> <AllCMDsPresent Include="$(_CMDDIR)\**\*.$(TestScriptExtension)" Exclude="$(_CMDDIR)\**\AppBundle\*.$(TestScriptExtension)" /> <TestAssemblies Include="@(AllCMDsPresent->'%(RelativeDir)%(Filename).dll')" /> <TestAssemblyDirs Include="@(AllCMDsPresent->'%(RelativeDir)')" /> <AssembliesInTestDirs Include="%(AllCMDsPresent.RelativeDir)*.dll" Exclude="@(TestAssemblies)"/> <RuntimePackLibs Include="$(MicrosoftNetCoreAppRuntimePackDir)lib/**/*.dll" /> <RuntimePackNativeLibs Include="$(MicrosoftNetCoreAppRuntimePackDir)native/**/*.dll;$(MicrosoftNetCoreAppRuntimePackDir)native/**/*.a;$(MicrosoftNetCoreAppRuntimePackDir)native/**/*.so" /> <TestTargetingPathLibs Include="$(TargetingPackPath)/*.dll" /> </ItemGroup> <Copy SourceFiles="@(TestAssemblies)" DestinationFolder="$(BuildDir)" /> <Copy SourceFiles="@(AssembliesInTestDirs)" DestinationFolder="$(BuildDir)" /> <Copy SourceFiles="@(RuntimePackNativeLibs)" DestinationFolder="$(BuildDir)" /> <Copy SourceFiles="@(RuntimePackLibs)" DestinationFolder="$(BuildDir)" /> <Copy SourceFiles="@(TestTargetingPathLibs)" DestinationFolder="$(BuildDir)" /> <AndroidAppBuilderTask RuntimeIdentifier="$(RuntimeIdentifier)" ProjectName="$(Category)" MonoRuntimeHeaders="$(MicrosoftNetCoreAppRuntimePackDir)/native/include/mono-2.0" RuntimeComponents="$(RuntimeComponents)" DiagnosticPorts="$(DiagnosticPorts)" StripDebugSymbols="$(StripDebugSymbols)" ForceInterpreter="$(MonoInterp)" AppDir="$(BuildDir)" OutputDir="$(AppDir)"> <Output TaskParameter="ApkBundlePath" PropertyName="ApkBundlePath" /> <Output TaskParameter="ApkPackageId" PropertyName="ApkPackageId" /> </AndroidAppBuilderTask> <Move SourceFiles="$(ApkBundlePath)" DestinationFiles="$(FinalApkPath)" /> <Message Importance="High" Text="Apk: $(FinalApkPath)"/> <Message Importance="High" Text="PackageId: $(ApkPackageId)"/> <Message Importance="High" Text="MonoInterp: $(MonoInterp)"/> <!-- delete the BuildDir in CI builds to save disk space on build agents since they're no longer needed --> <RemoveDir Condition="'$(ContinuousIntegrationBuild)' == 'true'" Directories="$(BuildDir)" /> </Target> <Target Name="BuildAllAndroidApp" DependsOnTargets="GetListOfTestCmds;FindCmdDirectories"> <MSBuild Projects="$(MSBuildProjectFile)" Targets="BuildAndroidApp" Properties="_CMDDIR=%(TestDirectories.Identity)" Condition="'@(TestDirectories)' != ''" /> </Target> <UsingTask TaskName="AppleAppBuilderTask" AssemblyFile="$(AppleAppBuilderTasksAssemblyPath)" /> <UsingTask TaskName="MonoAOTCompiler" AssemblyFile="$(MonoAOTCompilerTasksAssemblyPath)" /> <Target Name="BuildiOSApp"> <PropertyGroup> <CMDDIR_Grandparent>$([System.IO.Path]::GetDirectoryName($([System.IO.Path]::GetDirectoryName($(_CMDDIR)))))</CMDDIR_Grandparent> <CategoryWithSlash>$([System.String]::Copy('$(_CMDDIR)').Replace("$(CMDDIR_Grandparent)/",""))</CategoryWithSlash> <Category>$([System.String]::Copy('$(CategoryWithSlash)').Replace('/','_'))</Category> <XUnitWrapperFileName>$([System.String]::Copy('$(CategoryWithSlash)').Replace('/', '.')).XUnitWrapper.dll</XUnitWrapperFileName> <XUnitWrapperDll>$(CMDDIR_GrandParent)/$(CategoryWithSlash)/$(XUnitWrapperFileName)</XUnitWrapperDll> <BuildDir>$(IntermediateOutputPath)\iOSApps\$(Category)</BuildDir> <FinalPath>$(XUnitTestBinBase)$(CategoryWithSlash)\$(Category).app</FinalPath> <RuntimeComponents>diagnostics_tracing</RuntimeComponents> </PropertyGroup> <PropertyGroup> <AssemblyName>$(Category)</AssemblyName> <MicrosoftNetCoreAppRuntimePackDir>$(ArtifactsBinDir)microsoft.netcore.app.runtime.iossimulator-$(TargetArchitecture)/$(Configuration)/runtimes/iossimulator-$(TargetArchitecture)</MicrosoftNetCoreAppRuntimePackDir> <MicrosoftNetCoreAppRuntimePackNativeDir>$(MicrosoftNetCoreAppRuntimePackDir)/native</MicrosoftNetCoreAppRuntimePackNativeDir> </PropertyGroup> <ItemGroup> <AllTestScripts Include="$(_CMDDIR)\**\*.sh" Exclude="$(_CMDDIR)\**\AppBundle\*.sh" /> </ItemGroup> <ItemGroup> <TestExclusions Include="@(ExcludeList->Metadata('FullPath'))" Condition="$(HaveExcludes)" /> <TestScripts Include="@(AllTestScripts)" Exclude="@(TestExclusions)" /> <TestDllPaths Include="$([System.IO.Path]::ChangeExtension('%(TestScripts.Identity)', 'dll'))" /> <TestDlls Include="%(TestDllPaths.Identity)" Condition="Exists(%(TestDllPaths.Identity))" /> <AssembliesInTestDirs Include="%(AllCMDsPresent.RelativeDir)*.dll" Exclude="@(TestAssemblies)"/> <RuntimePackLibs Include="$(MicrosoftNetCoreAppRuntimePackDir)lib/**/*.dll" /> <TestTargetingPathLibs Include="$(TargetingPackPath)/*.dll" /> </ItemGroup> <ItemGroup> <ExtraDlls Include="%(TestDlls.RelativeDir)*.dll" Exclude="@(TestDlls)"> <TestDllFilename>@(TestDlls->'%(Filename)')</TestDllFilename> </ExtraDlls> </ItemGroup> <PropertyGroup> <BundleDir>$([MSBuild]::NormalizeDirectory('$(BuildDir)', 'AppBundle'))</BundleDir> </PropertyGroup> <ItemGroup> <RuntimePackNativeLibs Include="$(MicrosoftNetCoreAppRuntimePackDir)/**/*.dll;$(MicrosoftNetCoreAppRuntimePackDir)/native/**/*.a;$(MicrosoftNetCoreAppRuntimePackDir)/native/**/*.dylib" /> </ItemGroup> <RemoveDir Directories="$(BundleDir)" /> <RemoveDir Directories="$(BuildDir)" /> <MakeDir Directories="$(BuildDir)" /> <MakeDir Directories="$(BuildDir)/testdir-%(TestDlls.Filename)" /> <Copy SourceFiles="@(RuntimePackNativeLibs)" DestinationFolder="$(BuildDir)" /> <Copy SourceFiles="@(RuntimePackLibs)" DestinationFolder="$(BuildDir)" /> <Copy SourceFiles="@(TestTargetingPathLibs)" DestinationFolder="$(BuildDir)" /> <Copy SourceFiles="%(TestDlls.Identity)" DestinationFolder="$(BuildDir)/testdir-%(TestDlls.Filename)" /> <Copy SourceFiles="%(ExtraDlls.Identity)" DestinationFolder="$(BuildDir)/testdir-%(ExtraDlls.TestDllFilename)" /> <AppleAppBuilderTask TargetOS="$(TargetOS)" Arch="$(TargetArchitecture)" ProjectName="$(AssemblyName)" MonoRuntimeHeaders="$(MicrosoftNetCoreAppRuntimePackNativeDir)/include/mono-2.0" RuntimeComponents="$(RuntimeComponents)" Assemblies="@(BundleAssemblies)" ForceInterpreter="$(MonoForceInterpreter)" EnableAppSandbox="$(EnableAppSandbox)" UseConsoleUITemplate="True" GenerateXcodeProject="True" BuildAppBundle="True" Optimized="True" DevTeamProvisioning="$(DevTeamProvisioning)" OutputDirectory="$(BundleDir)" AppDir="$(BuildDir)" InvariantGlobalization="true" > <Output TaskParameter="AppBundlePath" PropertyName="AppBundlePath" /> <Output TaskParameter="XcodeProjectPath" PropertyName="XcodeProjectPath" /> </AppleAppBuilderTask> <!-- Apparently MSBuild cannot move directories and recursively copying a a directory requires writing some sort of recursive traversal logic yourself. --> <ItemGroup> <RecursiveCopyHack Include="$(AppBundlePath)/**/*.*" /> </ItemGroup> <MakeDir Directories="$(FinalPath)" /> <Copy SourceFiles="@(RecursiveCopyHack)" DestinationFolder="$(FinalPath)/%(RecursiveDir)" /> <RemoveDir Directories="$(AppBundlePath)" /> <Message Importance="High" Text="App: $(FinalPath)" /> </Target> <Target Name="BuildAlliOSApp" DependsOnTargets="GetListOfTestCmds;FindCmdDirectories"> <ItemGroup> <RunProj Include="$(MSBuildProjectFile)"> <Properties>_CMDDIR=%(TestDirectories.Identity)</Properties> </RunProj> </ItemGroup> <MSBuild Projects="@(RunProj)" Targets="BuildiOSApp" BuildInParallel="true" Condition="'@(TestDirectories)' != ''" /> </Target> <Target Name="GetListOfTestCmds"> <ItemGroup> <AllRunnableTestPaths Include="$(XunitTestBinBase)\**\*.$(TestScriptExtension)"/> <AllRunnableTestPaths Remove="$(XunitTestBinBase)\**\run-v8.sh" Condition="'$(TargetArchitecture)' == 'wasm'" /> <MergedAssemblyMarkerPaths Include="$(XunitTestBinBase)\**\*.MergedTestAssembly"/> <MergedRunnableTestPaths Include="$([System.IO.Path]::ChangeExtension('%(MergedAssemblyMarkerPaths.Identity)', '.$(TestScriptExtension)'))" /> <OutOfProcessTestMarkerPaths Include="$(XunitTestBinBase)\**\*.OutOfProcessTest"/> <OutOfProcessTestPaths Include="$([System.IO.Path]::ChangeExtension('%(OutOfProcessTestMarkerPaths.Identity)', '.$(TestScriptExtension)'))" /> </ItemGroup> <!-- Remove the cmd/sh scripts for merged test runner app bundles from our list. --> <PropertyGroup Condition="'$(TargetsMobile)' == 'true'"> <MergedRunnableTestAppBundleScriptPathsPattern>@(MergedAssemblyMarkerPaths->'%(RootDir)%(Directory)AppBundle/**/*.$(TestScriptExtension)')</MergedRunnableTestAppBundleScriptPathsPattern> </PropertyGroup> <ItemGroup> <LegacyRunnableTestPaths Include="@(AllRunnableTestPaths)" Exclude="@(MergedRunnableTestPaths);@(OutOfProcessTestPaths);$(MergedRunnableTestAppBundleScriptPathsPattern)" /> </ItemGroup> </Target> <Import Project="$(RepoRoot)/src/tests/Common/tests.targets" /> <Import Project="$(RepoRoot)/src/tests/Common/publishdependency.targets" /> <Target Name="CreateTestOverlay" DependsOnTargets="CopyDependencyToCoreRoot" /> <Target Name="Clean"> <RemoveDir Condition=" '$(BuildWrappers)'=='true'" Directories="$(MSBuildThisFileDirectory)../$(XunitWrapperGeneratedCSDirBase);" ContinueOnError="WarnAndContinue" /> </Target> <Target Name="TestBuild" DependsOnTargets="@(TestBuildSteps)" /> <Target Name="BuildTargetingPack" AfterTargets="BatchRestorePackages"> <Message Text="$(MsgPrefix)Building Targeting Pack" Importance="High" /> <MSBuild Projects="Common\external\external.csproj" Targets="Build" /> </Target> <Target Name="BatchRestorePackages"> <Message Importance="High" Text="[$([System.DateTime]::Now.ToString('HH:mm:ss.ff'))] Restoring all packages..." /> <!-- restore all csproj's with PackageReferences in one pass --> <MSBuild Projects="build.proj" Properties="RestoreProj=%(RestoreProjects.Identity)" Targets="RestorePackage" /> <Message Importance="High" Text="[$([System.DateTime]::Now.ToString('HH:mm:ss.ff'))] Restoring all packages...Done." /> </Target> <Target Name="RestorePackage"> <PropertyGroup> <_ConfigurationProperties>/p:TargetOS=$(TargetOS) /p:TargetArchitecture=$(TargetArchitecture) /p:Configuration=$(Configuration) /p:CrossBuild=$(CrossBuild)</_ConfigurationProperties> <DotnetRestoreCommand Condition="'$(__DistroRid)' == ''">"$(DotNetTool)" restore $(RestoreProj) $(PackageVersionArg) /p:SetTFMForRestore=true $(_ConfigurationProperties)</DotnetRestoreCommand> <DotnetRestoreCommand Condition="'$(__DistroRid)' != ''">"$(DotNetTool)" restore -r $(__DistroRid) $(RestoreProj) $(PackageVersionArg) /p:SetTFMForRestore=true $(_ConfigurationProperties)</DotnetRestoreCommand> </PropertyGroup> <Exec Command="$(DotnetRestoreCommand)"/> </Target> <!-- Override RestorePackages from dir.traversal.targets and do a batch restore --> <Target Name="RestorePackages" DependsOnTargets="BatchRestorePackages" Condition="'$(__SkipRestorePackages)' != '1'" /> <Target Name="ManagedBuild" DependsOnTargets="BuildManagedTestGroups" Condition="'$(__BuildTestWrappersOnly)' != '1' and '$(__GenerateLayoutOnly)' != '1' and '$(__SkipManaged)' != '1' and !$(MonoAot) and !$(MonoFullAot)" /> <Target Name="BuildManagedTestGroups" DependsOnTargets="RestorePackages;ResolveDisabledProjects;BuildNativeAotFrameworkObjects"> <Message Importance="High" Text="$(MsgPrefix)Building managed test components" /> <!-- Execute msbuild test build in stages - workaround for excessive data retention in MSBuild ConfigCache --> <!-- See https://github.com/Microsoft/msbuild/issues/2993 --> <!-- We need to build group #1 manually as it doesn't have a _GroupStartsWith item associated with it, see the comment in Common\dirs.proj --> <MSBuild Projects="$(MSBuildThisFileFullPath)" Targets="BuildManagedTestGroup" Properties="__TestGroupToBuild=1;__SkipRestorePackages=1" /> <MSBuild Projects="$(MSBuildThisFileFullPath)" Targets="BuildManagedTestGroup" Properties="__TestGroupToBuild=%(_GroupStartsWith.GroupNumber);__SkipRestorePackages=1" /> </Target> <Target Name="BuildManagedTestGroup" DependsOnTargets="ResolveDisabledProjects" Condition="'$(__SkipManaged)' != '1'" > <PropertyGroup> <TargetToBuild>Build</TargetToBuild> <!-- In split pipeline mode (in the lab) we're using the native component copying step to generate the test execution scripts --> <TargetToBuild Condition="'$(__CopyNativeTestBinaries)' == '1'">CopyAllNativeTestProjectBinaries</TargetToBuild> <GroupBuildCmd>$(DotNetCli) msbuild</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) $(MSBuildThisFileFullPath)</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) /t:$(TargetToBuild)</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:TargetArchitecture=$(TargetArchitecture)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:Configuration=$(Configuration)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:LibrariesConfiguration=$(LibrariesConfiguration)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:TargetOS=$(TargetOS)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:RuntimeOS=$(RuntimeOS)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:RuntimeFlavor=$(RuntimeFlavor)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:RuntimeVariant=$(RuntimeVariant)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:CLRTestBuildAllTargets=$(CLRTestBuildAllTargets)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:__TestGroupToBuild=$(__TestGroupToBuild)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:__SkipRestorePackages=1"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) /nodeReuse:false</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) /maxcpucount</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) /bl:$(ArtifactsDir)/log/$(Configuration)/InnerManagedTestBuild.$(__TestGroupToBuild).binlog</GroupBuildCmd> <GroupBuildCmd Condition="'$(TestBuildMode)' == 'nativeaot'">$(GroupBuildCmd) "/p:DefaultBuildAllTarget=BuildNativeAot"</GroupBuildCmd> <GroupBuildCmd Condition="'$(IlcMultiModule)' == 'true'">$(GroupBuildCmd) "/p:IlcMultiModule=true"</GroupBuildCmd> <GroupBuildCmd Condition="'$(BuildNativeAotFrameworkObjects)' == 'true'">$(GroupBuildCmd) "/p:BuildNativeAotFrameworkObjects=true"</GroupBuildCmd> </PropertyGroup> <Message Importance="High" Text="$(MsgPrefix)Building managed test group $(__TestGroupToBuild): $(GroupBuildCmd)" /> <Exec Command="$(GroupBuildCmd)" /> </Target> <Target Name="CheckTestBuildStep" DependsOnTargets="CheckTestBuild" Condition="'$(__BuildTestWrappersOnly)' != '1' and '$(__GenerateLayoutOnly)' != '1' and '$(__CopyNativeTestBinaries)' != '1' and !$(MonoAot) and !$(MonoFullAot)" /> <Target Name="GenerateLayout" DependsOnTargets="CreateTestOverlay" AfterTargets="ManagedBuild;RestorePackages" Condition="'$(__BuildTestWrappersOnly)' != '1' and '$(__CopyNativeTestBinaries)' != '1' and '$(__SkipGenerateLayout)' != '1' and !$(MonoAot) and !$(MonoFullAot)" /> <Target Name="BuildTestWrappers" DependsOnTargets="CreateAllWrappers" AfterTargets="ManagedBuild;RestorePackages" Condition="'$(__GenerateLayoutOnly)' != '1' and '$(__CopyNativeTestBinaries)' != '1' and !$(MonoAot) and !$(MonoFullAot) and ('$(__BuildTestWrappersOnly)' == '1' or ('$(__SkipTestWrappers)' != '1' and '$(__SkipManaged)' != '1'))" /> <Target Name="CrossgenFramework" DependsOnTargets="GenerateLayout" Condition="'$(__BuildTestWrappersOnly)' != '1' and '$(__CopyNativeTestBinaries)' != '1' and '$(__TestBuildMode)' == 'crossgen2' and !$(MonoAot) and !$(MonoFullAot)" > <PropertyGroup> <CrossgenDir>$(__BinDir)</CrossgenDir> <CrossgenDir Condition="'$(TargetArchitecture)' == 'arm'">$(CrossgenDir)\x64</CrossgenDir> <CrossgenDir Condition="'$(TargetArchitecture)' == 'arm64'">$(CrossgenDir)\x64</CrossgenDir> <CrossgenDir Condition="'$(TargetArchitecture)' == 'x86'">$(CrossgenDir)\x64</CrossgenDir> <CrossgenOutputDir>$(__TestIntermediatesDir)\crossgen.out</CrossgenOutputDir> <CrossgenCmd>$(DotNetCli)</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) "$(CORE_ROOT)\R2RTest\R2RTest.dll"</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) compile-framework</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) -cr "$(CORE_ROOT)"</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) --output-directory "$(CrossgenOutputDir)"</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) --release</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) --nocleanup</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) --target-arch $(TargetArchitecture)</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) -dop $(NUMBER_OF_PROCESSORS)</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) -m "$(CORE_ROOT)\StandardOptimizationData.mibc"</CrossgenCmd> <CrossgenCmd Condition="'$(__CreatePdb)' != ''">$(CrossgenCmd) --pdb</CrossgenCmd> <CrossgenCmd Condition="'$(__CreatePerfmap)' != ''">$(CrossgenCmd) --perfmap --perfmap-format-version 1</CrossgenCmd> <CrossgenCmd Condition="'$(__CompositeBuildMode)' != ''">$(CrossgenCmd) --composite</CrossgenCmd> <CrossgenCmd Condition="'$(__CompositeBuildMode)' == ''">$(CrossgenCmd) --crossgen2-parallelism 1</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) --verify-type-and-field-layout</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) --crossgen2-path "$(CrossgenDir)\crossgen2\crossgen2.dll"</CrossgenCmd> </PropertyGroup> <Message Importance="High" Text="$(MsgPrefix)Compiling framework using Crossgen2: $(CrossgenCmd)" /> <Exec Command="$(CrossgenCmd)" /> <ItemGroup> <CrossgenOutputFiles Include="$(CrossgenOutputDir)\*.dll" /> <CrossgenOutputFiles Include="$(CrossgenOutputDir)\*.ni.pdb" Condition="'$(__CreatePdb)' != ''" /> <CrossgenOutputFiles Include="$(CrossgenOutputDir)\*.ni.r2rmap" Condition="'$(__CreatePerfmap)' != ''" /> </ItemGroup> <Move SourceFiles="@(CrossgenOutputFiles)" DestinationFolder="$(CORE_ROOT)" /> </Target> <Target Name="CreateAndroidApps" DependsOnTargets="BuildAllAndroidApp" AfterTargets="ManagedBuild" Condition="'$(__BuildTestWrappersOnly)' != '1' and '$(__GenerateLayoutOnly)' != '1' and '$(__CopyNativeTestBinaries)' != '1' and $(RunWithAndroid)" /> <Target Name="CreateIosApps" DependsOnTargets="BuildAlliOSApp" AfterTargets="ManagedBuild" Condition="'$(__BuildTestWrappersOnly)' != '1' and '$(__GenerateLayoutOnly)' != '1' and '$(__CopyNativeTestBinaries)' != '1' and ('$(TargetOS)' == 'iOS' or '$(TargetOS)' == 'iOSSimulator')" /> <Target Name="BuildMonoAot" DependsOnTargets="MonoAotCompileTests" AfterTargets="ManagedBuild" Condition="'$(__BuildTestWrappersOnly)' != '1' and '$(__GenerateLayoutOnly)' != '1' and '$(__CopyNativeTestBinaries)' != '1' and ($(MonoAot) or $(MonoFullAot))" /> <Target Name="BuildNativeAotFrameworkObjects" Condition="'$(BuildNativeAotFrameworkObjects)' == 'true' and '$(TestBuildMode)' == 'nativeaot'"> <ItemGroup> <CreateLibProperty Include="IlcToolsPath=$(IlcToolsPath)" /> <CreateLibProperty Include="IlcBuildTasksPath=$(IlcBuildTasksPath)" /> <CreateLibProperty Include="IlcSdkPath=$(IlcSdkPath)" /> <CreateLibProperty Include="IlcFrameworkPath=$(IlcFrameworkPath)" /> <CreateLibProperty Include="FrameworkLibPath=$(IlcSdkPath)" /> <CreateLibProperty Include="FrameworkObjPath=$(IntermediateOutputPath)/NativeAOTFX" /> <CreateLibProperty Condition="'$(Configuration)' == 'Checked' or '$(Configuration)' == 'Release'" Include="Optimize=true" /> <CreateLibProperty Include="NETCoreSdkVersion=6.0.0" /> </ItemGroup> <MSBuild Projects="$(CoreCLRBuildIntegrationDir)/BuildFrameworkNativeObjects.proj" Targets="CreateLib" Properties="@(CreateLibProperty)" /> </Target> </Project>
<Project DefaultTargets="Build"> <Import Project="Common\dirs.proj" /> <Import Project="Directory.Build.targets" /> <Import Project="xunit-wrappers.targets" /> <PropertyGroup> <XunitTestBinBase Condition="'$(XunitTestBinBase)'==''" >$(BaseOutputPathWithConfig)</XunitTestBinBase> <XunitWrapperGeneratedCSDirBase>$(XunitTestBinBase)\TestWrappers\</XunitWrapperGeneratedCSDirBase> <MSBuildEnableAllPropertyFunctions>1</MSBuildEnableAllPropertyFunctions> <Language>C#</Language> <RuntimeIdentifier>$(OutputRid)</RuntimeIdentifier> </PropertyGroup> <ItemGroup> <DisabledTestDir Include="bin" /> <DisabledTestDir Include="Common" /> <DisabledTestDir Include="Tests" /> <DisabledTestDir Include="TestWrappers" /> <_SkipTestDir Include="@(DisabledTestDir)" /> </ItemGroup> <ItemGroup> <RestoreProjects Include="Common\test_dependencies_fs\test_dependencies.fsproj" /> <RestoreProjects Include="Common\test_dependencies\test_dependencies.csproj" /> <RestoreProjects Include="Common\CoreCLRTestLibrary\CoreCLRTestLibrary.csproj" /> <RestoreProjects Include="Common\XUnitWrapperGenerator\XUnitWrapperGenerator.csproj" /> <RestoreProjects Include="Common\XUnitWrapperLibrary\XUnitWrapperLibrary.csproj" /> <RestoreProjects Include="Common\XHarnessRunnerLibrary\XHarnessRunnerLibrary.csproj" /> <RestoreProjects Include="Common\external\external.csproj" /> <RestoreProjects Include="Common\ilasm\ilasm.ilproj" /> </ItemGroup> <ItemGroup> <TestBuildSteps Include="RestorePackages" /> <TestBuildSteps Include="ManagedBuild" /> <TestBuildSteps Include="CheckTestBuildStep" /> <TestBuildSteps Include="GenerateLayout" /> <TestBuildSteps Include="BuildTestWrappers" /> <TestBuildSteps Include="CrossgenFramework" /> <TestBuildSteps Include="CreateAndroidApps" /> <TestBuildSteps Include="CreateIosApps" /> <TestBuildSteps Include="BuildMonoAot" /> </ItemGroup> <Target Name="Rebuild" /> <Target Name="FindCmdDirectories" DependsOnTargets="GetListOfTestCmds"> <Error Condition="!Exists('$(XunitTestBinBase)')" Text="$(XunitTestBinBase) does not exist. Please run src\tests\build / src/tests/build.sh from the repo root at least once to get the tests built." /> <ItemGroup> <AllTestDirsNonCanonicalPaths Include="$([System.IO.Directory]::GetDirectories(`$(XunitTestBinBase)`))" /> <AllTestDirsPaths Include="@(AllTestDirsNonCanonicalPaths)" /> <AllTestDirsPaths Include="@(AllTestDirsNonCanonicalPaths)" > <Path>$([System.IO.Path]::GetFullPath(%(Identity)))</Path> </AllTestDirsPaths> <SkipTestDirsPaths Include="$([System.IO.Path]::GetFullPath('$(XunitTestBinBase)%(_SkipTestDir.Identity)'))" /> <NonExcludedTestDirectories Include="@(AllTestDirsPaths -> '%(Path)')" Exclude="@(SkipTestDirsPaths)" /> </ItemGroup> <ItemGroup Condition="'@(LegacyRunnableTestPaths)' != ''"> <TopLevelDirectories Include="@(NonExcludedTestDirectories)" /> <SecondLevel Include="$([System.IO.Directory]::GetDirectories(%(TopLevelDirectories.Identity)))" /> <SecondLevelDirectories Include="@(SecondLevel)"> <Path>$([System.IO.Path]::GetFullPath(%(LegacyRunnableTestPaths.Identity)))</Path> </SecondLevelDirectories> <TestDirectoriesWithDup Include="@(SecondLevelDirectories -> '%(Identity)')" Condition="$([System.String]::new('%(Path)').StartsWith('%(Identity)'))" /> </ItemGroup> <RemoveDuplicates Inputs="@(TestDirectoriesWithDup)"> <Output TaskParameter="Filtered" ItemName="TestDirectories"/> </RemoveDuplicates> </Target> <!-- Target to check the test build, to see if it looks ok. We've had several cases where a change inadvertently and drastically changes the set of tests that are built, and that change is unnoticed. The most common case is for a build of the Priority 1 tests to only build the Priority 0 tests. This target is run after a test build to verify that the basic number of tests that were built is basically what was expected. When this was written, there were about 2500 Priority 0 tests and about 10268 Priority 1 tests on Windows, 9976 on Ubuntu (it differs slightly based on platform). We currently check that the number of Priority 0 tests is greater than 2000 and less than 3000, and the number of Priority 1 tests is greater than 9000. --> <Target Name="CheckTestBuild" DependsOnTargets="GetListOfTestCmds"> <Error Condition="!Exists('$(XunitTestBinBase)')" Text="$(XunitTestBinBase) does not exist. Please run src\tests\build / src/tests/build.sh from the repo root at least once to get the tests built." /> <PropertyGroup> <TestCount>@(LegacyRunnableTestPaths->Count())</TestCount> </PropertyGroup> <Message Text="Found $(TestCount) built tests"/> <ItemGroup> <Error Condition="'$(CLRTestPriorityToBuild)' == '0' and '$(TestCount)' &lt;= 2000" Text="Unexpected test count. Expected &gt; 2000, found $(TestCount).'" /> <Error Condition="'$(CLRTestPriorityToBuild)' == '0' and '$(TestCount)' &gt;= 3000" Text="Unexpected test count. Expected &lt; 3000, found $(TestCount).'" /> <Error Condition="'$(CLRTestPriorityToBuild)' == '1' and '$(TestCount)' &lt;= 9000" Text="Unexpected test count. Expected &gt; 9000, found $(TestCount).'" /> <Error Condition="'$(CLRTestPriorityToBuild)' != '0' and '$(CLRTestPriorityToBuild)' != '1'" Text="Unknown priority $(CLRTestPriorityToBuild)" /> </ItemGroup> </Target> <Import Project="$(__Exclude)" Condition="'$(__Exclude)' != '' AND '$(XunitTestBinBase)' != ''" /> <PropertyGroup> <HaveExcludes>False</HaveExcludes> <HaveExcludes Condition="'$(__Exclude)' != ''">True</HaveExcludes> </PropertyGroup> <Target Name="MonoAotCompileTests" DependsOnTargets="GetListOfTestCmds;FindCmdDirectories"> <ItemGroup> <AllTestScripts Include="%(TestDirectories.Identity)\**\*.sh" /> <TestExclusions Include="@(ExcludeList->Metadata('FullPath'))" Condition="$(HaveExcludes)" /> <TestScripts Include="@(AllTestScripts)" Exclude="@(TestExclusions)" /> <TestAssemblyPaths Include="$([System.IO.Path]::ChangeExtension('%(TestScripts.Identity)', 'dll'))" /> <TestAssemblies Include="%(TestAssemblyPaths.Identity)" Condition="Exists(%(TestAssemblyPaths.Identity))" /> <TestDirsWithDuplicates Include="$([System.IO.Path]::GetDirectoryName('%(TestAssemblies.Identity)'))" /> </ItemGroup> <RemoveDuplicates Inputs="@(TestDirsWithDuplicates)"> <Output TaskParameter="Filtered" ItemName="TestDirs" /> </RemoveDuplicates> <ItemGroup> <TestsAndAssociatedAssemblies Include="%(TestDirs.Identity)/*.dll" /> <CoreRootDlls Include="$(CORE_ROOT)/*.dll" Exclude="$(CORE_ROOT)/xunit.performance.api.dll" /> <AllDlls Condition="'$(MonoFullAot)' == 'true'" Include="@(TestsAndAssociatedAssemblies);@(CoreRootDlls)" /> <AllDlls Condition="'$(MonoFullAot)' != 'true'" Include="@(TestsAndAssociatedAssemblies)" /> </ItemGroup> <PropertyGroup Condition="'$(CROSSCOMPILE)' == ''"> <AotCompiler Condition="'$(RunningOnUnix)' == 'true'">$(CORE_ROOT)/corerun</AotCompiler> <AotCompiler Condition="'$(RunningOnUnix)' != 'true'">$(CORE_ROOT)\corerun.exe</AotCompiler> <MonoLlvmPath>$(MonoBinDir)</MonoLlvmPath> </PropertyGroup> <PropertyGroup Condition="'$(CROSSCOMPILE)' != ''"> <AotCompiler>$(MonoBinDir)/cross/$(OutputRid)/mono-aot-cross</AotCompiler> <MonoLlvmPath>$(MonoBinDir)/cross/$(OutputRid)</MonoLlvmPath> </PropertyGroup> <ItemGroup> <MonoAotOption Condition="'$(MonoFullAot)' == 'true'" Include="full" /> <MonoAotOption Condition="'$(MonoFullAot)' == 'true'" Include="nimt-trampolines=2000" /> <MonoAotOption Condition="'$(MonoFullAot)' == 'true'" Include="ntrampolines=10000" /> <MonoAotOption Condition="'$(MonoFullAot)' == 'true'" Include="nrgctx-fetch-trampolines=256" /> <MonoAotOption Condition="'$(MonoFullAot)' == 'true'" Include="ngsharedvt-trampolines=4400" /> <MonoAotOption Condition="'$(MonoFullAot)' == 'true'" Include="nftnptr-arg-trampolines=4000" /> <MonoAotOption Condition="'$(MonoFullAot)' == 'true'" Include="nrgctx-trampolines=21000" /> <MonoAotOption Include="llvm" /> <MonoAotOption Include="llvm-path=$(MonoLlvmPath)" /> <MonoAotOption Condition="'$(__MonoToolPrefix)' != ''" Include="tool-prefix=$(__MonoToolPrefix)" /> </ItemGroup> <ItemGroup Condition="'$(TargetArchitecture)' == 'arm64'"> <MonoAotOption Include="mattr=crc" /> <MonoAotOption Include="mattr=crypto" /> </ItemGroup> <ItemGroup Condition="'$(TargetArchitecture)' == 'x64'"> <MonoAotOption Include="mattr=sse4.2" /> <MonoAotOption Include="mattr=popcnt" /> <MonoAotOption Include="mattr=lzcnt" /> <MonoAotOption Include="mattr=bmi" /> <MonoAotOption Include="mattr=bmi2" /> <MonoAotOption Include="mattr=pclmul" /> <MonoAotOption Include="mattr=aes" /> </ItemGroup> <PropertyGroup> <MonoAotOptions>@(MonoAotOption->'%(Identity)', ',')</MonoAotOptions> <MonoPath>$(CORE_ROOT)</MonoPath> </PropertyGroup> <Message Importance="High" Text="Mono AOT options: $(MonoAotOptions)" /> <Message Importance="High" Text="Mono AOT MONO_PATH: $(MonoPath)" /> <ItemGroup> <AotProject Include="../mono/msbuild/aot-compile.proj"> <Properties>_AotCompiler=$(AotCompiler);_TestDll=%(AllDlls.Identity);_MonoPath=$(MonoPath);_MonoAotOptions=$(MonoAotOptions)</Properties> </AotProject> </ItemGroup> <MSBuild Projects="@(AotProject)" Targets="AotCompile" Condition="@(AllDlls->Count()) &gt; 0" BuildInParallel="true" /> </Target> <UsingTask TaskName="AndroidAppBuilderTask" AssemblyFile="$(AndroidAppBuilderTasksAssemblyPath)" Condition="'$(RunWithAndroid)'=='true'"/> <Target Name="BuildAndroidApp"> <PropertyGroup> <RuntimeIdentifier>android-$(TargetArchitecture)</RuntimeIdentifier> <CMDDIR_Grandparent>$([System.IO.Path]::GetDirectoryName($([System.IO.Path]::GetDirectoryName($(_CMDDIR)))))</CMDDIR_Grandparent> <CategoryWithSlash>$([System.String]::Copy('$(_CMDDIR)').Replace("$(CMDDIR_Grandparent)/",""))</CategoryWithSlash> <Category>$([System.String]::Copy('$(CategoryWithSlash)').Replace('/','_'))</Category> <BuildDir>$(IntermediateOutputPath)\AndroidApps\$(Category)</BuildDir> <AppDir>$(BuildDir)\apk</AppDir> <FinalApkPath>$(XUnitTestBinBase)$(CategoryWithSlash)\$(Category).apk</FinalApkPath> <StripDebugSymbols>False</StripDebugSymbols> <RuntimeComponents>diagnostics_tracing</RuntimeComponents> <DiagnosticPorts>127.0.0.1:9000,nosuspend,listen</DiagnosticPorts> <StripDebugSymbols Condition="'$(Configuration)' == 'Release'">True</StripDebugSymbols> <MicrosoftNetCoreAppRuntimePackDir>$(ArtifactsBinDir)microsoft.netcore.app.runtime.android-$(TargetArchitecture)\$(Configuration)\runtimes\android-$(TargetArchitecture)\</MicrosoftNetCoreAppRuntimePackDir> <AndroidAbi Condition="'$(TargetArchitecture)' == 'arm64'">arm64-v8a</AndroidAbi> <AndroidAbi Condition="'$(TargetArchitecture)' == 'arm'">armeabi-v7a</AndroidAbi> <AndroidAbi Condition="'$(TargetArchitecture)' == 'x64'">x86_64</AndroidAbi> <AndroidAbi Condition="'$(TargetArchitecture)' == 'x86'">x86</AndroidAbi> <MonoInterp>false</MonoInterp> <MonoInterp Condition="'$(RuntimeVariant)' == 'monointerpreter'">true</MonoInterp> </PropertyGroup> <RemoveDir Directories="$(AppDir)" /> <MakeDir Directories="$(BuildDir)"/> <ItemGroup> <AllCMDsPresent Include="$(_CMDDIR)\**\*.$(TestScriptExtension)" Exclude="$(_CMDDIR)\**\AppBundle\*.$(TestScriptExtension)" /> <TestAssemblies Include="@(AllCMDsPresent->'%(RelativeDir)%(Filename).dll')" /> <TestAssemblyDirs Include="@(AllCMDsPresent->'%(RelativeDir)')" /> <AssembliesInTestDirs Include="%(AllCMDsPresent.RelativeDir)*.dll" Exclude="@(TestAssemblies)"/> <RuntimePackLibs Include="$(MicrosoftNetCoreAppRuntimePackDir)lib/**/*.dll" /> <RuntimePackNativeLibs Include="$(MicrosoftNetCoreAppRuntimePackDir)native/**/*.dll;$(MicrosoftNetCoreAppRuntimePackDir)native/**/*.a;$(MicrosoftNetCoreAppRuntimePackDir)native/**/*.so" /> <TestTargetingPathLibs Include="$(TargetingPackPath)/*.dll" /> </ItemGroup> <Copy SourceFiles="@(TestAssemblies)" DestinationFolder="$(BuildDir)" /> <Copy SourceFiles="@(AssembliesInTestDirs)" DestinationFolder="$(BuildDir)" /> <Copy SourceFiles="@(RuntimePackNativeLibs)" DestinationFolder="$(BuildDir)" /> <Copy SourceFiles="@(RuntimePackLibs)" DestinationFolder="$(BuildDir)" /> <Copy SourceFiles="@(TestTargetingPathLibs)" DestinationFolder="$(BuildDir)" /> <AndroidAppBuilderTask RuntimeIdentifier="$(RuntimeIdentifier)" ProjectName="$(Category)" MonoRuntimeHeaders="$(MicrosoftNetCoreAppRuntimePackDir)/native/include/mono-2.0" RuntimeComponents="$(RuntimeComponents)" DiagnosticPorts="$(DiagnosticPorts)" StripDebugSymbols="$(StripDebugSymbols)" ForceInterpreter="$(MonoInterp)" AppDir="$(BuildDir)" OutputDir="$(AppDir)"> <Output TaskParameter="ApkBundlePath" PropertyName="ApkBundlePath" /> <Output TaskParameter="ApkPackageId" PropertyName="ApkPackageId" /> </AndroidAppBuilderTask> <Move SourceFiles="$(ApkBundlePath)" DestinationFiles="$(FinalApkPath)" /> <Message Importance="High" Text="Apk: $(FinalApkPath)"/> <Message Importance="High" Text="PackageId: $(ApkPackageId)"/> <Message Importance="High" Text="MonoInterp: $(MonoInterp)"/> <!-- delete the BuildDir in CI builds to save disk space on build agents since they're no longer needed --> <RemoveDir Condition="'$(ContinuousIntegrationBuild)' == 'true'" Directories="$(BuildDir)" /> </Target> <Target Name="BuildAllAndroidApp" DependsOnTargets="GetListOfTestCmds;FindCmdDirectories"> <MSBuild Projects="$(MSBuildProjectFile)" Targets="BuildAndroidApp" Properties="_CMDDIR=%(TestDirectories.Identity)" Condition="'@(TestDirectories)' != ''" /> </Target> <UsingTask TaskName="AppleAppBuilderTask" AssemblyFile="$(AppleAppBuilderTasksAssemblyPath)" /> <UsingTask TaskName="MonoAOTCompiler" AssemblyFile="$(MonoAOTCompilerTasksAssemblyPath)" /> <Target Name="BuildiOSApp"> <PropertyGroup> <CMDDIR_Grandparent>$([System.IO.Path]::GetDirectoryName($([System.IO.Path]::GetDirectoryName($(_CMDDIR)))))</CMDDIR_Grandparent> <CategoryWithSlash>$([System.String]::Copy('$(_CMDDIR)').Replace("$(CMDDIR_Grandparent)/",""))</CategoryWithSlash> <Category>$([System.String]::Copy('$(CategoryWithSlash)').Replace('/','_'))</Category> <XUnitWrapperFileName>$([System.String]::Copy('$(CategoryWithSlash)').Replace('/', '.')).XUnitWrapper.dll</XUnitWrapperFileName> <XUnitWrapperDll>$(CMDDIR_GrandParent)/$(CategoryWithSlash)/$(XUnitWrapperFileName)</XUnitWrapperDll> <BuildDir>$(IntermediateOutputPath)\iOSApps\$(Category)</BuildDir> <FinalPath>$(XUnitTestBinBase)$(CategoryWithSlash)\$(Category).app</FinalPath> <RuntimeComponents>diagnostics_tracing</RuntimeComponents> </PropertyGroup> <PropertyGroup> <AssemblyName>$(Category)</AssemblyName> <MicrosoftNetCoreAppRuntimePackDir>$(ArtifactsBinDir)microsoft.netcore.app.runtime.iossimulator-$(TargetArchitecture)/$(Configuration)/runtimes/iossimulator-$(TargetArchitecture)</MicrosoftNetCoreAppRuntimePackDir> <MicrosoftNetCoreAppRuntimePackNativeDir>$(MicrosoftNetCoreAppRuntimePackDir)/native</MicrosoftNetCoreAppRuntimePackNativeDir> </PropertyGroup> <ItemGroup> <AllTestScripts Include="$(_CMDDIR)\**\*.sh" Exclude="$(_CMDDIR)\**\AppBundle\*.sh" /> </ItemGroup> <ItemGroup> <TestExclusions Include="@(ExcludeList->Metadata('FullPath'))" Condition="$(HaveExcludes)" /> <TestScripts Include="@(AllTestScripts)" Exclude="@(TestExclusions)" /> <TestDllPaths Include="$([System.IO.Path]::ChangeExtension('%(TestScripts.Identity)', 'dll'))" /> <TestDlls Include="%(TestDllPaths.Identity)" Condition="Exists(%(TestDllPaths.Identity))" /> <AssembliesInTestDirs Include="%(AllCMDsPresent.RelativeDir)*.dll" Exclude="@(TestAssemblies)"/> <RuntimePackLibs Include="$(MicrosoftNetCoreAppRuntimePackDir)lib/**/*.dll" /> <TestTargetingPathLibs Include="$(TargetingPackPath)/*.dll" /> </ItemGroup> <ItemGroup> <ExtraDlls Include="%(TestDlls.RelativeDir)*.dll" Exclude="@(TestDlls)"> <TestDllFilename>@(TestDlls->'%(Filename)')</TestDllFilename> </ExtraDlls> </ItemGroup> <PropertyGroup> <BundleDir>$([MSBuild]::NormalizeDirectory('$(BuildDir)', 'AppBundle'))</BundleDir> </PropertyGroup> <ItemGroup> <RuntimePackNativeLibs Include="$(MicrosoftNetCoreAppRuntimePackDir)/**/*.dll;$(MicrosoftNetCoreAppRuntimePackDir)/native/**/*.a;$(MicrosoftNetCoreAppRuntimePackDir)/native/**/*.dylib" /> </ItemGroup> <RemoveDir Directories="$(BundleDir)" /> <RemoveDir Directories="$(BuildDir)" /> <MakeDir Directories="$(BuildDir)" /> <MakeDir Directories="$(BuildDir)/testdir-%(TestDlls.Filename)" /> <Copy SourceFiles="@(RuntimePackNativeLibs)" DestinationFolder="$(BuildDir)" /> <Copy SourceFiles="@(RuntimePackLibs)" DestinationFolder="$(BuildDir)" /> <Copy SourceFiles="@(TestTargetingPathLibs)" DestinationFolder="$(BuildDir)" /> <Copy SourceFiles="%(TestDlls.Identity)" DestinationFolder="$(BuildDir)/testdir-%(TestDlls.Filename)" /> <Copy SourceFiles="%(ExtraDlls.Identity)" DestinationFolder="$(BuildDir)/testdir-%(ExtraDlls.TestDllFilename)" /> <AppleAppBuilderTask TargetOS="$(TargetOS)" Arch="$(TargetArchitecture)" ProjectName="$(AssemblyName)" MonoRuntimeHeaders="$(MicrosoftNetCoreAppRuntimePackNativeDir)/include/mono-2.0" RuntimeComponents="$(RuntimeComponents)" Assemblies="@(BundleAssemblies)" ForceInterpreter="$(MonoForceInterpreter)" EnableAppSandbox="$(EnableAppSandbox)" UseConsoleUITemplate="True" GenerateXcodeProject="True" BuildAppBundle="True" Optimized="True" DevTeamProvisioning="$(DevTeamProvisioning)" OutputDirectory="$(BundleDir)" AppDir="$(BuildDir)" InvariantGlobalization="true" > <Output TaskParameter="AppBundlePath" PropertyName="AppBundlePath" /> <Output TaskParameter="XcodeProjectPath" PropertyName="XcodeProjectPath" /> </AppleAppBuilderTask> <!-- Apparently MSBuild cannot move directories and recursively copying a a directory requires writing some sort of recursive traversal logic yourself. --> <ItemGroup> <RecursiveCopyHack Include="$(AppBundlePath)/**/*.*" /> </ItemGroup> <MakeDir Directories="$(FinalPath)" /> <Copy SourceFiles="@(RecursiveCopyHack)" DestinationFolder="$(FinalPath)/%(RecursiveDir)" /> <RemoveDir Directories="$(AppBundlePath)" /> <Message Importance="High" Text="App: $(FinalPath)" /> </Target> <Target Name="BuildAlliOSApp" DependsOnTargets="GetListOfTestCmds;FindCmdDirectories"> <ItemGroup> <RunProj Include="$(MSBuildProjectFile)"> <Properties>_CMDDIR=%(TestDirectories.Identity)</Properties> </RunProj> </ItemGroup> <MSBuild Projects="@(RunProj)" Targets="BuildiOSApp" BuildInParallel="true" Condition="'@(TestDirectories)' != ''" /> </Target> <Target Name="GetListOfTestCmds"> <ItemGroup> <AllRunnableTestPaths Include="$(XunitTestBinBase)\**\*.$(TestScriptExtension)"/> <AllRunnableTestPaths Remove="$(XunitTestBinBase)\**\run-v8.sh" Condition="'$(TargetArchitecture)' == 'wasm'" /> <MergedAssemblyMarkerPaths Include="$(XunitTestBinBase)\**\*.MergedTestAssembly"/> <MergedRunnableTestPaths Include="$([System.IO.Path]::ChangeExtension('%(MergedAssemblyMarkerPaths.Identity)', '.$(TestScriptExtension)'))" /> <OutOfProcessTestMarkerPaths Include="$(XunitTestBinBase)\**\*.OutOfProcessTest"/> <OutOfProcessTestPaths Include="$([System.IO.Path]::ChangeExtension('%(OutOfProcessTestMarkerPaths.Identity)', '.$(TestScriptExtension)'))" /> </ItemGroup> <!-- Remove the cmd/sh scripts for merged test runner app bundles from our list. --> <PropertyGroup Condition="'$(TargetsMobile)' == 'true'"> <MergedRunnableTestAppBundleScriptPathsPattern>@(MergedAssemblyMarkerPaths->'%(RootDir)%(Directory)AppBundle/**/*.$(TestScriptExtension)')</MergedRunnableTestAppBundleScriptPathsPattern> </PropertyGroup> <ItemGroup> <LegacyRunnableTestPaths Include="@(AllRunnableTestPaths)" Exclude="@(MergedRunnableTestPaths);@(OutOfProcessTestPaths);$(MergedRunnableTestAppBundleScriptPathsPattern)" /> </ItemGroup> </Target> <Import Project="$(RepoRoot)/src/tests/Common/tests.targets" /> <Import Project="$(RepoRoot)/src/tests/Common/publishdependency.targets" /> <Target Name="CreateTestOverlay" DependsOnTargets="CopyDependencyToCoreRoot" /> <Target Name="Clean"> <RemoveDir Condition=" '$(BuildWrappers)'=='true'" Directories="$(MSBuildThisFileDirectory)../$(XunitWrapperGeneratedCSDirBase);" ContinueOnError="WarnAndContinue" /> </Target> <Target Name="TestBuild" DependsOnTargets="@(TestBuildSteps)" /> <Target Name="BuildTargetingPack" AfterTargets="BatchRestorePackages"> <Message Text="$(MsgPrefix)Building Targeting Pack" Importance="High" /> <MSBuild Projects="Common\external\external.csproj" Targets="Build" /> </Target> <Target Name="BatchRestorePackages"> <Message Importance="High" Text="[$([System.DateTime]::Now.ToString('HH:mm:ss.ff'))] Restoring all packages..." /> <!-- restore all csproj's with PackageReferences in one pass --> <MSBuild Projects="build.proj" Properties="RestoreProj=%(RestoreProjects.Identity)" Targets="RestorePackage" /> <Message Importance="High" Text="[$([System.DateTime]::Now.ToString('HH:mm:ss.ff'))] Restoring all packages...Done." /> </Target> <Target Name="RestorePackage"> <PropertyGroup> <_ConfigurationProperties>/p:TargetOS=$(TargetOS) /p:TargetArchitecture=$(TargetArchitecture) /p:Configuration=$(Configuration) /p:CrossBuild=$(CrossBuild)</_ConfigurationProperties> <DotnetRestoreCommand Condition="'$(__DistroRid)' == ''">"$(DotNetTool)" restore $(RestoreProj) $(PackageVersionArg) /p:SetTFMForRestore=true $(_ConfigurationProperties)</DotnetRestoreCommand> <DotnetRestoreCommand Condition="'$(__DistroRid)' != ''">"$(DotNetTool)" restore -r $(__DistroRid) $(RestoreProj) $(PackageVersionArg) /p:SetTFMForRestore=true $(_ConfigurationProperties)</DotnetRestoreCommand> </PropertyGroup> <Exec Command="$(DotnetRestoreCommand)"/> </Target> <!-- Override RestorePackages from dir.traversal.targets and do a batch restore --> <Target Name="RestorePackages" DependsOnTargets="BatchRestorePackages" Condition="'$(__SkipRestorePackages)' != '1'" /> <Target Name="ManagedBuild" DependsOnTargets="BuildManagedTestGroups" Condition="'$(__BuildTestWrappersOnly)' != '1' and '$(__GenerateLayoutOnly)' != '1' and '$(__SkipManaged)' != '1' and !$(MonoAot) and !$(MonoFullAot)" /> <Target Name="BuildManagedTestGroups" DependsOnTargets="RestorePackages;ResolveDisabledProjects;BuildNativeAotFrameworkObjects"> <Message Importance="High" Text="$(MsgPrefix)Building managed test components" /> <!-- Execute msbuild test build in stages - workaround for excessive data retention in MSBuild ConfigCache --> <!-- See https://github.com/Microsoft/msbuild/issues/2993 --> <!-- We need to build group #1 manually as it doesn't have a _GroupStartsWith item associated with it, see the comment in Common\dirs.proj --> <MSBuild Projects="$(MSBuildThisFileFullPath)" Targets="BuildManagedTestGroup" Properties="__TestGroupToBuild=1;__SkipRestorePackages=1" /> <MSBuild Projects="$(MSBuildThisFileFullPath)" Targets="BuildManagedTestGroup" Properties="__TestGroupToBuild=%(_GroupStartsWith.GroupNumber);__SkipRestorePackages=1" /> </Target> <Target Name="BuildManagedTestGroup" DependsOnTargets="ResolveDisabledProjects" Condition="'$(__SkipManaged)' != '1'" > <PropertyGroup> <TargetToBuild>Build</TargetToBuild> <!-- In split pipeline mode (in the lab) we're using the native component copying step to generate the test execution scripts --> <TargetToBuild Condition="'$(__CopyNativeTestBinaries)' == '1'">CopyAllNativeTestProjectBinaries</TargetToBuild> <GroupBuildCmd>$(DotNetCli) msbuild</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) $(MSBuildThisFileFullPath)</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) /t:$(TargetToBuild)</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:TargetArchitecture=$(TargetArchitecture)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:Configuration=$(Configuration)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:LibrariesConfiguration=$(LibrariesConfiguration)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:TargetOS=$(TargetOS)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:RuntimeOS=$(RuntimeOS)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:RuntimeFlavor=$(RuntimeFlavor)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:RuntimeVariant=$(RuntimeVariant)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:CLRTestBuildAllTargets=$(CLRTestBuildAllTargets)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:__TestGroupToBuild=$(__TestGroupToBuild)"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) "/p:__SkipRestorePackages=1"</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) /nodeReuse:false</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) /maxcpucount</GroupBuildCmd> <GroupBuildCmd>$(GroupBuildCmd) /bl:$(ArtifactsDir)/log/$(Configuration)/InnerManagedTestBuild.$(__TestGroupToBuild).binlog</GroupBuildCmd> <GroupBuildCmd Condition="'$(TestBuildMode)' == 'nativeaot'">$(GroupBuildCmd) "/p:DefaultBuildAllTarget=BuildNativeAot"</GroupBuildCmd> <GroupBuildCmd Condition="'$(IlcMultiModule)' == 'true'">$(GroupBuildCmd) "/p:IlcMultiModule=true"</GroupBuildCmd> <GroupBuildCmd Condition="'$(BuildNativeAotFrameworkObjects)' == 'true'">$(GroupBuildCmd) "/p:BuildNativeAotFrameworkObjects=true"</GroupBuildCmd> </PropertyGroup> <Message Importance="High" Text="$(MsgPrefix)Building managed test group $(__TestGroupToBuild): $(GroupBuildCmd)" /> <Exec Command="$(GroupBuildCmd)" /> </Target> <Target Name="CheckTestBuildStep" DependsOnTargets="CheckTestBuild" Condition="'$(__BuildTestWrappersOnly)' != '1' and '$(__GenerateLayoutOnly)' != '1' and '$(__CopyNativeTestBinaries)' != '1' and !$(MonoAot) and !$(MonoFullAot)" /> <Target Name="GenerateLayout" DependsOnTargets="CreateTestOverlay" AfterTargets="ManagedBuild;RestorePackages" Condition="'$(__BuildTestWrappersOnly)' != '1' and '$(__CopyNativeTestBinaries)' != '1' and '$(__SkipGenerateLayout)' != '1' and !$(MonoAot) and !$(MonoFullAot)" /> <Target Name="BuildTestWrappers" DependsOnTargets="CreateAllWrappers" AfterTargets="ManagedBuild;RestorePackages" Condition="'$(__GenerateLayoutOnly)' != '1' and '$(__CopyNativeTestBinaries)' != '1' and !$(MonoAot) and !$(MonoFullAot) and ('$(__BuildTestWrappersOnly)' == '1' or ('$(__SkipTestWrappers)' != '1' and '$(__SkipManaged)' != '1'))" /> <Target Name="CrossgenFramework" DependsOnTargets="GenerateLayout" Condition="'$(__BuildTestWrappersOnly)' != '1' and '$(__CopyNativeTestBinaries)' != '1' and '$(__TestBuildMode)' == 'crossgen2' and !$(MonoAot) and !$(MonoFullAot)" > <PropertyGroup> <CrossgenDir>$(__BinDir)</CrossgenDir> <CrossgenDir Condition="'$(TargetArchitecture)' == 'arm'">$(CrossgenDir)\x64</CrossgenDir> <CrossgenDir Condition="'$(TargetArchitecture)' == 'arm64'">$(CrossgenDir)\x64</CrossgenDir> <CrossgenDir Condition="'$(TargetArchitecture)' == 'x86'">$(CrossgenDir)\x64</CrossgenDir> <CrossgenOutputDir>$(__TestIntermediatesDir)\crossgen.out</CrossgenOutputDir> <CrossgenCmd>$(DotNetCli)</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) "$(CORE_ROOT)\R2RTest\R2RTest.dll"</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) compile-framework</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) -cr "$(CORE_ROOT)"</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) --output-directory "$(CrossgenOutputDir)"</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) --release</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) --nocleanup</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) --target-arch $(TargetArchitecture)</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) -dop $(NUMBER_OF_PROCESSORS)</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) -m "$(CORE_ROOT)\StandardOptimizationData.mibc"</CrossgenCmd> <CrossgenCmd Condition="'$(__CreatePdb)' != ''">$(CrossgenCmd) --pdb</CrossgenCmd> <CrossgenCmd Condition="'$(__CreatePerfmap)' != ''">$(CrossgenCmd) --perfmap --perfmap-format-version 1</CrossgenCmd> <CrossgenCmd Condition="'$(__CompositeBuildMode)' != ''">$(CrossgenCmd) --composite</CrossgenCmd> <CrossgenCmd Condition="'$(__CompositeBuildMode)' == ''">$(CrossgenCmd) --crossgen2-parallelism 1</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) --verify-type-and-field-layout</CrossgenCmd> <CrossgenCmd>$(CrossgenCmd) --crossgen2-path "$(CrossgenDir)\crossgen2\crossgen2.dll"</CrossgenCmd> </PropertyGroup> <Message Importance="High" Text="$(MsgPrefix)Compiling framework using Crossgen2: $(CrossgenCmd)" /> <Exec Command="$(CrossgenCmd)" /> <ItemGroup> <CrossgenOutputFiles Include="$(CrossgenOutputDir)\*.dll" /> <CrossgenOutputFiles Include="$(CrossgenOutputDir)\*.ni.pdb" Condition="'$(__CreatePdb)' != ''" /> <CrossgenOutputFiles Include="$(CrossgenOutputDir)\*.ni.r2rmap" Condition="'$(__CreatePerfmap)' != ''" /> </ItemGroup> <Move SourceFiles="@(CrossgenOutputFiles)" DestinationFolder="$(CORE_ROOT)" /> </Target> <Target Name="CreateAndroidApps" DependsOnTargets="BuildAllAndroidApp" AfterTargets="ManagedBuild" Condition="'$(__BuildTestWrappersOnly)' != '1' and '$(__GenerateLayoutOnly)' != '1' and '$(__CopyNativeTestBinaries)' != '1' and $(RunWithAndroid)" /> <Target Name="CreateIosApps" DependsOnTargets="BuildAlliOSApp" AfterTargets="ManagedBuild" Condition="'$(__BuildTestWrappersOnly)' != '1' and '$(__GenerateLayoutOnly)' != '1' and '$(__CopyNativeTestBinaries)' != '1' and ('$(TargetOS)' == 'iOS' or '$(TargetOS)' == 'iOSSimulator')" /> <Target Name="BuildMonoAot" DependsOnTargets="MonoAotCompileTests" AfterTargets="ManagedBuild" Condition="'$(__BuildTestWrappersOnly)' != '1' and '$(__GenerateLayoutOnly)' != '1' and '$(__CopyNativeTestBinaries)' != '1' and ($(MonoAot) or $(MonoFullAot))" /> <Target Name="BuildNativeAotFrameworkObjects" Condition="'$(BuildNativeAotFrameworkObjects)' == 'true' and '$(TestBuildMode)' == 'nativeaot'"> <ItemGroup> <CreateLibProperty Include="IlcToolsPath=$(IlcToolsPath)" /> <CreateLibProperty Include="IlcBuildTasksPath=$(IlcBuildTasksPath)" /> <CreateLibProperty Include="IlcSdkPath=$(IlcSdkPath)" /> <CreateLibProperty Include="IlcFrameworkPath=$(IlcFrameworkPath)" /> <CreateLibProperty Include="FrameworkLibPath=$(IlcSdkPath)" /> <CreateLibProperty Include="FrameworkObjPath=$(IntermediateOutputPath)/NativeAOTFX" /> <CreateLibProperty Condition="'$(Configuration)' == 'Checked' or '$(Configuration)' == 'Release'" Include="Optimize=true" /> <CreateLibProperty Include="NETCoreSdkVersion=6.0.0" /> </ItemGroup> <MSBuild Projects="$(CoreCLRBuildIntegrationDir)/BuildFrameworkNativeObjects.proj" Targets="CreateLib" Properties="@(CreateLibProperty)" /> </Target> </Project>
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/pipelines/installer/jobs/base-job.yml
parameters: buildConfig: '' osGroup: '' archType: '' osSubgroup: '' platform: '' crossBuild: false crossrootfsDir: '' timeoutInMinutes: 120 condition: true shouldContinueOnError: false container: '' buildSteps: [] dependsOn: [] dependsOnGlobalBuild: false dependOnEvaluatePaths: false globalBuildSuffix: '' variables: [] name: '' displayName: '' runtimeVariant: '' pool: '' pgoType: '' packageDistroList: - image: mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-14.04-debpkg-e5cf912-20175003025046 packageType: deb packagingArgs: /p:BuildDebPackage=true - image: mcr.microsoft.com/dotnet-buildtools/prereqs:rhel-7-rpmpkg-c982313-20174116044113 packageType: rpm packagingArgs: /p:BuildRpmPackage=true isOfficialBuild: false buildFullPlatformManifest: false liveRuntimeBuildConfig: '' liveLibrariesBuildConfig: '' runtimeFlavor: 'coreclr' platforms: [] jobs: - job: ${{ format('installer_{0}_{1}_{2}_{3}_{4}_', parameters.pgoType, parameters.runtimeFlavor, parameters.runtimeVariant, coalesce(parameters.name, parameters.platform), parameters.buildConfig) }} displayName: ${{ format('{0} Installer Build and Test {1} {2} {3} {4}', parameters.pgoType, parameters.runtimeFlavor, parameters.runtimeVariant, coalesce(parameters.name, parameters.platform), parameters.buildConfig) }} condition: and(succeeded(), ${{ parameters.condition }}) pool: ${{ parameters.pool }} timeoutInMinutes: ${{ parameters.timeoutInMinutes }} # Do not attempt to clean workspace on Linux: the agent might not be able to remove the files # because they may be owned by "root" due to the way this job uses Docker. We do our own cleanup # in this case as a prepare step. ${{ if ne(parameters.osGroup, 'Linux') }}: workspace: clean: all variables: - ${{ each variable in parameters.variables }}: - ${{ variable }} - name: OfficialBuildArg value: '' - name: SkipTests value: ${{ or( not(in(parameters.archType, 'x64', 'x86')), eq(parameters.runtimeFlavor, 'mono'), eq(parameters.isOfficialBuild, true), eq(parameters.crossBuild, true), eq(parameters.pgoType, 'PGO')) }} - name: BuildAction value: -test - ${{ if eq(variables.SkipTests, true) }}: - name: BuildAction value: '' - name: SignType value: test - name: pgoInstrumentArg value: '' - ${{ if eq(parameters.pgoType, 'PGO' )}}: - name: pgoInstrumentArg value: '-pgoinstrument ' # Set up non-PR build from internal project - ${{ if eq(parameters.isOfficialBuild, true) }}: - name: SignType value: $[ coalesce(variables.OfficialSignType, 'real') ] - name: OfficialBuildArg value: /p:OfficialBuildId=$(Build.BuildNumber) - name: buildCommandSourcesDirectory ${{ if not(in(parameters.osGroup, 'Linux', 'FreeBSD')) }}: value: '$(Build.SourcesDirectory)/' # This job runs within Docker containers, so Build.SourcesDirectory is not accurate. ${{ if in(parameters.osGroup, 'Linux', 'FreeBSD') }}: value: '/root/runtime/' ### ### Platform-specific variable setup ### - ${{ if eq(parameters.osGroup, 'windows') }}: - name: CommonMSBuildArgs value: >- /p:TargetArchitecture=${{ parameters.archType }} /p:PortableBuild=true /p:SkipTests=$(SkipTests) /p:RuntimeFlavor=${{ parameters.runtimeFlavor }} $(OfficialBuildArg) - name: MsbuildSigningArguments value: >- /p:CertificateId=400 /p:DotNetSignType=$(SignType) - name: TargetArchitecture value: ${{ parameters.archType }} - name: BaseJobBuildCommand value: >- build.cmd -subset host+packs -ci $(BuildAction) -configuration $(_BuildConfig) $(pgoInstrumentArg) $(LiveOverridePathArgs) $(CommonMSBuildArgs) $(MsbuildSigningArguments) - ${{ if eq(parameters.osGroup, 'OSX') }}: - name: CommonMSBuildArgs value: >- /p:PortableBuild=true /p:SkipTests=$(SkipTests) /p:RuntimeFlavor=${{ parameters.runtimeFlavor }} /p:TargetArchitecture=${{ parameters.archType }} /p:CrossBuild=${{ parameters.crossBuild }} - name: BaseJobBuildCommand value: >- $(Build.SourcesDirectory)/build.sh -ci $(BuildAction) -configuration $(_BuildConfig) -arch ${{ parameters.archType }} $(LiveOverridePathArgs) $(CommonMSBuildArgs) $(OfficialBuildArg) - ${{ if in(parameters.osGroup, 'iOS', 'tvOS', 'Android', 'Browser') }}: - name: CommonMSBuildArgs value: >- /p:PortableBuild=true /p:SkipTests=$(SkipTests) - name: BaseJobBuildCommand value: >- $(Build.SourcesDirectory)/build.sh -subset packs -ci $(BuildAction) -configuration $(_BuildConfig) -os ${{ parameters.osGroup }} -arch ${{ parameters.archType }} /p:StripSymbols=true $(LiveOverridePathArgs) $(CommonMSBuildArgs) $(OfficialBuildArg) - ${{ if in(parameters.osGroup, 'Linux', 'FreeBSD') }}: # Preserve the NuGet authentication env vars into the Docker container. # The 'NuGetAuthenticate' build step may have set these. - name: PreserveNuGetAuthDockerArgs value: >- -e VSS_NUGET_URI_PREFIXES -e VSS_NUGET_ACCESSTOKEN - ${{ if ne(parameters.container, '') }}: - name: RunArguments value: >- docker run --privileged --rm -v "$(Build.SourcesDirectory):/root/runtime" -w="/root/runtime" $(PreserveNuGetAuthDockerArgs) -e ROOTFS_DIR=${{ parameters.crossrootfsDir }} ${{ parameters.container }} - name: BuildScript value: ./build.sh - name: MSBuildScript value: /root/runtime/eng/common/msbuild.sh - ${{ if eq(parameters.isOfficialBuild, true) }}: - name: BuildScript value: ./eng/install-nuget-credprovider-then-build.sh --subset host+packs - name: MSBuildScript value: /root/runtime/eng/install-nuget-credprovider-then-msbuild.sh - name: CommonMSBuildArgs value: >- /p:Configuration=$(_BuildConfig) /p:TargetOS=${{ parameters.osGroup }} /p:TargetArchitecture=${{ parameters.archType }} /p:RuntimeFlavor=${{ parameters.runtimeFlavor }} $(OfficialBuildArg) - name: _PortableBuild value: ${{ eq(parameters.osSubgroup, '') }} - ${{ if and(eq(parameters.osSubgroup, '_musl'), eq(parameters.osGroup, 'Linux')) }}: # Set output RID manually: musl isn't properly detected. Make sure to also convert linux to # lowercase for RID format. (Detection normally converts, but we're preventing it.) - name: OutputRidArg value: /p:OutputRid=linux-musl-${{ parameters.archType }} - name: RuntimeOSArg value: /p:RuntimeOS=linux-musl - name: _PortableBuild value: true - name: BuildArguments value: >- -subset host+packs -ci $(BuildAction) /p:CrossBuild=${{ parameters.crossBuild }} /p:PortableBuild=$(_PortableBuild) /p:SkipTests=$(SkipTests) $(pgoInstrumentArg) $(LiveOverridePathArgs) $(CommonMSBuildArgs) $(OutputRidArg) $(RuntimeOSArg) - name: PublishArguments value: >- /p:PortableBuild=$(_PortableBuild) $(CommonMSBuildArgs) $(OutputRidArg) /bl:msbuild.publish.binlog - name: DockerRunMSBuild value: >- docker run -v $(Build.SourcesDirectory):/root/runtime -w=/root/runtime $(PreserveNuGetAuthDockerArgs) - name: installersSubsetArg value: --subset packs.installers - name: BaseJobBuildCommand value: | set -x df -h docker info $(RunArguments) $(BuildScript) $(BuildArguments) ### ### Common Live build override variable setup ### - name: LiveOverridePathArgs value: >- $(RuntimeArtifactsArgs) $(LibrariesConfigurationArg) - name: RuntimeArtifactsArgs value: '' - name: LibrariesConfigurationArg value: '' - name: RuntimeDownloadPath value: '' - name: LibrariesDownloadPath value: '' - ${{ if ne(parameters.liveRuntimeBuildConfig, '') }}: - name: liveRuntimeLegName value: ${{ format('{0}{1}_{2}_{3}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveRuntimeBuildConfig) }} - name: RuntimeDownloadPath value: 'artifacts/transport/${{ parameters.runtimeFlavor }}' - name: RuntimeArtifactsArgs value: >- /p:RuntimeArtifactsPath=$(buildCommandSourcesDirectory)$(RuntimeDownloadPath) /p:RuntimeConfiguration=${{ parameters.liveRuntimeBuildConfig }} - name: RuntimeArtifactName value: $(runtimeFlavorName)Product_${{ parameters.pgoType }}_${{ parameters.runtimeVariant }}_$(liveRuntimeLegName) - ${{ if ne(parameters.liveLibrariesBuildConfig, '') }}: - name: liveLibrariesLegName value: ${{ format('{0}{1}_{2}_{3}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveLibrariesBuildConfig) }} - name: LibrariesDownloadPath value: 'artifacts' - name: LibrariesArtifactName value: libraries_bin_$(liveLibrariesLegName) - name: LibrariesConfigurationArg value: ' /p:LibrariesConfiguration=${{ parameters.liveLibrariesBuildConfig }}' dependsOn: - ${{ if eq(parameters.dependOnEvaluatePaths, true) }}: - evaluate_paths - ${{ parameters.dependsOn }} - ${{ if ne(parameters.liveRuntimeBuildConfig, '') }}: - ${{ format('{0}_{1}_product_build_{2}{3}_{4}_{5}{6}', parameters.runtimeFlavor, parameters.runtimeVariant, parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveRuntimeBuildConfig, parameters.pgoType) }} - ${{ if ne(parameters.liveLibrariesBuildConfig, '') }}: - libraries_build_${{ format('{0}{1}_{2}_{3}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveLibrariesBuildConfig) }} steps: - ${{ if ne(parameters.container, '') }}: # Builds don't set user ID, so files might be owned by root and unable to be cleaned up by AzDO. # Clean up the build dirs ourselves in another Docker container to avoid failures. # Using hosted agents is tracked by https://github.com/dotnet/core-setup/issues/4997 - script: | set -x docker run --rm \ -v "$(Agent.BuildDirectory):/root/build" \ -w /root/build \ ${{ parameters.container }} \ bash -c ' rm -v -rf a b s' mkdir "$(Agent.BuildDirectory)/s" displayName: Clean up old artifacts owned by root - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: NuGetAuthenticate@0 - ${{ if eq(parameters.osGroup, 'windows') }}: # NuGet's http cache lasts 30 minutes. If we're on a static machine, this may interfere with # auto-update PRs by preventing the CI build from fetching the new version. Delete the cache. - powershell: Remove-Item -Recurse -ErrorAction Ignore "$env:LocalAppData\NuGet\v3-cache" displayName: Clear NuGet http cache (if exists) - task: MicroBuildSigningPlugin@2 displayName: Install MicroBuild plugin for Signing inputs: signType: $(SignType) zipSources: false feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json continueOnError: false condition: and(succeeded(), in(variables['SignType'], 'real', 'test'), eq(${{ parameters.isOfficialBuild }}, true)) - checkout: self clean: true fetchDepth: $(checkoutFetchDepth) - ${{ if ne(parameters.liveRuntimeBuildConfig, '') }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory)/$(RuntimeDownloadPath) artifactFileName: '$(RuntimeArtifactName)$(archiveExtension)' artifactName: '$(RuntimeArtifactName)' displayName: '$(runtimeFlavorName) artifacts' - ${{ if ne(parameters.liveLibrariesBuildConfig, '') }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory)/$(LibrariesDownloadPath) artifactFileName: '$(LibrariesArtifactName)$(archiveExtension)' artifactName: '$(LibrariesArtifactName)' displayName: 'Libraries artifacts' cleanUnpackFolder: false - ${{ if in(parameters.osGroup, 'OSX', 'iOS', 'tvOS') }}: - script: $(Build.SourcesDirectory)/eng/install-native-dependencies.sh ${{ parameters.osGroup }} ${{ parameters.archType }} azDO displayName: Install Build Dependencies - script: | du -sh $(Build.SourcesDirectory)/* df -h displayName: Disk Usage before Build # Build the default subset non-MacOS platforms - ${{ if ne(parameters.osGroup, 'OSX') }}: - script: $(BaseJobBuildCommand) displayName: Build continueOnError: ${{ and(eq(variables.SkipTests, false), eq(parameters.shouldContinueOnError, true)) }} # Build corehost, sign and add entitlements to MacOS binaries - ${{ if eq(parameters.osGroup, 'OSX') }}: - script: $(BaseJobBuildCommand) -subset host.native displayName: Build CoreHost continueOnError: ${{ and(eq(variables.SkipTests, false), eq(parameters.shouldContinueOnError, true)) }} - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - template: /eng/pipelines/common/macos-sign-with-entitlements.yml parameters: filesToSign: - name: dotnet path: $(Build.SourcesDirectory)/artifacts/bin/osx-${{ parameters.archType }}.$(_BuildConfig)/corehost entitlementsFile: $(Build.SourcesDirectory)/eng/pipelines/common/entitlements.plist - name: apphost path: $(Build.SourcesDirectory)/artifacts/bin/osx-${{ parameters.archType }}.$(_BuildConfig)/corehost entitlementsFile: $(Build.SourcesDirectory)/eng/pipelines/common/entitlements.plist - script: $(BaseJobBuildCommand) -subset host.pkg+host.tools+host.tests+packs displayName: Build and Package continueOnError: ${{ and(eq(variables.SkipTests, false), eq(parameters.shouldContinueOnError, true)) }} - ${{ if in(parameters.osGroup, 'OSX', 'iOS', 'tvOS') }}: - script: | du -sh $(Build.SourcesDirectory)/* df -h displayName: Disk Usage after Build # Only in glibc leg, we produce RPMs and Debs - ${{ if and(eq(parameters.runtimeFlavor, 'coreclr'), or(eq(parameters.platform, 'Linux_x64'), eq(parameters.platform, 'Linux_arm64')), eq(parameters.osSubgroup, ''), eq(parameters.pgoType, ''))}}: - ${{ each packageBuild in parameters.packageDistroList }}: # This leg's RID matches the build image. Build its distro-dependent packages, as well as # the distro-independent installers. (There's no particular reason to build the distro- # independent installers on this leg, but we need to do it somewhere.) # Currently, Linux_arm64 supports 'rpm' type only. - ${{ if or(not(eq(parameters.platform, 'Linux_arm64')), eq(packageBuild.packageType, 'rpm')) }}: - template: steps/build-linux-package.yml parameters: packageType: ${{ packageBuild.packageType }} image: ${{ packageBuild.image }} packageStepDescription: Runtime Deps, Runtime, Framework Packs installers subsetArg: $(installersSubsetArg) packagingArgs: ${{ packageBuild.packagingArgs }} - ${{ if ne(parameters.container, '') }}: # Files may be owned by root because builds don't set user ID. Later build steps run 'find' in # the source tree, which fails due to permissions in the 'NetCore*-Int-Pool' queues. This step # prevents the failure by using chown to clean up our source tree. - script: | set -x docker run --rm \ -v "$(Agent.BuildDirectory):/root/build" \ -w /root/build \ ${{ parameters.container }} \ bash -c "chown -R $(id -u):$(id -g) *" displayName: Update file ownership from root to build agent account continueOnError: true condition: succeededOrFailed() - ${{ if and(eq(parameters.osGroup, 'windows'), eq(parameters.isOfficialBuild, true)) }}: - task: NuGetCommand@2 displayName: Push Visual Studio NuPkgs inputs: command: push packagesToPush: '$(Build.SourcesDirectory)/artifacts/packages/$(_BuildConfig)/*/VS.Redist.Common.*.nupkg' nuGetFeedType: external publishFeedCredentials: 'DevDiv - VS package feed' condition: and( succeeded(), eq(variables['_BuildConfig'], 'Release'), ne(variables['DisableVSPublish'], 'true'), ne(variables['PostBuildSign'], 'true')) - template: steps/upload-job-artifacts.yml parameters: name: ${{ coalesce(parameters.name, parameters.platform) }} runtimeFlavor: ${{ parameters.runtimeFlavor }} runtimeVariant: ${{ parameters.runtimeVariant }} skipTests: $(SkipTests) isOfficialBuild: ${{ eq(parameters.isOfficialBuild, true) }} pgoType: ${{ parameters.pgoType }} - ${{ if ne(parameters.osGroup, 'windows') }}: - script: set -x && df -h displayName: Check remaining storage space condition: always() continueOnError: true # Force clean up machine in case any docker images are left behind - ${{ if ne(parameters.container, '') }}: - script: docker system prune -af && df -h displayName: Run Docker clean up condition: succeededOrFailed()
parameters: buildConfig: '' osGroup: '' archType: '' osSubgroup: '' platform: '' crossBuild: false crossrootfsDir: '' timeoutInMinutes: 120 condition: true shouldContinueOnError: false container: '' buildSteps: [] dependsOn: [] dependsOnGlobalBuild: false dependOnEvaluatePaths: false globalBuildSuffix: '' variables: [] name: '' displayName: '' runtimeVariant: '' pool: '' pgoType: '' packageDistroList: - image: mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-14.04-debpkg-e5cf912-20175003025046 packageType: deb packagingArgs: /p:BuildDebPackage=true - image: mcr.microsoft.com/dotnet-buildtools/prereqs:rhel-7-rpmpkg-c982313-20174116044113 packageType: rpm packagingArgs: /p:BuildRpmPackage=true isOfficialBuild: false buildFullPlatformManifest: false liveRuntimeBuildConfig: '' liveLibrariesBuildConfig: '' runtimeFlavor: 'coreclr' platforms: [] jobs: - job: ${{ format('installer_{0}_{1}_{2}_{3}_{4}_', parameters.pgoType, parameters.runtimeFlavor, parameters.runtimeVariant, coalesce(parameters.name, parameters.platform), parameters.buildConfig) }} displayName: ${{ format('{0} Installer Build and Test {1} {2} {3} {4}', parameters.pgoType, parameters.runtimeFlavor, parameters.runtimeVariant, coalesce(parameters.name, parameters.platform), parameters.buildConfig) }} condition: and(succeeded(), ${{ parameters.condition }}) pool: ${{ parameters.pool }} timeoutInMinutes: ${{ parameters.timeoutInMinutes }} # Do not attempt to clean workspace on Linux: the agent might not be able to remove the files # because they may be owned by "root" due to the way this job uses Docker. We do our own cleanup # in this case as a prepare step. ${{ if ne(parameters.osGroup, 'Linux') }}: workspace: clean: all variables: - ${{ each variable in parameters.variables }}: - ${{ variable }} - name: OfficialBuildArg value: '' - name: SkipTests value: ${{ or( not(in(parameters.archType, 'x64', 'x86')), eq(parameters.runtimeFlavor, 'mono'), eq(parameters.isOfficialBuild, true), eq(parameters.crossBuild, true), eq(parameters.pgoType, 'PGO')) }} - name: BuildAction value: -test - ${{ if eq(variables.SkipTests, true) }}: - name: BuildAction value: '' - name: SignType value: test - name: pgoInstrumentArg value: '' - ${{ if eq(parameters.pgoType, 'PGO' )}}: - name: pgoInstrumentArg value: '-pgoinstrument ' # Set up non-PR build from internal project - ${{ if eq(parameters.isOfficialBuild, true) }}: - name: SignType value: $[ coalesce(variables.OfficialSignType, 'real') ] - name: OfficialBuildArg value: /p:OfficialBuildId=$(Build.BuildNumber) - name: buildCommandSourcesDirectory ${{ if not(in(parameters.osGroup, 'Linux', 'FreeBSD')) }}: value: '$(Build.SourcesDirectory)/' # This job runs within Docker containers, so Build.SourcesDirectory is not accurate. ${{ if in(parameters.osGroup, 'Linux', 'FreeBSD') }}: value: '/root/runtime/' ### ### Platform-specific variable setup ### - ${{ if eq(parameters.osGroup, 'windows') }}: - name: CommonMSBuildArgs value: >- /p:TargetArchitecture=${{ parameters.archType }} /p:PortableBuild=true /p:SkipTests=$(SkipTests) /p:RuntimeFlavor=${{ parameters.runtimeFlavor }} $(OfficialBuildArg) - name: MsbuildSigningArguments value: >- /p:CertificateId=400 /p:DotNetSignType=$(SignType) - name: TargetArchitecture value: ${{ parameters.archType }} - name: BaseJobBuildCommand value: >- build.cmd -subset host+packs -ci $(BuildAction) -configuration $(_BuildConfig) $(pgoInstrumentArg) $(LiveOverridePathArgs) $(CommonMSBuildArgs) $(MsbuildSigningArguments) - ${{ if eq(parameters.osGroup, 'OSX') }}: - name: CommonMSBuildArgs value: >- /p:PortableBuild=true /p:SkipTests=$(SkipTests) /p:RuntimeFlavor=${{ parameters.runtimeFlavor }} /p:TargetArchitecture=${{ parameters.archType }} /p:CrossBuild=${{ parameters.crossBuild }} - name: BaseJobBuildCommand value: >- $(Build.SourcesDirectory)/build.sh -ci $(BuildAction) -configuration $(_BuildConfig) -arch ${{ parameters.archType }} $(LiveOverridePathArgs) $(CommonMSBuildArgs) $(OfficialBuildArg) - ${{ if in(parameters.osGroup, 'iOS', 'tvOS', 'Android', 'Browser') }}: - name: CommonMSBuildArgs value: >- /p:PortableBuild=true /p:SkipTests=$(SkipTests) - name: BaseJobBuildCommand value: >- $(Build.SourcesDirectory)/build.sh -subset packs -ci $(BuildAction) -configuration $(_BuildConfig) -os ${{ parameters.osGroup }} -arch ${{ parameters.archType }} /p:StripSymbols=true $(LiveOverridePathArgs) $(CommonMSBuildArgs) $(OfficialBuildArg) - ${{ if in(parameters.osGroup, 'Linux', 'FreeBSD') }}: # Preserve the NuGet authentication env vars into the Docker container. # The 'NuGetAuthenticate' build step may have set these. - name: PreserveNuGetAuthDockerArgs value: >- -e VSS_NUGET_URI_PREFIXES -e VSS_NUGET_ACCESSTOKEN - ${{ if ne(parameters.container, '') }}: - name: RunArguments value: >- docker run --privileged --rm -v "$(Build.SourcesDirectory):/root/runtime" -w="/root/runtime" $(PreserveNuGetAuthDockerArgs) -e ROOTFS_DIR=${{ parameters.crossrootfsDir }} ${{ parameters.container }} - name: BuildScript value: ./build.sh - name: MSBuildScript value: /root/runtime/eng/common/msbuild.sh - ${{ if eq(parameters.isOfficialBuild, true) }}: - name: BuildScript value: ./eng/install-nuget-credprovider-then-build.sh --subset host+packs - name: MSBuildScript value: /root/runtime/eng/install-nuget-credprovider-then-msbuild.sh - name: CommonMSBuildArgs value: >- /p:Configuration=$(_BuildConfig) /p:TargetOS=${{ parameters.osGroup }} /p:TargetArchitecture=${{ parameters.archType }} /p:RuntimeFlavor=${{ parameters.runtimeFlavor }} $(OfficialBuildArg) - name: _PortableBuild value: ${{ eq(parameters.osSubgroup, '') }} - ${{ if and(eq(parameters.osSubgroup, '_musl'), eq(parameters.osGroup, 'Linux')) }}: # Set output RID manually: musl isn't properly detected. Make sure to also convert linux to # lowercase for RID format. (Detection normally converts, but we're preventing it.) - name: OutputRidArg value: /p:OutputRid=linux-musl-${{ parameters.archType }} - name: RuntimeOSArg value: /p:RuntimeOS=linux-musl - name: _PortableBuild value: true - name: BuildArguments value: >- -subset host+packs -ci $(BuildAction) /p:CrossBuild=${{ parameters.crossBuild }} /p:PortableBuild=$(_PortableBuild) /p:SkipTests=$(SkipTests) $(pgoInstrumentArg) $(LiveOverridePathArgs) $(CommonMSBuildArgs) $(OutputRidArg) $(RuntimeOSArg) - name: PublishArguments value: >- /p:PortableBuild=$(_PortableBuild) $(CommonMSBuildArgs) $(OutputRidArg) /bl:msbuild.publish.binlog - name: DockerRunMSBuild value: >- docker run -v $(Build.SourcesDirectory):/root/runtime -w=/root/runtime $(PreserveNuGetAuthDockerArgs) - name: installersSubsetArg value: --subset packs.installers - name: BaseJobBuildCommand value: | set -x df -h docker info $(RunArguments) $(BuildScript) $(BuildArguments) ### ### Common Live build override variable setup ### - name: LiveOverridePathArgs value: >- $(RuntimeArtifactsArgs) $(LibrariesConfigurationArg) - name: RuntimeArtifactsArgs value: '' - name: LibrariesConfigurationArg value: '' - name: RuntimeDownloadPath value: '' - name: LibrariesDownloadPath value: '' - ${{ if ne(parameters.liveRuntimeBuildConfig, '') }}: - name: liveRuntimeLegName value: ${{ format('{0}{1}_{2}_{3}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveRuntimeBuildConfig) }} - name: RuntimeDownloadPath value: 'artifacts/transport/${{ parameters.runtimeFlavor }}' - name: RuntimeArtifactsArgs value: >- /p:RuntimeArtifactsPath=$(buildCommandSourcesDirectory)$(RuntimeDownloadPath) /p:RuntimeConfiguration=${{ parameters.liveRuntimeBuildConfig }} - name: RuntimeArtifactName value: $(runtimeFlavorName)Product_${{ parameters.pgoType }}_${{ parameters.runtimeVariant }}_$(liveRuntimeLegName) - ${{ if ne(parameters.liveLibrariesBuildConfig, '') }}: - name: liveLibrariesLegName value: ${{ format('{0}{1}_{2}_{3}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveLibrariesBuildConfig) }} - name: LibrariesDownloadPath value: 'artifacts' - name: LibrariesArtifactName value: libraries_bin_$(liveLibrariesLegName) - name: LibrariesConfigurationArg value: ' /p:LibrariesConfiguration=${{ parameters.liveLibrariesBuildConfig }}' dependsOn: - ${{ if eq(parameters.dependOnEvaluatePaths, true) }}: - evaluate_paths - ${{ parameters.dependsOn }} - ${{ if ne(parameters.liveRuntimeBuildConfig, '') }}: - ${{ format('{0}_{1}_product_build_{2}{3}_{4}_{5}{6}', parameters.runtimeFlavor, parameters.runtimeVariant, parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveRuntimeBuildConfig, parameters.pgoType) }} - ${{ if ne(parameters.liveLibrariesBuildConfig, '') }}: - libraries_build_${{ format('{0}{1}_{2}_{3}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveLibrariesBuildConfig) }} steps: - ${{ if ne(parameters.container, '') }}: # Builds don't set user ID, so files might be owned by root and unable to be cleaned up by AzDO. # Clean up the build dirs ourselves in another Docker container to avoid failures. # Using hosted agents is tracked by https://github.com/dotnet/core-setup/issues/4997 - script: | set -x docker run --rm \ -v "$(Agent.BuildDirectory):/root/build" \ -w /root/build \ ${{ parameters.container }} \ bash -c ' rm -v -rf a b s' mkdir "$(Agent.BuildDirectory)/s" displayName: Clean up old artifacts owned by root - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: NuGetAuthenticate@0 - ${{ if eq(parameters.osGroup, 'windows') }}: # NuGet's http cache lasts 30 minutes. If we're on a static machine, this may interfere with # auto-update PRs by preventing the CI build from fetching the new version. Delete the cache. - powershell: Remove-Item -Recurse -ErrorAction Ignore "$env:LocalAppData\NuGet\v3-cache" displayName: Clear NuGet http cache (if exists) - task: MicroBuildSigningPlugin@2 displayName: Install MicroBuild plugin for Signing inputs: signType: $(SignType) zipSources: false feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json continueOnError: false condition: and(succeeded(), in(variables['SignType'], 'real', 'test'), eq(${{ parameters.isOfficialBuild }}, true)) - checkout: self clean: true fetchDepth: $(checkoutFetchDepth) - ${{ if ne(parameters.liveRuntimeBuildConfig, '') }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory)/$(RuntimeDownloadPath) artifactFileName: '$(RuntimeArtifactName)$(archiveExtension)' artifactName: '$(RuntimeArtifactName)' displayName: '$(runtimeFlavorName) artifacts' - ${{ if ne(parameters.liveLibrariesBuildConfig, '') }}: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: $(Build.SourcesDirectory)/$(LibrariesDownloadPath) artifactFileName: '$(LibrariesArtifactName)$(archiveExtension)' artifactName: '$(LibrariesArtifactName)' displayName: 'Libraries artifacts' cleanUnpackFolder: false - ${{ if in(parameters.osGroup, 'OSX', 'iOS', 'tvOS') }}: - script: $(Build.SourcesDirectory)/eng/install-native-dependencies.sh ${{ parameters.osGroup }} ${{ parameters.archType }} azDO displayName: Install Build Dependencies - script: | du -sh $(Build.SourcesDirectory)/* df -h displayName: Disk Usage before Build # Build the default subset non-MacOS platforms - ${{ if ne(parameters.osGroup, 'OSX') }}: - script: $(BaseJobBuildCommand) displayName: Build continueOnError: ${{ and(eq(variables.SkipTests, false), eq(parameters.shouldContinueOnError, true)) }} # Build corehost, sign and add entitlements to MacOS binaries - ${{ if eq(parameters.osGroup, 'OSX') }}: - script: $(BaseJobBuildCommand) -subset host.native displayName: Build CoreHost continueOnError: ${{ and(eq(variables.SkipTests, false), eq(parameters.shouldContinueOnError, true)) }} - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - template: /eng/pipelines/common/macos-sign-with-entitlements.yml parameters: filesToSign: - name: dotnet path: $(Build.SourcesDirectory)/artifacts/bin/osx-${{ parameters.archType }}.$(_BuildConfig)/corehost entitlementsFile: $(Build.SourcesDirectory)/eng/pipelines/common/entitlements.plist - name: apphost path: $(Build.SourcesDirectory)/artifacts/bin/osx-${{ parameters.archType }}.$(_BuildConfig)/corehost entitlementsFile: $(Build.SourcesDirectory)/eng/pipelines/common/entitlements.plist - script: $(BaseJobBuildCommand) -subset host.pkg+host.tools+host.tests+packs displayName: Build and Package continueOnError: ${{ and(eq(variables.SkipTests, false), eq(parameters.shouldContinueOnError, true)) }} - ${{ if in(parameters.osGroup, 'OSX', 'iOS', 'tvOS') }}: - script: | du -sh $(Build.SourcesDirectory)/* df -h displayName: Disk Usage after Build # Only in glibc leg, we produce RPMs and Debs - ${{ if and(eq(parameters.runtimeFlavor, 'coreclr'), or(eq(parameters.platform, 'Linux_x64'), eq(parameters.platform, 'Linux_arm64')), eq(parameters.osSubgroup, ''), eq(parameters.pgoType, ''))}}: - ${{ each packageBuild in parameters.packageDistroList }}: # This leg's RID matches the build image. Build its distro-dependent packages, as well as # the distro-independent installers. (There's no particular reason to build the distro- # independent installers on this leg, but we need to do it somewhere.) # Currently, Linux_arm64 supports 'rpm' type only. - ${{ if or(not(eq(parameters.platform, 'Linux_arm64')), eq(packageBuild.packageType, 'rpm')) }}: - template: steps/build-linux-package.yml parameters: packageType: ${{ packageBuild.packageType }} image: ${{ packageBuild.image }} packageStepDescription: Runtime Deps, Runtime, Framework Packs installers subsetArg: $(installersSubsetArg) packagingArgs: ${{ packageBuild.packagingArgs }} - ${{ if ne(parameters.container, '') }}: # Files may be owned by root because builds don't set user ID. Later build steps run 'find' in # the source tree, which fails due to permissions in the 'NetCore*-Int-Pool' queues. This step # prevents the failure by using chown to clean up our source tree. - script: | set -x docker run --rm \ -v "$(Agent.BuildDirectory):/root/build" \ -w /root/build \ ${{ parameters.container }} \ bash -c "chown -R $(id -u):$(id -g) *" displayName: Update file ownership from root to build agent account continueOnError: true condition: succeededOrFailed() - ${{ if and(eq(parameters.osGroup, 'windows'), eq(parameters.isOfficialBuild, true)) }}: - task: NuGetCommand@2 displayName: Push Visual Studio NuPkgs inputs: command: push packagesToPush: '$(Build.SourcesDirectory)/artifacts/packages/$(_BuildConfig)/*/VS.Redist.Common.*.nupkg' nuGetFeedType: external publishFeedCredentials: 'DevDiv - VS package feed' condition: and( succeeded(), eq(variables['_BuildConfig'], 'Release'), ne(variables['DisableVSPublish'], 'true'), ne(variables['PostBuildSign'], 'true')) - template: steps/upload-job-artifacts.yml parameters: name: ${{ coalesce(parameters.name, parameters.platform) }} runtimeFlavor: ${{ parameters.runtimeFlavor }} runtimeVariant: ${{ parameters.runtimeVariant }} skipTests: $(SkipTests) isOfficialBuild: ${{ eq(parameters.isOfficialBuild, true) }} pgoType: ${{ parameters.pgoType }} - ${{ if ne(parameters.osGroup, 'windows') }}: - script: set -x && df -h displayName: Check remaining storage space condition: always() continueOnError: true # Force clean up machine in case any docker images are left behind - ${{ if ne(parameters.container, '') }}: - script: docker system prune -af && df -h displayName: Run Docker clean up condition: succeededOrFailed()
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/actions/backport/action.yml
name: 'PR Backporter' description: 'Backports a pull request to a branch using the "/backport to <branch>" comment' inputs: target_branch: description: 'Backport target branch.' auth_token: description: 'The token used to authenticate to GitHub.' pr_title_template: description: 'The template used for the PR title. Special placeholder tokens that will be replaced with a value: %target_branch%, %source_pr_title%, %source_pr_number%, %cc_users%.' default: '[%target_branch%] %source_pr_title%' pr_description_template: description: 'The template used for the PR description. Special placeholder tokens that will be replaced with a value: %target_branch%, %source_pr_title%, %source_pr_number%, %cc_users%.' default: | Backport of #%source_pr_number% to %target_branch% /cc %cc_users% runs: using: 'node12' main: 'index.js'
name: 'PR Backporter' description: 'Backports a pull request to a branch using the "/backport to <branch>" comment' inputs: target_branch: description: 'Backport target branch.' auth_token: description: 'The token used to authenticate to GitHub.' pr_title_template: description: 'The template used for the PR title. Special placeholder tokens that will be replaced with a value: %target_branch%, %source_pr_title%, %source_pr_number%, %cc_users%.' default: '[%target_branch%] %source_pr_title%' pr_description_template: description: 'The template used for the PR description. Special placeholder tokens that will be replaced with a value: %target_branch%, %source_pr_title%, %source_pr_number%, %cc_users%.' default: | Backport of #%source_pr_number% to %target_branch% /cc %cc_users% runs: using: 'node12' main: 'index.js'
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/coreclr/scripts/exploratory.proj
<Project Sdk="Microsoft.DotNet.Helix.Sdk" DefaultTargets="Test"> <PropertyGroup Condition="'$(AGENT_OS)' == 'Windows_NT'"> <FileSeparatorChar>\</FileSeparatorChar> </PropertyGroup> <PropertyGroup Condition="'$(AGENT_OS)' != 'Windows_NT'"> <FileSeparatorChar>/</FileSeparatorChar> </PropertyGroup> <PropertyGroup Condition="'$(AGENT_OS)' == 'Windows_NT'"> <Python>%HELIX_PYTHONPATH%</Python> <OutputDirectory>%HELIX_WORKITEM_UPLOAD_ROOT%</OutputDirectory> <CoreRoot>%HELIX_CORRELATION_PAYLOAD%\CoreRoot</CoreRoot> <ToolPath>%HELIX_CORRELATION_PAYLOAD%\exploratory</ToolPath> <!-- Workaround until https://github.com/dotnet/arcade/pull/6179 is not available --> <HelixResultsDestinationDir>$(BUILD_SOURCESDIRECTORY)\artifacts\helixresults</HelixResultsDestinationDir> </PropertyGroup> <PropertyGroup Condition="'$(AGENT_OS)' != 'Windows_NT'"> <Python>$HELIX_PYTHONPATH</Python> <OutputDirectory>$HELIX_WORKITEM_UPLOAD_ROOT</OutputDirectory> <CoreRoot>$HELIX_CORRELATION_PAYLOAD/CoreRoot</CoreRoot> <ToolPath>$HELIX_CORRELATION_PAYLOAD/exploratory</ToolPath> <!-- Workaround until https://github.com/dotnet/arcade/pull/6179 is not available --> <HelixResultsDestinationDir>$(BUILD_SOURCESDIRECTORY)/artifacts/helixresults</HelixResultsDestinationDir> </PropertyGroup> <PropertyGroup> <EnableAzurePipelinesReporter>false</EnableAzurePipelinesReporter> <EnableXUnitReporter>false</EnableXUnitReporter> <Creator>$(_Creator)</Creator> <HelixAccessToken>$(_HelixAccessToken)</HelixAccessToken> <HelixBuild>$(_HelixBuild)</HelixBuild> <HelixSource>$(_HelixSource)</HelixSource> <HelixTargetQueues>$(_HelixTargetQueues)</HelixTargetQueues> <HelixType>$(_HelixType)</HelixType> </PropertyGroup> <!-- For Scheduled= 3 hours. For PRs= 1 hour --> <PropertyGroup Condition=" '$(RunReason)' == 'Scheduled' "> <WorkItemTimeout>3:30</WorkItemTimeout> <RunDuration>180</RunDuration> </PropertyGroup> <PropertyGroup Condition=" '$(RunReason)' != 'Scheduled' "> <WorkItemTimeout>1:30</WorkItemTimeout> <RunDuration>60</RunDuration> </PropertyGroup> <ItemGroup Condition=" '$(AGENT_OS)' == 'Windows_NT' "> <HelixPreCommand Include="taskkill.exe /f /im corerun.exe"/> <HelixPostCommand Include="taskkill.exe /f /im corerun.exe&amp;del /s /q %HELIX_DUMP_FOLDER%\*"/> </ItemGroup> <ItemGroup Condition=" '$(AGENT_OS)' != 'Windows_NT' "> <HelixPostCommand Include="rm -r -f $HELIX_DUMP_FOLDER/*"/> </ItemGroup> <PropertyGroup> <HelixPreCommands>@(HelixPreCommand)</HelixPreCommands> <HelixPostCommands>@(HelixPostCommand)</HelixPostCommands> </PropertyGroup> <PropertyGroup Condition=" '$(ToolName)' == 'Antigen' "> <WorkItemCommand>$(Python) $(CoreRoot)$(FileSeparatorChar)antigen_run.py -run_configuration $(RunConfiguration) -output_directory $(OutputDirectory) -antigen_directory $(ToolPath) -core_root $(CoreRoot) -run_duration $(RunDuration) </WorkItemCommand> </PropertyGroup> <PropertyGroup Condition=" '$(ToolName)' == 'Fuzzlyn' "> <WorkItemCommand>$(Python) $(CoreRoot)$(FileSeparatorChar)fuzzlyn_run.py -run_configuration $(RunConfiguration) -output_directory $(OutputDirectory) -fuzzlyn_directory $(ToolPath) -core_root $(CoreRoot) -run_duration $(RunDuration)</WorkItemCommand> </PropertyGroup> <ItemGroup> <HelixCorrelationPayload Include="$(CorrelationPayloadDirectory)"> <PayloadDirectory>%(Identity)</PayloadDirectory> </HelixCorrelationPayload> </ItemGroup> <ItemGroup> <Run_Partition Include="Partition0" Index="0" /> <Run_Partition Include="Partition1" Index="1" /> <Run_Partition Include="Partition2" Index="2" /> <Run_Partition Include="Partition3" Index="3" /> </ItemGroup> <ItemGroup> <HelixWorkItem Include="@(Run_Partition)"> <PartitionName>Partition%(HelixWorkItem.Index)</PartitionName> <PayloadDirectory>$(WorkItemDirectory)</PayloadDirectory> <Command>$(WorkItemCommand) -partition %(PartitionName)</Command> <Timeout>$(WorkItemTimeout)</Timeout> <DownloadFilesFromResults>AllIssues-$(RunConfiguration)-%(PartitionName).zip;issues-summary-$(RunConfiguration)-%(PartitionName).txt;$(ToolName)-$(RunConfiguration)-%(PartitionName).log</DownloadFilesFromResults> </HelixWorkItem> </ItemGroup> </Project>
<Project Sdk="Microsoft.DotNet.Helix.Sdk" DefaultTargets="Test"> <PropertyGroup Condition="'$(AGENT_OS)' == 'Windows_NT'"> <FileSeparatorChar>\</FileSeparatorChar> </PropertyGroup> <PropertyGroup Condition="'$(AGENT_OS)' != 'Windows_NT'"> <FileSeparatorChar>/</FileSeparatorChar> </PropertyGroup> <PropertyGroup Condition="'$(AGENT_OS)' == 'Windows_NT'"> <Python>%HELIX_PYTHONPATH%</Python> <OutputDirectory>%HELIX_WORKITEM_UPLOAD_ROOT%</OutputDirectory> <CoreRoot>%HELIX_CORRELATION_PAYLOAD%\CoreRoot</CoreRoot> <ToolPath>%HELIX_CORRELATION_PAYLOAD%\exploratory</ToolPath> <!-- Workaround until https://github.com/dotnet/arcade/pull/6179 is not available --> <HelixResultsDestinationDir>$(BUILD_SOURCESDIRECTORY)\artifacts\helixresults</HelixResultsDestinationDir> </PropertyGroup> <PropertyGroup Condition="'$(AGENT_OS)' != 'Windows_NT'"> <Python>$HELIX_PYTHONPATH</Python> <OutputDirectory>$HELIX_WORKITEM_UPLOAD_ROOT</OutputDirectory> <CoreRoot>$HELIX_CORRELATION_PAYLOAD/CoreRoot</CoreRoot> <ToolPath>$HELIX_CORRELATION_PAYLOAD/exploratory</ToolPath> <!-- Workaround until https://github.com/dotnet/arcade/pull/6179 is not available --> <HelixResultsDestinationDir>$(BUILD_SOURCESDIRECTORY)/artifacts/helixresults</HelixResultsDestinationDir> </PropertyGroup> <PropertyGroup> <EnableAzurePipelinesReporter>false</EnableAzurePipelinesReporter> <EnableXUnitReporter>false</EnableXUnitReporter> <Creator>$(_Creator)</Creator> <HelixAccessToken>$(_HelixAccessToken)</HelixAccessToken> <HelixBuild>$(_HelixBuild)</HelixBuild> <HelixSource>$(_HelixSource)</HelixSource> <HelixTargetQueues>$(_HelixTargetQueues)</HelixTargetQueues> <HelixType>$(_HelixType)</HelixType> </PropertyGroup> <!-- For Scheduled= 3 hours. For PRs= 1 hour --> <PropertyGroup Condition=" '$(RunReason)' == 'Scheduled' "> <WorkItemTimeout>3:30</WorkItemTimeout> <RunDuration>180</RunDuration> </PropertyGroup> <PropertyGroup Condition=" '$(RunReason)' != 'Scheduled' "> <WorkItemTimeout>1:30</WorkItemTimeout> <RunDuration>60</RunDuration> </PropertyGroup> <ItemGroup Condition=" '$(AGENT_OS)' == 'Windows_NT' "> <HelixPreCommand Include="taskkill.exe /f /im corerun.exe"/> <HelixPostCommand Include="taskkill.exe /f /im corerun.exe&amp;del /s /q %HELIX_DUMP_FOLDER%\*"/> </ItemGroup> <ItemGroup Condition=" '$(AGENT_OS)' != 'Windows_NT' "> <HelixPostCommand Include="rm -r -f $HELIX_DUMP_FOLDER/*"/> </ItemGroup> <PropertyGroup> <HelixPreCommands>@(HelixPreCommand)</HelixPreCommands> <HelixPostCommands>@(HelixPostCommand)</HelixPostCommands> </PropertyGroup> <PropertyGroup Condition=" '$(ToolName)' == 'Antigen' "> <WorkItemCommand>$(Python) $(CoreRoot)$(FileSeparatorChar)antigen_run.py -run_configuration $(RunConfiguration) -output_directory $(OutputDirectory) -antigen_directory $(ToolPath) -core_root $(CoreRoot) -run_duration $(RunDuration) </WorkItemCommand> </PropertyGroup> <PropertyGroup Condition=" '$(ToolName)' == 'Fuzzlyn' "> <WorkItemCommand>$(Python) $(CoreRoot)$(FileSeparatorChar)fuzzlyn_run.py -run_configuration $(RunConfiguration) -output_directory $(OutputDirectory) -fuzzlyn_directory $(ToolPath) -core_root $(CoreRoot) -run_duration $(RunDuration)</WorkItemCommand> </PropertyGroup> <ItemGroup> <HelixCorrelationPayload Include="$(CorrelationPayloadDirectory)"> <PayloadDirectory>%(Identity)</PayloadDirectory> </HelixCorrelationPayload> </ItemGroup> <ItemGroup> <Run_Partition Include="Partition0" Index="0" /> <Run_Partition Include="Partition1" Index="1" /> <Run_Partition Include="Partition2" Index="2" /> <Run_Partition Include="Partition3" Index="3" /> </ItemGroup> <ItemGroup> <HelixWorkItem Include="@(Run_Partition)"> <PartitionName>Partition%(HelixWorkItem.Index)</PartitionName> <PayloadDirectory>$(WorkItemDirectory)</PayloadDirectory> <Command>$(WorkItemCommand) -partition %(PartitionName)</Command> <Timeout>$(WorkItemTimeout)</Timeout> <DownloadFilesFromResults>AllIssues-$(RunConfiguration)-%(PartitionName).zip;issues-summary-$(RunConfiguration)-%(PartitionName).txt;$(ToolName)-$(RunConfiguration)-%(PartitionName).log</DownloadFilesFromResults> </HelixWorkItem> </ItemGroup> </Project>
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/pipelines/common/platform-matrix-multijob.yml
# Use one list of platforms to create build jobs for multiple templates. Avoids # platform list duplication. parameters: jobTemplates: [] platforms: [] jobs: - ${{ each job in parameters.jobTemplates }}: - template: /eng/pipelines/common/platform-matrix.yml parameters: platforms: ${{ parameters.platforms }} ${{ insert }}: ${{ job }}
# Use one list of platforms to create build jobs for multiple templates. Avoids # platform list duplication. parameters: jobTemplates: [] platforms: [] jobs: - ${{ each job in parameters.jobTemplates }}: - template: /eng/pipelines/common/platform-matrix.yml parameters: platforms: ${{ parameters.platforms }} ${{ insert }}: ${{ job }}
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/native/ijw/getRefPackFolderFromArtifacts.ps1
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the MIT license. $engNativeFolder = Split-Path $PSScriptRoot -Parent $engFolder = Split-Path $engNativeFolder -Parent $repoRoot = Split-Path $engFolder -Parent $versionPropsFile = "$repoRoot/eng/Versions.props" $majorVersion = Select-Xml -Path $versionPropsFile -XPath "/Project/PropertyGroup/MajorVersion" | %{$_.Node.InnerText} $minorVersion = Select-Xml -Path $versionPropsFile -XPath "/Project/PropertyGroup/MinorVersion" | %{$_.Node.InnerText} $refPackPath = "$repoRoot/artifacts/bin/ref/net$majorVersion.$minorVersion" if (-not (Test-Path $refPackPath)) { Write-Error "Reference assemblies not found in the artifacts folder at '$refPackPath'. Did you invoke 'build.cmd libs.sfx+libs.oob /p:RefOnly=true' to make sure that refs are built? Did the repo layout change?" exit 1 } Write-Output "refPackPath=$refPackPath"
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the MIT license. $engNativeFolder = Split-Path $PSScriptRoot -Parent $engFolder = Split-Path $engNativeFolder -Parent $repoRoot = Split-Path $engFolder -Parent $versionPropsFile = "$repoRoot/eng/Versions.props" $majorVersion = Select-Xml -Path $versionPropsFile -XPath "/Project/PropertyGroup/MajorVersion" | %{$_.Node.InnerText} $minorVersion = Select-Xml -Path $versionPropsFile -XPath "/Project/PropertyGroup/MinorVersion" | %{$_.Node.InnerText} $refPackPath = "$repoRoot/artifacts/bin/ref/net$majorVersion.$minorVersion" if (-not (Test-Path $refPackPath)) { Write-Error "Reference assemblies not found in the artifacts folder at '$refPackPath'. Did you invoke 'build.cmd libs.sfx+libs.oob /p:RefOnly=true' to make sure that refs are built? Did the repo layout change?" exit 1 } Write-Output "refPackPath=$refPackPath"
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./eng/pipelines/coreclr/templates/run-superpmi-asmdiffs-checked-release-job.yml
parameters: steps: [] # optional -- any additional steps that need to happen before pulling down the jitutils repo and sending the jitutils to helix (ie building your repo) variables: [] # optional -- list of additional variables to send to the template jobName: '' # required -- job name displayName: '' # optional -- display name for the job. Will use jobName if not passed pool: '' # required -- name of the Build pool container: '' # required -- name of the container buildConfig: '' # required -- build configuration archType: '' # required -- targeting CPU architecture osGroup: '' # required -- operating system for the job osSubgroup: '' # optional -- operating system subgroup continueOnError: 'false' # optional -- determines whether to continue the build if the step errors dependsOn: '' # optional -- dependencies of the job timeoutInMinutes: 320 # optional -- timeout for the job enableTelemetry: false # optional -- enable for telemetry liveLibrariesBuildConfig: '' # optional -- live-live libraries configuration to use for the run helixQueues: '' # required -- Helix queues dependOnEvaluatePaths: false jobs: - template: xplat-pipeline-job.yml parameters: dependsOn: ${{ parameters.dependsOn }} buildConfig: ${{ parameters.buildConfig }} archType: ${{ parameters.archType }} osGroup: ${{ parameters.osGroup }} osSubgroup: ${{ parameters.osSubgroup }} liveLibrariesBuildConfig: ${{ parameters.liveLibrariesBuildConfig }} enableTelemetry: ${{ parameters.enableTelemetry }} enablePublishBuildArtifacts: true continueOnError: ${{ parameters.continueOnError }} dependOnEvaluatePaths: ${{ parameters.dependOnEvaluatePaths }} timeoutInMinutes: ${{ parameters.timeoutInMinutes }} ${{ if ne(parameters.displayName, '') }}: displayName: '${{ parameters.displayName }}' ${{ if eq(parameters.displayName, '') }}: displayName: '${{ parameters.jobName }}' variables: - name: PythonScript value: 'py -3' - name: PipScript value: 'py -3 -m pip' - name: SpmiCollectionLocation value: '$(Build.SourcesDirectory)\artifacts\spmi\' - name: SpmiLogsLocation value: '$(Build.SourcesDirectory)\artifacts\spmi_logs\' - name: HelixResultLocation value: '$(Build.SourcesDirectory)\artifacts\helixresults\' - ${{ each variable in parameters.variables }}: - ${{insert}}: ${{ variable }} workspace: clean: all pool: ${{ parameters.pool }} container: ${{ parameters.container }} steps: - ${{ parameters.steps }} - script: | mkdir -p $(SpmiCollectionLocation) displayName: Create directory for SPMI collection - script: $(PythonScript) $(Build.SourcesDirectory)/src/coreclr/scripts/superpmi_asmdiffs_checked_release_setup.py -source_directory $(Build.SourcesDirectory) -checked_directory $(buildProductRootFolderPath) -release_directory $(releaseProductRootFolderPath) -arch $(archType) displayName: ${{ format('SuperPMI asmdiffs checked release setup ({0} {1})', parameters.osGroup, parameters.archType) }} # Run superpmi asmdiffs between checked build and release build in helix - template: /eng/pipelines/common/templates/runtimes/send-to-helix-step.yml parameters: displayName: 'Send job to Helix' helixBuild: $(Build.BuildNumber) helixSource: $(_HelixSource) helixType: 'build/tests/' helixQueues: ${{ join(',', parameters.helixQueues) }} creator: dotnet-bot WorkItemTimeout: 4:00 # 4 hours WorkItemDirectory: '$(WorkItemDirectory)' CorrelationPayloadDirectory: '$(CorrelationPayloadDirectory)' helixProjectArguments: '$(Build.SourcesDirectory)/src/coreclr/scripts/superpmi-asmdiffs-checked-release.proj' BuildConfig: ${{ parameters.buildConfig }} osGroup: ${{ parameters.osGroup }} archType: ${{ parameters.archType }} shouldContinueOnError: true # Run the future step i.e. upload superpmi logs # Always upload the available logs for diagnostics - task: CopyFiles@2 displayName: Copying superpmi.log of all partitions inputs: sourceFolder: '$(HelixResultLocation)' contents: '**/superpmi_*.log' targetFolder: '$(SpmiLogsLocation)' condition: always() - task: PublishPipelineArtifact@1 displayName: Publish SuperPMI logs inputs: targetPath: $(SpmiLogsLocation) artifactName: 'SuperPMI_Logs_$(archType)_$(buildConfig)' condition: always() - task: PublishPipelineArtifact@1 displayName: Publish SuperPMI build logs inputs: targetPath: $(Build.SourcesDirectory)/artifacts/log artifactName: 'SuperPMI_BuildLogs_$(archType)_$(buildConfig)' condition: always()
parameters: steps: [] # optional -- any additional steps that need to happen before pulling down the jitutils repo and sending the jitutils to helix (ie building your repo) variables: [] # optional -- list of additional variables to send to the template jobName: '' # required -- job name displayName: '' # optional -- display name for the job. Will use jobName if not passed pool: '' # required -- name of the Build pool container: '' # required -- name of the container buildConfig: '' # required -- build configuration archType: '' # required -- targeting CPU architecture osGroup: '' # required -- operating system for the job osSubgroup: '' # optional -- operating system subgroup continueOnError: 'false' # optional -- determines whether to continue the build if the step errors dependsOn: '' # optional -- dependencies of the job timeoutInMinutes: 320 # optional -- timeout for the job enableTelemetry: false # optional -- enable for telemetry liveLibrariesBuildConfig: '' # optional -- live-live libraries configuration to use for the run helixQueues: '' # required -- Helix queues dependOnEvaluatePaths: false jobs: - template: xplat-pipeline-job.yml parameters: dependsOn: ${{ parameters.dependsOn }} buildConfig: ${{ parameters.buildConfig }} archType: ${{ parameters.archType }} osGroup: ${{ parameters.osGroup }} osSubgroup: ${{ parameters.osSubgroup }} liveLibrariesBuildConfig: ${{ parameters.liveLibrariesBuildConfig }} enableTelemetry: ${{ parameters.enableTelemetry }} enablePublishBuildArtifacts: true continueOnError: ${{ parameters.continueOnError }} dependOnEvaluatePaths: ${{ parameters.dependOnEvaluatePaths }} timeoutInMinutes: ${{ parameters.timeoutInMinutes }} ${{ if ne(parameters.displayName, '') }}: displayName: '${{ parameters.displayName }}' ${{ if eq(parameters.displayName, '') }}: displayName: '${{ parameters.jobName }}' variables: - name: PythonScript value: 'py -3' - name: PipScript value: 'py -3 -m pip' - name: SpmiCollectionLocation value: '$(Build.SourcesDirectory)\artifacts\spmi\' - name: SpmiLogsLocation value: '$(Build.SourcesDirectory)\artifacts\spmi_logs\' - name: HelixResultLocation value: '$(Build.SourcesDirectory)\artifacts\helixresults\' - ${{ each variable in parameters.variables }}: - ${{insert}}: ${{ variable }} workspace: clean: all pool: ${{ parameters.pool }} container: ${{ parameters.container }} steps: - ${{ parameters.steps }} - script: | mkdir -p $(SpmiCollectionLocation) displayName: Create directory for SPMI collection - script: $(PythonScript) $(Build.SourcesDirectory)/src/coreclr/scripts/superpmi_asmdiffs_checked_release_setup.py -source_directory $(Build.SourcesDirectory) -checked_directory $(buildProductRootFolderPath) -release_directory $(releaseProductRootFolderPath) -arch $(archType) displayName: ${{ format('SuperPMI asmdiffs checked release setup ({0} {1})', parameters.osGroup, parameters.archType) }} # Run superpmi asmdiffs between checked build and release build in helix - template: /eng/pipelines/common/templates/runtimes/send-to-helix-step.yml parameters: displayName: 'Send job to Helix' helixBuild: $(Build.BuildNumber) helixSource: $(_HelixSource) helixType: 'build/tests/' helixQueues: ${{ join(',', parameters.helixQueues) }} creator: dotnet-bot WorkItemTimeout: 4:00 # 4 hours WorkItemDirectory: '$(WorkItemDirectory)' CorrelationPayloadDirectory: '$(CorrelationPayloadDirectory)' helixProjectArguments: '$(Build.SourcesDirectory)/src/coreclr/scripts/superpmi-asmdiffs-checked-release.proj' BuildConfig: ${{ parameters.buildConfig }} osGroup: ${{ parameters.osGroup }} archType: ${{ parameters.archType }} shouldContinueOnError: true # Run the future step i.e. upload superpmi logs # Always upload the available logs for diagnostics - task: CopyFiles@2 displayName: Copying superpmi.log of all partitions inputs: sourceFolder: '$(HelixResultLocation)' contents: '**/superpmi_*.log' targetFolder: '$(SpmiLogsLocation)' condition: always() - task: PublishPipelineArtifact@1 displayName: Publish SuperPMI logs inputs: targetPath: $(SpmiLogsLocation) artifactName: 'SuperPMI_Logs_$(archType)_$(buildConfig)' condition: always() - task: PublishPipelineArtifact@1 displayName: Publish SuperPMI build logs inputs: targetPath: $(Build.SourcesDirectory)/artifacts/log artifactName: 'SuperPMI_BuildLogs_$(archType)_$(buildConfig)' condition: always()
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.DirectoryServices.ActiveDirectory { public class GlobalCatalog : DomainController { // private variables private ActiveDirectorySchema? _schema; private bool _disabled; #region constructors internal GlobalCatalog(DirectoryContext context, string globalCatalogName) : base(context, globalCatalogName) { } internal GlobalCatalog(DirectoryContext context, string globalCatalogName, DirectoryEntryManager directoryEntryMgr) : base(context, globalCatalogName, directoryEntryMgr) { } #endregion constructors #region public methods public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) { string? gcDnsName = null; bool isGlobalCatalog = false; DirectoryEntryManager? directoryEntryMgr = null; // check that the context argument is not null if (context == null) throw new ArgumentNullException(nameof(context)); // target should be GC if (context.ContextType != DirectoryContextType.DirectoryServer) { throw new ArgumentException(SR.TargetShouldBeGC, nameof(context)); } // target should be a server if (!(context.isServer())) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound, context.Name), typeof(GlobalCatalog), context.Name); } // work with copy of the context context = new DirectoryContext(context); try { // Get dns name of the dc // by binding to root dse and getting the "dnsHostName" attribute // (also check that the "isGlobalCatalogReady" attribute is true) directoryEntryMgr = new DirectoryEntryManager(context); DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory)) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound, context.Name), typeof(GlobalCatalog), context.Name); } gcDnsName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName)!; isGlobalCatalog = (bool)bool.Parse((string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.IsGlobalCatalogReady)!); if (!isGlobalCatalog) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound, context.Name), typeof(GlobalCatalog), context.Name); } } catch (COMException e) { int errorCode = e.ErrorCode; if (errorCode == unchecked((int)0x8007203a)) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound, context.Name), typeof(GlobalCatalog), context.Name); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } return new GlobalCatalog(context, gcDnsName, directoryEntryMgr); } public static new GlobalCatalog FindOne(DirectoryContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } return FindOneWithCredentialValidation(context, null, 0); } public static new GlobalCatalog FindOne(DirectoryContext context, string siteName) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } if (siteName == null) { throw new ArgumentNullException(nameof(siteName)); } return FindOneWithCredentialValidation(context, siteName, 0); } public static new GlobalCatalog FindOne(DirectoryContext context, LocatorOptions flag) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } return FindOneWithCredentialValidation(context, null, flag); } public static new GlobalCatalog FindOne(DirectoryContext context, string siteName, LocatorOptions flag) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } if (siteName == null) { throw new ArgumentNullException(nameof(siteName)); } return FindOneWithCredentialValidation(context, siteName, flag); } public static new GlobalCatalogCollection FindAll(DirectoryContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } // work with copy of the context context = new DirectoryContext(context); return FindAllInternal(context, null); } public static new GlobalCatalogCollection FindAll(DirectoryContext context, string siteName) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } if (siteName == null) { throw new ArgumentNullException(nameof(siteName)); } // work with copy of the context context = new DirectoryContext(context); return FindAllInternal(context, siteName); } public override GlobalCatalog EnableGlobalCatalog() { CheckIfDisposed(); throw new InvalidOperationException(SR.CannotPerformOnGCObject); } public DomainController DisableGlobalCatalog() { CheckIfDisposed(); CheckIfDisabled(); // bind to the server object DirectoryEntry serverNtdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); // reset the NTDSDSA_OPT_IS_GC flag on the "options" property int options = 0; try { if (serverNtdsaEntry.Properties[PropertyManager.Options].Value != null) { options = (int)serverNtdsaEntry.Properties[PropertyManager.Options].Value!; } serverNtdsaEntry.Properties[PropertyManager.Options].Value = options & (~1); serverNtdsaEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } // mark as disbaled _disabled = true; // return a domain controller object return new DomainController(context, Name); } public override bool IsGlobalCatalog() { CheckIfDisposed(); CheckIfDisabled(); // since this is a global catalog object, this should always return true return true; } public ReadOnlyActiveDirectorySchemaPropertyCollection FindAllProperties() { CheckIfDisposed(); CheckIfDisabled(); // create an ActiveDirectorySchema object if (_schema == null) { string? schemaNC = null; try { schemaNC = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } _ = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context); _schema = new ActiveDirectorySchema(context, schemaNC); } // return the global catalog replicated properties return _schema.FindAllProperties(PropertyTypes.InGlobalCatalog); } public override DirectorySearcher GetDirectorySearcher() { CheckIfDisposed(); CheckIfDisabled(); return InternalGetDirectorySearcher(); } #endregion public methods #region private methods private void CheckIfDisabled() { if (_disabled) { throw new InvalidOperationException(SR.GCDisabled); } } internal static new GlobalCatalog FindOneWithCredentialValidation(DirectoryContext context, string? siteName, LocatorOptions flag) { GlobalCatalog gc; bool retry = false; bool credsValidated = false; // work with copy of the context context = new DirectoryContext(context); // authenticate against this GC to validate the credentials gc = FindOneInternal(context, context.Name, siteName, flag); try { ValidateCredential(gc, context); credsValidated = true; } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x8007203a)) { // server is down , so try again with force rediscovery if the flags did not already contain force rediscovery if ((flag & LocatorOptions.ForceRediscovery) == 0) { retry = true; } else { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest, context.Name), typeof(GlobalCatalog), null); } } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { if (!credsValidated) { gc.Dispose(); } } if (retry) { credsValidated = false; gc = FindOneInternal(context, context.Name, siteName, flag | LocatorOptions.ForceRediscovery); try { ValidateCredential(gc, context); credsValidated = true; } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x8007203a)) { // server is down throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest, context.Name), typeof(GlobalCatalog), null); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { if (!credsValidated) { gc.Dispose(); } } } return gc; } internal static new GlobalCatalog FindOneInternal(DirectoryContext context, string? forestName, string? siteName, LocatorOptions flag) { DomainControllerInfo domainControllerInfo; int errorCode = 0; if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } // check that the flags passed have only the valid bits set if (((long)flag & (~((long)LocatorOptions.AvoidSelf | (long)LocatorOptions.ForceRediscovery | (long)LocatorOptions.KdcRequired | (long)LocatorOptions.TimeServerRequired | (long)LocatorOptions.WriteableRequired))) != 0) { throw new ArgumentException(SR.InvalidFlags, nameof(flag)); } if (forestName == null) { // get the dns name of the logged on forest DomainControllerInfo tempDomainControllerInfo; int error = Locator.DsGetDcNameWrapper(null, DirectoryContext.GetLoggedOnDomain(), null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out tempDomainControllerInfo); if (error == NativeMethods.ERROR_NO_SUCH_DOMAIN) { // throw not found exception throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(GlobalCatalog), null); } else if (error != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } Debug.Assert(tempDomainControllerInfo.DnsForestName != null); forestName = tempDomainControllerInfo.DnsForestName; } // call DsGetDcName errorCode = Locator.DsGetDcNameWrapper(null, forestName, siteName, (long)flag | (long)(PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DirectoryServicesRequired), out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest, forestName), typeof(GlobalCatalog), null); } // this can only occur when flag is being explicitly passed (since the flags that we pass internally are valid) if (errorCode == NativeMethods.ERROR_INVALID_FLAGS) { throw new ArgumentException(SR.InvalidFlags, nameof(flag)); } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } // create a GlobalCatalog object // the name is returned in the form "\\servername", so skip the "\\" Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2); string globalCatalogName = domainControllerInfo.DomainControllerName.Substring(2); // create a new context object for the global catalog DirectoryContext gcContext = Utils.GetNewDirectoryContext(globalCatalogName, DirectoryContextType.DirectoryServer, context); return new GlobalCatalog(gcContext, globalCatalogName); } internal static GlobalCatalogCollection FindAllInternal(DirectoryContext context, string? siteName) { ArrayList gcList = new ArrayList(); if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } foreach (string gcName in Utils.GetReplicaList(context, null /* not specific to any partition */, siteName, false /* isDefaultNC */, false /* isADAM */, true /* mustBeGC */)) { DirectoryContext gcContext = Utils.GetNewDirectoryContext(gcName, DirectoryContextType.DirectoryServer, context); gcList.Add(new GlobalCatalog(gcContext, gcName)); } return new GlobalCatalogCollection(gcList); } private DirectorySearcher InternalGetDirectorySearcher() { DirectoryEntry de = new DirectoryEntry("GC://" + Name); de.AuthenticationType = Utils.DefaultAuthType | AuthenticationTypes.ServerBind; de.Username = context.UserName; de.Password = context.Password; return new DirectorySearcher(de); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.DirectoryServices.ActiveDirectory { public class GlobalCatalog : DomainController { // private variables private ActiveDirectorySchema? _schema; private bool _disabled; #region constructors internal GlobalCatalog(DirectoryContext context, string globalCatalogName) : base(context, globalCatalogName) { } internal GlobalCatalog(DirectoryContext context, string globalCatalogName, DirectoryEntryManager directoryEntryMgr) : base(context, globalCatalogName, directoryEntryMgr) { } #endregion constructors #region public methods public static GlobalCatalog GetGlobalCatalog(DirectoryContext context) { string? gcDnsName = null; bool isGlobalCatalog = false; DirectoryEntryManager? directoryEntryMgr = null; // check that the context argument is not null if (context == null) throw new ArgumentNullException(nameof(context)); // target should be GC if (context.ContextType != DirectoryContextType.DirectoryServer) { throw new ArgumentException(SR.TargetShouldBeGC, nameof(context)); } // target should be a server if (!(context.isServer())) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound, context.Name), typeof(GlobalCatalog), context.Name); } // work with copy of the context context = new DirectoryContext(context); try { // Get dns name of the dc // by binding to root dse and getting the "dnsHostName" attribute // (also check that the "isGlobalCatalogReady" attribute is true) directoryEntryMgr = new DirectoryEntryManager(context); DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory)) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound, context.Name), typeof(GlobalCatalog), context.Name); } gcDnsName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName)!; isGlobalCatalog = (bool)bool.Parse((string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.IsGlobalCatalogReady)!); if (!isGlobalCatalog) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound, context.Name), typeof(GlobalCatalog), context.Name); } } catch (COMException e) { int errorCode = e.ErrorCode; if (errorCode == unchecked((int)0x8007203a)) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound, context.Name), typeof(GlobalCatalog), context.Name); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } return new GlobalCatalog(context, gcDnsName, directoryEntryMgr); } public static new GlobalCatalog FindOne(DirectoryContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } return FindOneWithCredentialValidation(context, null, 0); } public static new GlobalCatalog FindOne(DirectoryContext context, string siteName) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } if (siteName == null) { throw new ArgumentNullException(nameof(siteName)); } return FindOneWithCredentialValidation(context, siteName, 0); } public static new GlobalCatalog FindOne(DirectoryContext context, LocatorOptions flag) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } return FindOneWithCredentialValidation(context, null, flag); } public static new GlobalCatalog FindOne(DirectoryContext context, string siteName, LocatorOptions flag) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } if (siteName == null) { throw new ArgumentNullException(nameof(siteName)); } return FindOneWithCredentialValidation(context, siteName, flag); } public static new GlobalCatalogCollection FindAll(DirectoryContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } // work with copy of the context context = new DirectoryContext(context); return FindAllInternal(context, null); } public static new GlobalCatalogCollection FindAll(DirectoryContext context, string siteName) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.ContextType != DirectoryContextType.Forest) { throw new ArgumentException(SR.TargetShouldBeForest, nameof(context)); } if (siteName == null) { throw new ArgumentNullException(nameof(siteName)); } // work with copy of the context context = new DirectoryContext(context); return FindAllInternal(context, siteName); } public override GlobalCatalog EnableGlobalCatalog() { CheckIfDisposed(); throw new InvalidOperationException(SR.CannotPerformOnGCObject); } public DomainController DisableGlobalCatalog() { CheckIfDisposed(); CheckIfDisabled(); // bind to the server object DirectoryEntry serverNtdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName); // reset the NTDSDSA_OPT_IS_GC flag on the "options" property int options = 0; try { if (serverNtdsaEntry.Properties[PropertyManager.Options].Value != null) { options = (int)serverNtdsaEntry.Properties[PropertyManager.Options].Value!; } serverNtdsaEntry.Properties[PropertyManager.Options].Value = options & (~1); serverNtdsaEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } // mark as disbaled _disabled = true; // return a domain controller object return new DomainController(context, Name); } public override bool IsGlobalCatalog() { CheckIfDisposed(); CheckIfDisabled(); // since this is a global catalog object, this should always return true return true; } public ReadOnlyActiveDirectorySchemaPropertyCollection FindAllProperties() { CheckIfDisposed(); CheckIfDisabled(); // create an ActiveDirectorySchema object if (_schema == null) { string? schemaNC = null; try { schemaNC = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } _ = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context); _schema = new ActiveDirectorySchema(context, schemaNC); } // return the global catalog replicated properties return _schema.FindAllProperties(PropertyTypes.InGlobalCatalog); } public override DirectorySearcher GetDirectorySearcher() { CheckIfDisposed(); CheckIfDisabled(); return InternalGetDirectorySearcher(); } #endregion public methods #region private methods private void CheckIfDisabled() { if (_disabled) { throw new InvalidOperationException(SR.GCDisabled); } } internal static new GlobalCatalog FindOneWithCredentialValidation(DirectoryContext context, string? siteName, LocatorOptions flag) { GlobalCatalog gc; bool retry = false; bool credsValidated = false; // work with copy of the context context = new DirectoryContext(context); // authenticate against this GC to validate the credentials gc = FindOneInternal(context, context.Name, siteName, flag); try { ValidateCredential(gc, context); credsValidated = true; } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x8007203a)) { // server is down , so try again with force rediscovery if the flags did not already contain force rediscovery if ((flag & LocatorOptions.ForceRediscovery) == 0) { retry = true; } else { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest, context.Name), typeof(GlobalCatalog), null); } } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { if (!credsValidated) { gc.Dispose(); } } if (retry) { credsValidated = false; gc = FindOneInternal(context, context.Name, siteName, flag | LocatorOptions.ForceRediscovery); try { ValidateCredential(gc, context); credsValidated = true; } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x8007203a)) { // server is down throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest, context.Name), typeof(GlobalCatalog), null); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { if (!credsValidated) { gc.Dispose(); } } } return gc; } internal static new GlobalCatalog FindOneInternal(DirectoryContext context, string? forestName, string? siteName, LocatorOptions flag) { DomainControllerInfo domainControllerInfo; int errorCode = 0; if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } // check that the flags passed have only the valid bits set if (((long)flag & (~((long)LocatorOptions.AvoidSelf | (long)LocatorOptions.ForceRediscovery | (long)LocatorOptions.KdcRequired | (long)LocatorOptions.TimeServerRequired | (long)LocatorOptions.WriteableRequired))) != 0) { throw new ArgumentException(SR.InvalidFlags, nameof(flag)); } if (forestName == null) { // get the dns name of the logged on forest DomainControllerInfo tempDomainControllerInfo; int error = Locator.DsGetDcNameWrapper(null, DirectoryContext.GetLoggedOnDomain(), null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out tempDomainControllerInfo); if (error == NativeMethods.ERROR_NO_SUCH_DOMAIN) { // throw not found exception throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(GlobalCatalog), null); } else if (error != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } Debug.Assert(tempDomainControllerInfo.DnsForestName != null); forestName = tempDomainControllerInfo.DnsForestName; } // call DsGetDcName errorCode = Locator.DsGetDcNameWrapper(null, forestName, siteName, (long)flag | (long)(PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DirectoryServicesRequired), out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest, forestName), typeof(GlobalCatalog), null); } // this can only occur when flag is being explicitly passed (since the flags that we pass internally are valid) if (errorCode == NativeMethods.ERROR_INVALID_FLAGS) { throw new ArgumentException(SR.InvalidFlags, nameof(flag)); } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } // create a GlobalCatalog object // the name is returned in the form "\\servername", so skip the "\\" Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2); string globalCatalogName = domainControllerInfo.DomainControllerName.Substring(2); // create a new context object for the global catalog DirectoryContext gcContext = Utils.GetNewDirectoryContext(globalCatalogName, DirectoryContextType.DirectoryServer, context); return new GlobalCatalog(gcContext, globalCatalogName); } internal static GlobalCatalogCollection FindAllInternal(DirectoryContext context, string? siteName) { ArrayList gcList = new ArrayList(); if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } foreach (string gcName in Utils.GetReplicaList(context, null /* not specific to any partition */, siteName, false /* isDefaultNC */, false /* isADAM */, true /* mustBeGC */)) { DirectoryContext gcContext = Utils.GetNewDirectoryContext(gcName, DirectoryContextType.DirectoryServer, context); gcList.Add(new GlobalCatalog(gcContext, gcName)); } return new GlobalCatalogCollection(gcList); } private DirectorySearcher InternalGetDirectorySearcher() { DirectoryEntry de = new DirectoryEntry("GC://" + Name); de.AuthenticationType = Utils.DefaultAuthType | AuthenticationTypes.ServerBind; de.Username = context.UserName; de.Password = context.Password; return new DirectorySearcher(de); } #endregion } }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest123/Generated123.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated123 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public sequential sealed MyStruct173`1<T0> extends [mscorlib]System.ValueType implements class IBase2`2<class BaseClass1,class BaseClass0>, class IBase2`2<class BaseClass0,class BaseClass1> { .pack 0 .size 1 .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct173::Method7.1426<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod350() cil managed noinlining { ldstr "MyStruct173::ClassMethod350.1428()" ret } .method public hidebysig newslot instance string ClassMethod351() cil managed noinlining { ldstr "MyStruct173::ClassMethod351.1429()" ret } .method public hidebysig virtual instance bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated123 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct173.T<T0,(valuetype MyStruct173`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct173.T<T0,(valuetype MyStruct173`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct173`1<!!T0> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct173`1<!!T0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct173.A<(valuetype MyStruct173`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct173.A<(valuetype MyStruct173`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct173`1<class BaseClass0> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct173`1<class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct173.B<(valuetype MyStruct173`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct173.B<(valuetype MyStruct173`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct173`1<class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct173`1<class BaseClass1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct173`1<class BaseClass0> V_1) ldloca V_1 initobj valuetype MyStruct173`1<class BaseClass0> ldloca V_1 dup call instance string valuetype MyStruct173`1<class BaseClass0>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "valuetype MyStruct173`1<class BaseClass0> on type MyStruct173" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct173`1<class BaseClass0>::ClassMethod350() ldstr "MyStruct173::ClassMethod350.1428()" ldstr "valuetype MyStruct173`1<class BaseClass0> on type MyStruct173" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct173`1<class BaseClass0>::ClassMethod351() ldstr "MyStruct173::ClassMethod351.1429()" ldstr "valuetype MyStruct173`1<class BaseClass0> on type MyStruct173" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct173`1<class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct173`1<class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct173`1<class BaseClass0>::ToString() pop pop ldloc V_1 box valuetype MyStruct173`1<class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct173`1<class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct173`1<class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct173`1<class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct173`1<class BaseClass1> V_2) ldloca V_2 initobj valuetype MyStruct173`1<class BaseClass1> ldloca V_2 dup call instance string valuetype MyStruct173`1<class BaseClass1>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "valuetype MyStruct173`1<class BaseClass1> on type MyStruct173" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct173`1<class BaseClass1>::ClassMethod350() ldstr "MyStruct173::ClassMethod350.1428()" ldstr "valuetype MyStruct173`1<class BaseClass1> on type MyStruct173" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct173`1<class BaseClass1>::ClassMethod351() ldstr "MyStruct173::ClassMethod351.1429()" ldstr "valuetype MyStruct173`1<class BaseClass1> on type MyStruct173" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct173`1<class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct173`1<class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct173`1<class BaseClass1>::ToString() pop pop ldloc V_2 box valuetype MyStruct173`1<class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct173`1<class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct173`1<class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct173`1<class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct173`1<class BaseClass0> V_3) ldloca V_3 initobj valuetype MyStruct173`1<class BaseClass0> .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct173`1<class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.T<class BaseClass0,valuetype MyStruct173`1<class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.A<valuetype MyStruct173`1<class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct173`1<class BaseClass0>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.T<class BaseClass1,valuetype MyStruct173`1<class BaseClass0>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.B<valuetype MyStruct173`1<class BaseClass0>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct173`1<class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.T<class BaseClass0,valuetype MyStruct173`1<class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.A<valuetype MyStruct173`1<class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct173`1<class BaseClass0>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.T<class BaseClass1,valuetype MyStruct173`1<class BaseClass0>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.B<valuetype MyStruct173`1<class BaseClass0>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: .locals init (valuetype MyStruct173`1<class BaseClass1> V_4) ldloca V_4 initobj valuetype MyStruct173`1<class BaseClass1> .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct173`1<class BaseClass1>>(!!2,string) leave.s LV12 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.T<class BaseClass0,valuetype MyStruct173`1<class BaseClass1>>(!!1,string) leave.s LV13 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.A<valuetype MyStruct173`1<class BaseClass1>>(!!0,string) leave.s LV14 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct173`1<class BaseClass1>>(!!2,string) leave.s LV15 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.T<class BaseClass1,valuetype MyStruct173`1<class BaseClass1>>(!!1,string) leave.s LV16 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.B<valuetype MyStruct173`1<class BaseClass1>>(!!0,string) leave.s LV17 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct173`1<class BaseClass1>>(!!2,string) leave.s LV18 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.T<class BaseClass0,valuetype MyStruct173`1<class BaseClass1>>(!!1,string) leave.s LV19 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.A<valuetype MyStruct173`1<class BaseClass1>>(!!0,string) leave.s LV20 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct173`1<class BaseClass1>>(!!2,string) leave.s LV21 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.T<class BaseClass1,valuetype MyStruct173`1<class BaseClass1>>(!!1,string) leave.s LV22 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.B<valuetype MyStruct173`1<class BaseClass1>>(!!0,string) leave.s LV23 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct173`1<class BaseClass0> V_5) ldloca V_5 initobj valuetype MyStruct173`1<class BaseClass0> .try { ldloc V_5 ldstr "MyStruct173::Method7.1426<System.Object>()#" + "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.MyStruct173.T<class BaseClass0,valuetype MyStruct173`1<class BaseClass0>>(!!1,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_5 ldstr "MyStruct173::Method7.1426<System.Object>()#" + "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.MyStruct173.A<valuetype MyStruct173`1<class BaseClass0>>(!!0,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .locals init (valuetype MyStruct173`1<class BaseClass1> V_6) ldloca V_6 initobj valuetype MyStruct173`1<class BaseClass1> .try { ldloc V_6 ldstr "MyStruct173::Method7.1426<System.Object>()#" + "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.MyStruct173.T<class BaseClass1,valuetype MyStruct173`1<class BaseClass1>>(!!1,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_6 ldstr "MyStruct173::Method7.1426<System.Object>()#" + "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.MyStruct173.B<valuetype MyStruct173`1<class BaseClass1>>(!!0,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct173`1<class BaseClass0> V_7) ldloca V_7 initobj valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "valuetype MyStruct173`1<class BaseClass0> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass0>::ClassMethod350() calli default string(object) ldstr "MyStruct173::ClassMethod350.1428()" ldstr "valuetype MyStruct173`1<class BaseClass0> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass0>::ClassMethod351() calli default string(object) ldstr "MyStruct173::ClassMethod351.1429()" ldstr "valuetype MyStruct173`1<class BaseClass0> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldnull ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance bool valuetype MyStruct173`1<class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance int32 valuetype MyStruct173`1<class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass0>::ToString() calli default string(object) pop ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct173`1<class BaseClass1> V_8) ldloca V_8 initobj valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "valuetype MyStruct173`1<class BaseClass1> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass1>::ClassMethod350() calli default string(object) ldstr "MyStruct173::ClassMethod350.1428()" ldstr "valuetype MyStruct173`1<class BaseClass1> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass1>::ClassMethod351() calli default string(object) ldstr "MyStruct173::ClassMethod351.1429()" ldstr "valuetype MyStruct173`1<class BaseClass1> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldnull ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance bool valuetype MyStruct173`1<class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance int32 valuetype MyStruct173`1<class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass1>::ToString() calli default string(object) pop ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated123::MethodCallingTest() call void Generated123::ConstrainedCallsTest() call void Generated123::StructConstrainedInterfaceCallsTest() call void Generated123::CalliTest() ldc.i4 100 ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated123 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public sequential sealed MyStruct173`1<T0> extends [mscorlib]System.ValueType implements class IBase2`2<class BaseClass1,class BaseClass0>, class IBase2`2<class BaseClass0,class BaseClass1> { .pack 0 .size 1 .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct173::Method7.1426<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod350() cil managed noinlining { ldstr "MyStruct173::ClassMethod350.1428()" ret } .method public hidebysig newslot instance string ClassMethod351() cil managed noinlining { ldstr "MyStruct173::ClassMethod351.1429()" ret } .method public hidebysig virtual instance bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated123 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct173.T<T0,(valuetype MyStruct173`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct173.T<T0,(valuetype MyStruct173`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct173`1<!!T0> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct173`1<!!T0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct173.A<(valuetype MyStruct173`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct173.A<(valuetype MyStruct173`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct173`1<class BaseClass0> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct173`1<class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct173.B<(valuetype MyStruct173`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct173.B<(valuetype MyStruct173`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct173`1<class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct173`1<class BaseClass1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct173`1<class BaseClass0> V_1) ldloca V_1 initobj valuetype MyStruct173`1<class BaseClass0> ldloca V_1 dup call instance string valuetype MyStruct173`1<class BaseClass0>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "valuetype MyStruct173`1<class BaseClass0> on type MyStruct173" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct173`1<class BaseClass0>::ClassMethod350() ldstr "MyStruct173::ClassMethod350.1428()" ldstr "valuetype MyStruct173`1<class BaseClass0> on type MyStruct173" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct173`1<class BaseClass0>::ClassMethod351() ldstr "MyStruct173::ClassMethod351.1429()" ldstr "valuetype MyStruct173`1<class BaseClass0> on type MyStruct173" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct173`1<class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct173`1<class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct173`1<class BaseClass0>::ToString() pop pop ldloc V_1 box valuetype MyStruct173`1<class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct173`1<class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct173`1<class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct173`1<class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct173`1<class BaseClass1> V_2) ldloca V_2 initobj valuetype MyStruct173`1<class BaseClass1> ldloca V_2 dup call instance string valuetype MyStruct173`1<class BaseClass1>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "valuetype MyStruct173`1<class BaseClass1> on type MyStruct173" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct173`1<class BaseClass1>::ClassMethod350() ldstr "MyStruct173::ClassMethod350.1428()" ldstr "valuetype MyStruct173`1<class BaseClass1> on type MyStruct173" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct173`1<class BaseClass1>::ClassMethod351() ldstr "MyStruct173::ClassMethod351.1429()" ldstr "valuetype MyStruct173`1<class BaseClass1> on type MyStruct173" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct173`1<class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct173`1<class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct173`1<class BaseClass1>::ToString() pop pop ldloc V_2 box valuetype MyStruct173`1<class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct173`1<class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct173`1<class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct173`1<class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct173`1<class BaseClass0> V_3) ldloca V_3 initobj valuetype MyStruct173`1<class BaseClass0> .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct173`1<class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.T<class BaseClass0,valuetype MyStruct173`1<class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.A<valuetype MyStruct173`1<class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct173`1<class BaseClass0>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.T<class BaseClass1,valuetype MyStruct173`1<class BaseClass0>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.B<valuetype MyStruct173`1<class BaseClass0>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct173`1<class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.T<class BaseClass0,valuetype MyStruct173`1<class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.A<valuetype MyStruct173`1<class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct173`1<class BaseClass0>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.T<class BaseClass1,valuetype MyStruct173`1<class BaseClass0>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_3 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.B<valuetype MyStruct173`1<class BaseClass0>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: .locals init (valuetype MyStruct173`1<class BaseClass1> V_4) ldloca V_4 initobj valuetype MyStruct173`1<class BaseClass1> .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct173`1<class BaseClass1>>(!!2,string) leave.s LV12 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.T<class BaseClass0,valuetype MyStruct173`1<class BaseClass1>>(!!1,string) leave.s LV13 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.A<valuetype MyStruct173`1<class BaseClass1>>(!!0,string) leave.s LV14 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct173`1<class BaseClass1>>(!!2,string) leave.s LV15 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.T<class BaseClass1,valuetype MyStruct173`1<class BaseClass1>>(!!1,string) leave.s LV16 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.B<valuetype MyStruct173`1<class BaseClass1>>(!!0,string) leave.s LV17 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct173`1<class BaseClass1>>(!!2,string) leave.s LV18 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.T<class BaseClass0,valuetype MyStruct173`1<class BaseClass1>>(!!1,string) leave.s LV19 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.A.A<valuetype MyStruct173`1<class BaseClass1>>(!!0,string) leave.s LV20 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct173`1<class BaseClass1>>(!!2,string) leave.s LV21 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.T<class BaseClass1,valuetype MyStruct173`1<class BaseClass1>>(!!1,string) leave.s LV22 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22: .try { ldloc V_4 ldstr "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.IBase2.B.B<valuetype MyStruct173`1<class BaseClass1>>(!!0,string) leave.s LV23 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct173`1<class BaseClass0> V_5) ldloca V_5 initobj valuetype MyStruct173`1<class BaseClass0> .try { ldloc V_5 ldstr "MyStruct173::Method7.1426<System.Object>()#" + "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.MyStruct173.T<class BaseClass0,valuetype MyStruct173`1<class BaseClass0>>(!!1,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_5 ldstr "MyStruct173::Method7.1426<System.Object>()#" + "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.MyStruct173.A<valuetype MyStruct173`1<class BaseClass0>>(!!0,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .locals init (valuetype MyStruct173`1<class BaseClass1> V_6) ldloca V_6 initobj valuetype MyStruct173`1<class BaseClass1> .try { ldloc V_6 ldstr "MyStruct173::Method7.1426<System.Object>()#" + "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.MyStruct173.T<class BaseClass1,valuetype MyStruct173`1<class BaseClass1>>(!!1,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_6 ldstr "MyStruct173::Method7.1426<System.Object>()#" + "MyStruct173::Method7.1426<System.Object>()#" call void Generated123::M.MyStruct173.B<valuetype MyStruct173`1<class BaseClass1>>(!!0,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct173`1<class BaseClass0> V_7) ldloca V_7 initobj valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "valuetype MyStruct173`1<class BaseClass0> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass0>::ClassMethod350() calli default string(object) ldstr "MyStruct173::ClassMethod350.1428()" ldstr "valuetype MyStruct173`1<class BaseClass0> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass0>::ClassMethod351() calli default string(object) ldstr "MyStruct173::ClassMethod351.1429()" ldstr "valuetype MyStruct173`1<class BaseClass0> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldnull ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance bool valuetype MyStruct173`1<class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance int32 valuetype MyStruct173`1<class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass0>::ToString() calli default string(object) pop ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldloc V_7 box valuetype MyStruct173`1<class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct173`1<class BaseClass1> V_8) ldloca V_8 initobj valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "valuetype MyStruct173`1<class BaseClass1> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass1>::ClassMethod350() calli default string(object) ldstr "MyStruct173::ClassMethod350.1428()" ldstr "valuetype MyStruct173`1<class BaseClass1> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass1>::ClassMethod351() calli default string(object) ldstr "MyStruct173::ClassMethod351.1429()" ldstr "valuetype MyStruct173`1<class BaseClass1> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldnull ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance bool valuetype MyStruct173`1<class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance int32 valuetype MyStruct173`1<class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string valuetype MyStruct173`1<class BaseClass1>::ToString() calli default string(object) pop ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldloc V_8 box valuetype MyStruct173`1<class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct173::Method7.1426<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct173`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated123::MethodCallingTest() call void Generated123::ConstrainedCallsTest() call void Generated123::StructConstrainedInterfaceCallsTest() call void Generated123::CalliTest() ldc.i4 100 ret } }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Transform.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // This file contains the classes necessary to represent the Transform processing model used in // XMLDSIG. The basic idea is as follows. A Reference object contains within it a TransformChain, which // is an ordered set of XMLDSIG transforms (represented by <Transform>...</Transform> clauses in the XML). // A transform in XMLDSIG operates on an input of either an octet stream or a node set and produces // either an octet stream or a node set. Conversion between the two types is performed by parsing (octet stream-> // node set) or C14N (node set->octet stream). We generalize this slightly to allow a transform to define an array of // input and output types (because I believe in the future there will be perf gains by being smarter about what goes in & comes out) // Each XMLDSIG transform is represented by a subclass of the abstract Transform class. We need to use CryptoConfig to // associate Transform classes with URLs for transform extensibility, but that's a future concern for this code. // Once the Transform chain is constructed, call TransformToOctetStream to convert some sort of input type to an octet // stream. (We only bother implementing that much now since every use of transform chains in XmlDsig ultimately yields something to hash). using System.Collections; using System.IO; using System.Xml; namespace System.Security.Cryptography.Xml { public abstract class Transform { private string _algorithm; private string _baseUri; internal XmlResolver _xmlResolver; private bool _bResolverSet; private SignedXml _signedXml; private Reference _reference; private Hashtable _propagatedNamespaces; private XmlElement _context; internal string BaseURI { get { return _baseUri; } set { _baseUri = value; } } internal SignedXml SignedXml { get { return _signedXml; } set { _signedXml = value; } } internal Reference Reference { get { return _reference; } set { _reference = value; } } // // protected constructors // protected Transform() { } // // public properties // public string Algorithm { get { return _algorithm; } set { _algorithm = value; } } public XmlResolver Resolver { internal get { return _xmlResolver; } // This property only has a public setter. The rationale for this is that we don't have a good value // to return when it has not been explicitely set, as we are using XmlSecureResolver by default set { _xmlResolver = value; _bResolverSet = true; } } internal bool ResolverSet { get { return _bResolverSet; } } public abstract Type[] InputTypes { get; } public abstract Type[] OutputTypes { get; } internal bool AcceptsType(Type inputType) { if (InputTypes != null) { for (int i = 0; i < InputTypes.Length; i++) { if (inputType == InputTypes[i] || inputType.IsSubclassOf(InputTypes[i])) return true; } } return false; } // // public methods // public XmlElement GetXml() { XmlDocument document = new XmlDocument(); document.PreserveWhitespace = true; return GetXml(document); } internal XmlElement GetXml(XmlDocument document) { return GetXml(document, "Transform"); } internal XmlElement GetXml(XmlDocument document, string name) { XmlElement transformElement = document.CreateElement(name, SignedXml.XmlDsigNamespaceUrl); if (!string.IsNullOrEmpty(Algorithm)) transformElement.SetAttribute("Algorithm", Algorithm); XmlNodeList children = GetInnerXml(); if (children != null) { foreach (XmlNode node in children) { transformElement.AppendChild(document.ImportNode(node, true)); } } return transformElement; } public abstract void LoadInnerXml(XmlNodeList nodeList); protected abstract XmlNodeList GetInnerXml(); public abstract void LoadInput(object obj); public abstract object GetOutput(); public abstract object GetOutput(Type type); public virtual byte[] GetDigestedOutput(HashAlgorithm hash) { return hash.ComputeHash((Stream)GetOutput(typeof(Stream))); } public XmlElement Context { get { if (_context != null) return _context; Reference reference = Reference; SignedXml signedXml = (reference == null ? SignedXml : reference.SignedXml); if (signedXml == null) return null; return signedXml._context; } set { _context = value; } } public Hashtable PropagatedNamespaces { get { if (_propagatedNamespaces != null) return _propagatedNamespaces; Reference reference = Reference; SignedXml signedXml = (reference == null ? SignedXml : reference.SignedXml); // If the reference is not a Uri reference with a DataObject target, return an empty hashtable. if (reference != null && ((reference.ReferenceTargetType != ReferenceTargetType.UriReference) || (string.IsNullOrEmpty(reference.Uri) || reference.Uri[0] != '#'))) { _propagatedNamespaces = new Hashtable(0); return _propagatedNamespaces; } CanonicalXmlNodeList namespaces = null; if (reference != null) namespaces = reference._namespaces; else if (signedXml?._context != null) namespaces = Utils.GetPropagatedAttributes(signedXml._context); // if no namespaces have been propagated, return an empty hashtable. if (namespaces == null) { _propagatedNamespaces = new Hashtable(0); return _propagatedNamespaces; } _propagatedNamespaces = new Hashtable(namespaces.Count); foreach (XmlNode attrib in namespaces) { string key = ((attrib.Prefix.Length > 0) ? attrib.Prefix + ":" + attrib.LocalName : attrib.LocalName); if (!_propagatedNamespaces.Contains(key)) _propagatedNamespaces.Add(key, attrib.Value); } return _propagatedNamespaces; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // This file contains the classes necessary to represent the Transform processing model used in // XMLDSIG. The basic idea is as follows. A Reference object contains within it a TransformChain, which // is an ordered set of XMLDSIG transforms (represented by <Transform>...</Transform> clauses in the XML). // A transform in XMLDSIG operates on an input of either an octet stream or a node set and produces // either an octet stream or a node set. Conversion between the two types is performed by parsing (octet stream-> // node set) or C14N (node set->octet stream). We generalize this slightly to allow a transform to define an array of // input and output types (because I believe in the future there will be perf gains by being smarter about what goes in & comes out) // Each XMLDSIG transform is represented by a subclass of the abstract Transform class. We need to use CryptoConfig to // associate Transform classes with URLs for transform extensibility, but that's a future concern for this code. // Once the Transform chain is constructed, call TransformToOctetStream to convert some sort of input type to an octet // stream. (We only bother implementing that much now since every use of transform chains in XmlDsig ultimately yields something to hash). using System.Collections; using System.IO; using System.Xml; namespace System.Security.Cryptography.Xml { public abstract class Transform { private string _algorithm; private string _baseUri; internal XmlResolver _xmlResolver; private bool _bResolverSet; private SignedXml _signedXml; private Reference _reference; private Hashtable _propagatedNamespaces; private XmlElement _context; internal string BaseURI { get { return _baseUri; } set { _baseUri = value; } } internal SignedXml SignedXml { get { return _signedXml; } set { _signedXml = value; } } internal Reference Reference { get { return _reference; } set { _reference = value; } } // // protected constructors // protected Transform() { } // // public properties // public string Algorithm { get { return _algorithm; } set { _algorithm = value; } } public XmlResolver Resolver { internal get { return _xmlResolver; } // This property only has a public setter. The rationale for this is that we don't have a good value // to return when it has not been explicitely set, as we are using XmlSecureResolver by default set { _xmlResolver = value; _bResolverSet = true; } } internal bool ResolverSet { get { return _bResolverSet; } } public abstract Type[] InputTypes { get; } public abstract Type[] OutputTypes { get; } internal bool AcceptsType(Type inputType) { if (InputTypes != null) { for (int i = 0; i < InputTypes.Length; i++) { if (inputType == InputTypes[i] || inputType.IsSubclassOf(InputTypes[i])) return true; } } return false; } // // public methods // public XmlElement GetXml() { XmlDocument document = new XmlDocument(); document.PreserveWhitespace = true; return GetXml(document); } internal XmlElement GetXml(XmlDocument document) { return GetXml(document, "Transform"); } internal XmlElement GetXml(XmlDocument document, string name) { XmlElement transformElement = document.CreateElement(name, SignedXml.XmlDsigNamespaceUrl); if (!string.IsNullOrEmpty(Algorithm)) transformElement.SetAttribute("Algorithm", Algorithm); XmlNodeList children = GetInnerXml(); if (children != null) { foreach (XmlNode node in children) { transformElement.AppendChild(document.ImportNode(node, true)); } } return transformElement; } public abstract void LoadInnerXml(XmlNodeList nodeList); protected abstract XmlNodeList GetInnerXml(); public abstract void LoadInput(object obj); public abstract object GetOutput(); public abstract object GetOutput(Type type); public virtual byte[] GetDigestedOutput(HashAlgorithm hash) { return hash.ComputeHash((Stream)GetOutput(typeof(Stream))); } public XmlElement Context { get { if (_context != null) return _context; Reference reference = Reference; SignedXml signedXml = (reference == null ? SignedXml : reference.SignedXml); if (signedXml == null) return null; return signedXml._context; } set { _context = value; } } public Hashtable PropagatedNamespaces { get { if (_propagatedNamespaces != null) return _propagatedNamespaces; Reference reference = Reference; SignedXml signedXml = (reference == null ? SignedXml : reference.SignedXml); // If the reference is not a Uri reference with a DataObject target, return an empty hashtable. if (reference != null && ((reference.ReferenceTargetType != ReferenceTargetType.UriReference) || (string.IsNullOrEmpty(reference.Uri) || reference.Uri[0] != '#'))) { _propagatedNamespaces = new Hashtable(0); return _propagatedNamespaces; } CanonicalXmlNodeList namespaces = null; if (reference != null) namespaces = reference._namespaces; else if (signedXml?._context != null) namespaces = Utils.GetPropagatedAttributes(signedXml._context); // if no namespaces have been propagated, return an empty hashtable. if (namespaces == null) { _propagatedNamespaces = new Hashtable(0); return _propagatedNamespaces; } _propagatedNamespaces = new Hashtable(namespaces.Count); foreach (XmlNode attrib in namespaces) { string key = ((attrib.Prefix.Length > 0) ? attrib.Prefix + ":" + attrib.LocalName : attrib.LocalName); if (!_propagatedNamespaces.Contains(key)) _propagatedNamespaces.Add(key, attrib.Value); } return _propagatedNamespaces; } } } }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/tests/JIT/IL_Conformance/Old/Conformance_Base/add_ovf_i4.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .class public add_ovf_i4 { .method public static int32 i4(int32,int32,int32) { .locals (class [mscorlib]System.OverflowException,int32) .maxstack 2 try_start: ldarg 0 ldarg 1 add.ovf conv.ovf.i4 stloc.1 leave.s try_end try_end: ldloc.1 ldarg 2 ceq brfalse FAIL ldc.i4 0x11111111 br END aHandler: isinst [mscorlib]System.OverflowException stloc 0 leave aeEnd aeEnd: ldloc 0 brfalse FAIL ldc.i4 0xEEEEEEEE br END FAIL: ldc.i4 0x00000000 END: ret .try try_start to try_end catch [mscorlib]System.OverflowException handler aHandler to aeEnd } .method public void add_ovf_i4() { .maxstack 0 ret } .method public static int32 main(class [mscorlib]System.String[]) { .entrypoint .maxstack 5 ldc.i4 0x80000000 ldc.i4 0x80000000 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x80000000 ldc.i4 0xFFFFFFFF ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x80000000 ldc.i4 0x00000000 ldc.i4 0x80000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x80000000 ldc.i4 0x00000001 ldc.i4 0x80000001 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x80000000 ldc.i4 0x7FFFFFFF ldc.i4 0xFFFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x80000000 ldc.i4 0x55555555 ldc.i4 0xD5555555 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x80000000 ldc.i4 0xAAAAAAAA ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0xFFFFFFFF ldc.i4 0x80000000 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0xFFFFFFFF ldc.i4 0xFFFFFFFF ldc.i4 0xFFFFFFFE call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xFFFFFFFF ldc.i4 0x00000000 ldc.i4 0xFFFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xFFFFFFFF ldc.i4 0x00000001 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xFFFFFFFF ldc.i4 0x7FFFFFFF ldc.i4 0x7FFFFFFE call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xFFFFFFFF ldc.i4 0x55555555 ldc.i4 0x55555554 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xFFFFFFFF ldc.i4 0xAAAAAAAA ldc.i4 0xAAAAAAA9 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x80000000 ldc.i4 0x80000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0xFFFFFFFF ldc.i4 0xFFFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x00000000 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x00000001 ldc.i4 0x00000001 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x7FFFFFFF ldc.i4 0x7FFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x55555555 ldc.i4 0x55555555 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0xAAAAAAAA ldc.i4 0xAAAAAAAA call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x80000000 ldc.i4 0x80000001 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0xFFFFFFFF ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x00000000 ldc.i4 0x00000001 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x00000001 ldc.i4 0x00000002 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x7FFFFFFF ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x55555555 ldc.i4 0x55555556 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0xAAAAAAAA ldc.i4 0xAAAAAAAB call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x7FFFFFFF ldc.i4 0x80000000 ldc.i4 0xFFFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x7FFFFFFF ldc.i4 0xFFFFFFFF ldc.i4 0x7FFFFFFE call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x7FFFFFFF ldc.i4 0x00000000 ldc.i4 0x7FFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x7FFFFFFF ldc.i4 0x00000001 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x7FFFFFFF ldc.i4 0x7FFFFFFF ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x7FFFFFFF ldc.i4 0x55555555 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x7FFFFFFF ldc.i4 0xAAAAAAAA ldc.i4 0x2AAAAAA9 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x55555555 ldc.i4 0x80000000 ldc.i4 0xD5555555 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x55555555 ldc.i4 0xFFFFFFFF ldc.i4 0x55555554 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x55555555 ldc.i4 0x00000000 ldc.i4 0x55555555 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x55555555 ldc.i4 0x00000001 ldc.i4 0x55555556 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x55555555 ldc.i4 0x7FFFFFFF ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x55555555 ldc.i4 0x55555555 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x55555555 ldc.i4 0xAAAAAAAA ldc.i4 0xFFFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xAAAAAAAA ldc.i4 0x80000000 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0xAAAAAAAA ldc.i4 0xFFFFFFFF ldc.i4 0xAAAAAAA9 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xAAAAAAAA ldc.i4 0x00000000 ldc.i4 0xAAAAAAAA call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xAAAAAAAA ldc.i4 0x00000001 ldc.i4 0xAAAAAAAB call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xAAAAAAAA ldc.i4 0x7FFFFFFF ldc.i4 0x2AAAAAA9 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xAAAAAAAA ldc.i4 0x55555555 ldc.i4 0xFFFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xAAAAAAAA ldc.i4 0xAAAAAAAA ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL PASS: ldc.i4 100 br END FAIL: ldc.i4 0x00000000 END: ret } } .assembly add_ovf_i4{}
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .class public add_ovf_i4 { .method public static int32 i4(int32,int32,int32) { .locals (class [mscorlib]System.OverflowException,int32) .maxstack 2 try_start: ldarg 0 ldarg 1 add.ovf conv.ovf.i4 stloc.1 leave.s try_end try_end: ldloc.1 ldarg 2 ceq brfalse FAIL ldc.i4 0x11111111 br END aHandler: isinst [mscorlib]System.OverflowException stloc 0 leave aeEnd aeEnd: ldloc 0 brfalse FAIL ldc.i4 0xEEEEEEEE br END FAIL: ldc.i4 0x00000000 END: ret .try try_start to try_end catch [mscorlib]System.OverflowException handler aHandler to aeEnd } .method public void add_ovf_i4() { .maxstack 0 ret } .method public static int32 main(class [mscorlib]System.String[]) { .entrypoint .maxstack 5 ldc.i4 0x80000000 ldc.i4 0x80000000 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x80000000 ldc.i4 0xFFFFFFFF ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x80000000 ldc.i4 0x00000000 ldc.i4 0x80000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x80000000 ldc.i4 0x00000001 ldc.i4 0x80000001 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x80000000 ldc.i4 0x7FFFFFFF ldc.i4 0xFFFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x80000000 ldc.i4 0x55555555 ldc.i4 0xD5555555 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x80000000 ldc.i4 0xAAAAAAAA ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0xFFFFFFFF ldc.i4 0x80000000 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0xFFFFFFFF ldc.i4 0xFFFFFFFF ldc.i4 0xFFFFFFFE call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xFFFFFFFF ldc.i4 0x00000000 ldc.i4 0xFFFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xFFFFFFFF ldc.i4 0x00000001 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xFFFFFFFF ldc.i4 0x7FFFFFFF ldc.i4 0x7FFFFFFE call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xFFFFFFFF ldc.i4 0x55555555 ldc.i4 0x55555554 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xFFFFFFFF ldc.i4 0xAAAAAAAA ldc.i4 0xAAAAAAA9 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x80000000 ldc.i4 0x80000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0xFFFFFFFF ldc.i4 0xFFFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x00000000 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x00000001 ldc.i4 0x00000001 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x7FFFFFFF ldc.i4 0x7FFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0x55555555 ldc.i4 0x55555555 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000000 ldc.i4 0xAAAAAAAA ldc.i4 0xAAAAAAAA call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x80000000 ldc.i4 0x80000001 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0xFFFFFFFF ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x00000000 ldc.i4 0x00000001 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x00000001 ldc.i4 0x00000002 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x7FFFFFFF ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0x55555555 ldc.i4 0x55555556 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x00000001 ldc.i4 0xAAAAAAAA ldc.i4 0xAAAAAAAB call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x7FFFFFFF ldc.i4 0x80000000 ldc.i4 0xFFFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x7FFFFFFF ldc.i4 0xFFFFFFFF ldc.i4 0x7FFFFFFE call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x7FFFFFFF ldc.i4 0x00000000 ldc.i4 0x7FFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x7FFFFFFF ldc.i4 0x00000001 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x7FFFFFFF ldc.i4 0x7FFFFFFF ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x7FFFFFFF ldc.i4 0x55555555 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x7FFFFFFF ldc.i4 0xAAAAAAAA ldc.i4 0x2AAAAAA9 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x55555555 ldc.i4 0x80000000 ldc.i4 0xD5555555 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x55555555 ldc.i4 0xFFFFFFFF ldc.i4 0x55555554 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x55555555 ldc.i4 0x00000000 ldc.i4 0x55555555 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x55555555 ldc.i4 0x00000001 ldc.i4 0x55555556 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0x55555555 ldc.i4 0x7FFFFFFF ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x55555555 ldc.i4 0x55555555 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0x55555555 ldc.i4 0xAAAAAAAA ldc.i4 0xFFFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xAAAAAAAA ldc.i4 0x80000000 ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL ldc.i4 0xAAAAAAAA ldc.i4 0xFFFFFFFF ldc.i4 0xAAAAAAA9 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xAAAAAAAA ldc.i4 0x00000000 ldc.i4 0xAAAAAAAA call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xAAAAAAAA ldc.i4 0x00000001 ldc.i4 0xAAAAAAAB call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xAAAAAAAA ldc.i4 0x7FFFFFFF ldc.i4 0x2AAAAAA9 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xAAAAAAAA ldc.i4 0x55555555 ldc.i4 0xFFFFFFFF call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0x11111111 ceq brfalse FAIL ldc.i4 0xAAAAAAAA ldc.i4 0xAAAAAAAA ldc.i4 0x00000000 call int32 add_ovf_i4::i4(int32,int32,int32) ldc.i4 0xEEEEEEEE ceq brfalse FAIL PASS: ldc.i4 100 br END FAIL: ldc.i4 0x00000000 END: ret } } .assembly add_ovf_i4{}
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ExportsFileWriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; using System.Linq; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace ILCompiler { public class ExportsFileWriter { private string _exportsFile; private List<EcmaMethod> _methods; private TypeSystemContext _context; public ExportsFileWriter(TypeSystemContext context, string exportsFile) { _exportsFile = exportsFile; _context = context; _methods = new List<EcmaMethod>(); } public void AddExportedMethods(IEnumerable<EcmaMethod> methods) => _methods.AddRange(methods.Where(m => m.Module != _context.SystemModule)); public void EmitExportedMethods() { FileStream fileStream = new FileStream(_exportsFile, FileMode.Create); using (StreamWriter streamWriter = new StreamWriter(fileStream)) { if (_context.Target.IsWindows) { streamWriter.WriteLine("EXPORTS"); foreach (var method in _methods) streamWriter.WriteLine($" {method.GetUnmanagedCallersOnlyExportName()}"); } else if(_context.Target.IsOSX) { foreach (var method in _methods) streamWriter.WriteLine($"_{method.GetUnmanagedCallersOnlyExportName()}"); } else { streamWriter.WriteLine("V1.0 {"); streamWriter.WriteLine(" global: _init; _fini;"); foreach (var method in _methods) streamWriter.WriteLine($" {method.GetUnmanagedCallersOnlyExportName()};"); streamWriter.WriteLine(" local: *;"); streamWriter.WriteLine("};"); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; using System.Linq; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace ILCompiler { public class ExportsFileWriter { private string _exportsFile; private List<EcmaMethod> _methods; private TypeSystemContext _context; public ExportsFileWriter(TypeSystemContext context, string exportsFile) { _exportsFile = exportsFile; _context = context; _methods = new List<EcmaMethod>(); } public void AddExportedMethods(IEnumerable<EcmaMethod> methods) => _methods.AddRange(methods.Where(m => m.Module != _context.SystemModule)); public void EmitExportedMethods() { FileStream fileStream = new FileStream(_exportsFile, FileMode.Create); using (StreamWriter streamWriter = new StreamWriter(fileStream)) { if (_context.Target.IsWindows) { streamWriter.WriteLine("EXPORTS"); foreach (var method in _methods) streamWriter.WriteLine($" {method.GetUnmanagedCallersOnlyExportName()}"); } else if(_context.Target.IsOSX) { foreach (var method in _methods) streamWriter.WriteLine($"_{method.GetUnmanagedCallersOnlyExportName()}"); } else { streamWriter.WriteLine("V1.0 {"); streamWriter.WriteLine(" global: _init; _fini;"); foreach (var method in _methods) streamWriter.WriteLine($" {method.GetUnmanagedCallersOnlyExportName()};"); streamWriter.WriteLine(" local: *;"); streamWriter.WriteLine("};"); } } } } }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest1000/Generated1000.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated1000 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public G3_C1472`1<T0> extends class G2_C496`2<class BaseClass1,class BaseClass1> implements class IBase2`2<class BaseClass1,class BaseClass0> { .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "G3_C1472::Method7.16341<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<class BaseClass1,class BaseClass0>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<[1]>() ldstr "G3_C1472::Method7.MI.16342<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G2_C496<class BaseClass1,class BaseClass1>.ClassMethod2350'<M0>() cil managed noinlining { .override method instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<[1]>() ldstr "G3_C1472::ClassMethod2350.MI.16343<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G2_C496`2<class BaseClass1,class BaseClass1>::.ctor() ret } } .class public G2_C496`2<T0, T1> extends class G1_C9`2<!T0,!T0> implements class IBase1`1<class BaseClass1>, class IBase2`2<class BaseClass0,class BaseClass0> { .method public hidebysig virtual instance string Method4() cil managed noinlining { ldstr "G2_C496::Method4.9521()" ret } .method public hidebysig newslot virtual instance string Method5() cil managed noinlining { ldstr "G2_C496::Method5.9522()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass1>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.MI.9523()" ret } .method public hidebysig virtual instance string Method6<M0>() cil managed noinlining { ldstr "G2_C496::Method6.9524<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "G2_C496::Method7.9525<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod2350<M0>() cil managed noinlining { ldstr "G2_C496::ClassMethod2350.9526<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G1_C9<T0,T0>.ClassMethod1336'() cil managed noinlining { .override method instance string class G1_C9`2<!T0,!T0>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ret } .method public hidebysig newslot virtual instance string 'G1_C9<T0,T0>.ClassMethod1339'<M0>() cil managed noinlining { .override method instance string class G1_C9`2<!T0,!T0>::ClassMethod1339<[1]>() ldstr "G2_C496::ClassMethod1339.MI.9528<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G1_C9`2<!T0,!T0>::.ctor() ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public abstract G1_C9`2<T0, T1> implements class IBase2`2<class BaseClass0,!T0>, class IBase1`1<class BaseClass0> { .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "G1_C9::Method7.4833<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance string Method4() cil managed noinlining { ldstr "G1_C9::Method4.4834()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass0>.Method4'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G1_C9::Method4.MI.4835()" ret } .method public hidebysig newslot virtual instance string Method5() cil managed noinlining { ldstr "G1_C9::Method5.4836()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass0>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G1_C9::Method5.MI.4837()" ret } .method public hidebysig virtual instance string Method6<M0>() cil managed noinlining { ldstr "G1_C9::Method6.4838<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass0>.Method6'<M0>() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass0>::Method6<[1]>() ldstr "G1_C9::Method6.MI.4839<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1336() cil managed noinlining { ldstr "G1_C9::ClassMethod1336.4840()" ret } .method public hidebysig newslot virtual instance string ClassMethod1337() cil managed noinlining { ldstr "G1_C9::ClassMethod1337.4841()" ret } .method public hidebysig newslot virtual instance string ClassMethod1338<M0>() cil managed noinlining { ldstr "G1_C9::ClassMethod1338.4842<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1339<M0>() cil managed noinlining { ldstr "G1_C9::ClassMethod1339.4843<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class interface public abstract IBase1`1<+T0> { .method public hidebysig newslot abstract virtual instance string Method4() cil managed { } .method public hidebysig newslot abstract virtual instance string Method5() cil managed { } .method public hidebysig newslot abstract virtual instance string Method6<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated1000 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1472.T<T0,(class G3_C1472`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1472.T<T0,(class G3_C1472`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1472.A<(class G3_C1472`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1472.A<(class G3_C1472`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1472.B<(class G3_C1472`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1472.B<(class G3_C1472`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C496.T.T<T0,T1,(class G2_C496`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C496.T.T<T0,T1,(class G2_C496`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C496.A.T<T1,(class G2_C496`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C496.A.T<T1,(class G2_C496`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C496.A.A<(class G2_C496`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C496.A.A<(class G2_C496`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C496.A.B<(class G2_C496`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C496.A.B<(class G2_C496`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C496.B.T<T1,(class G2_C496`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C496.B.T<T1,(class G2_C496`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C496.B.A<(class G2_C496`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C496.B.A<(class G2_C496`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C496.B.B<(class G2_C496`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C496.B.B<(class G2_C496`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C9.T.T<T0,T1,(class G1_C9`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C9.T.T<T0,T1,(class G1_C9`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C9.A.T<T1,(class G1_C9`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C9.A.T<T1,(class G1_C9`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C9.A.A<(class G1_C9`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C9.A.A<(class G1_C9`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C9.A.B<(class G1_C9`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C9.A.B<(class G1_C9`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C9.B.T<T1,(class G1_C9`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C9.B.T<T1,(class G1_C9`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C9.B.A<(class G1_C9`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C9.B.A<(class G1_C9`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C9.B.B<(class G1_C9`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C9.B.B<(class G1_C9`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1472`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<object>() ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::Method7<object>() ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod2350<object>() ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G3_C1472`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<object>() ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::Method7<object>() ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod2350<object>() ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C496`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method5() ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod2350<object>() ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C496`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method5() ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod2350<object>() ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C496`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod2350<object>() ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C496`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<object>() ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1472`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.T.T<class BaseClass1,class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.T<class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.B<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.B<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass0,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.A<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G2_C496.T.T<class BaseClass1,class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G2_C496.B.T<class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G2_C496.B.B<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.B<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G3_C1472`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass0,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.A<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G3_C1472.T<class BaseClass0,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G3_C1472.A<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass1,class BaseClass0,class G3_C1472`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.T<class BaseClass0,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.A<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.T<class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.B<class G3_C1472`1<class BaseClass0>>(!!0,string) newobj instance void class G3_C1472`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.T.T<class BaseClass1,class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.T<class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.B<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.B<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass0,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.A<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G2_C496.T.T<class BaseClass1,class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G2_C496.B.T<class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G2_C496.B.B<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.B<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G3_C1472`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass0,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.A<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G3_C1472.T<class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G3_C1472.B<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass1,class BaseClass0,class G3_C1472`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.T<class BaseClass0,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.A<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.T<class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.B<class G3_C1472`1<class BaseClass1>>(!!0,string) newobj instance void class G2_C496`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.T.T<class BaseClass0,class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.A.T<class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.A.A<class G2_C496`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.A<class G2_C496`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.A<class G2_C496`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.B<class G2_C496`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.T.T<class BaseClass0,class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.A.T<class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.A.A<class G2_C496`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.B<class G2_C496`2<class BaseClass0,class BaseClass0>>(!!0,string) newobj instance void class G2_C496`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.T.T<class BaseClass0,class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.A.T<class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.A.A<class G2_C496`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.A<class G2_C496`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.A<class G2_C496`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.B<class G2_C496`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.T.T<class BaseClass0,class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.A.T<class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.A.B<class G2_C496`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.B<class G2_C496`2<class BaseClass0,class BaseClass1>>(!!0,string) newobj instance void class G2_C496`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.T.T<class BaseClass1,class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.T<class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.B<class G2_C496`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.B<class G2_C496`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.A<class G2_C496`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.T.T<class BaseClass1,class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.B.T<class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.B.A<class G2_C496`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.B<class G2_C496`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.A<class G2_C496`2<class BaseClass1,class BaseClass0>>(!!0,string) newobj instance void class G2_C496`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.T.T<class BaseClass1,class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.T<class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.B<class G2_C496`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.B<class G2_C496`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.A<class G2_C496`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.T.T<class BaseClass1,class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.B.T<class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.B.B<class G2_C496`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.B<class G2_C496`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.A<class G2_C496`2<class BaseClass1,class BaseClass1>>(!!0,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1472`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1337() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1336() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::ClassMethod2350<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::Method5() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method5.9522()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::Method4() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::ClassMethod1339<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::ClassMethod1338<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::ClassMethod1337() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::ClassMethod1336() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G3_C1472`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1337() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1336() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::ClassMethod2350<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::Method5() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method5.9522()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::Method4() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::ClassMethod1339<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::ClassMethod1338<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::ClassMethod1337() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::ClassMethod1336() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C496`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod2350<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C496`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod2350<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C496`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod2350<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C496`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated1000::MethodCallingTest() call void Generated1000::ConstrainedCallsTest() call void Generated1000::StructConstrainedInterfaceCallsTest() call void Generated1000::CalliTest() ldc.i4 100 ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated1000 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public G3_C1472`1<T0> extends class G2_C496`2<class BaseClass1,class BaseClass1> implements class IBase2`2<class BaseClass1,class BaseClass0> { .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "G3_C1472::Method7.16341<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<class BaseClass1,class BaseClass0>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<[1]>() ldstr "G3_C1472::Method7.MI.16342<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G2_C496<class BaseClass1,class BaseClass1>.ClassMethod2350'<M0>() cil managed noinlining { .override method instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<[1]>() ldstr "G3_C1472::ClassMethod2350.MI.16343<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G2_C496`2<class BaseClass1,class BaseClass1>::.ctor() ret } } .class public G2_C496`2<T0, T1> extends class G1_C9`2<!T0,!T0> implements class IBase1`1<class BaseClass1>, class IBase2`2<class BaseClass0,class BaseClass0> { .method public hidebysig virtual instance string Method4() cil managed noinlining { ldstr "G2_C496::Method4.9521()" ret } .method public hidebysig newslot virtual instance string Method5() cil managed noinlining { ldstr "G2_C496::Method5.9522()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass1>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.MI.9523()" ret } .method public hidebysig virtual instance string Method6<M0>() cil managed noinlining { ldstr "G2_C496::Method6.9524<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "G2_C496::Method7.9525<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod2350<M0>() cil managed noinlining { ldstr "G2_C496::ClassMethod2350.9526<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G1_C9<T0,T0>.ClassMethod1336'() cil managed noinlining { .override method instance string class G1_C9`2<!T0,!T0>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ret } .method public hidebysig newslot virtual instance string 'G1_C9<T0,T0>.ClassMethod1339'<M0>() cil managed noinlining { .override method instance string class G1_C9`2<!T0,!T0>::ClassMethod1339<[1]>() ldstr "G2_C496::ClassMethod1339.MI.9528<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G1_C9`2<!T0,!T0>::.ctor() ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public abstract G1_C9`2<T0, T1> implements class IBase2`2<class BaseClass0,!T0>, class IBase1`1<class BaseClass0> { .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "G1_C9::Method7.4833<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance string Method4() cil managed noinlining { ldstr "G1_C9::Method4.4834()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass0>.Method4'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G1_C9::Method4.MI.4835()" ret } .method public hidebysig newslot virtual instance string Method5() cil managed noinlining { ldstr "G1_C9::Method5.4836()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass0>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G1_C9::Method5.MI.4837()" ret } .method public hidebysig virtual instance string Method6<M0>() cil managed noinlining { ldstr "G1_C9::Method6.4838<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass0>.Method6'<M0>() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass0>::Method6<[1]>() ldstr "G1_C9::Method6.MI.4839<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1336() cil managed noinlining { ldstr "G1_C9::ClassMethod1336.4840()" ret } .method public hidebysig newslot virtual instance string ClassMethod1337() cil managed noinlining { ldstr "G1_C9::ClassMethod1337.4841()" ret } .method public hidebysig newslot virtual instance string ClassMethod1338<M0>() cil managed noinlining { ldstr "G1_C9::ClassMethod1338.4842<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1339<M0>() cil managed noinlining { ldstr "G1_C9::ClassMethod1339.4843<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class interface public abstract IBase1`1<+T0> { .method public hidebysig newslot abstract virtual instance string Method4() cil managed { } .method public hidebysig newslot abstract virtual instance string Method5() cil managed { } .method public hidebysig newslot abstract virtual instance string Method6<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated1000 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1472.T<T0,(class G3_C1472`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1472.T<T0,(class G3_C1472`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1472.A<(class G3_C1472`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1472.A<(class G3_C1472`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1472.B<(class G3_C1472`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1472.B<(class G3_C1472`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1472`1<class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C496.T.T<T0,T1,(class G2_C496`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C496.T.T<T0,T1,(class G2_C496`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C496.A.T<T1,(class G2_C496`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C496.A.T<T1,(class G2_C496`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C496.A.A<(class G2_C496`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C496.A.A<(class G2_C496`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C496.A.B<(class G2_C496`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C496.A.B<(class G2_C496`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C496.B.T<T1,(class G2_C496`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C496.B.T<T1,(class G2_C496`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C496.B.A<(class G2_C496`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C496.B.A<(class G2_C496`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C496.B.B<(class G2_C496`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C496.B.B<(class G2_C496`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C9.T.T<T0,T1,(class G1_C9`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C9.T.T<T0,T1,(class G1_C9`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C9.A.T<T1,(class G1_C9`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C9.A.T<T1,(class G1_C9`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C9.A.A<(class G1_C9`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C9.A.A<(class G1_C9`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C9.A.B<(class G1_C9`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C9.A.B<(class G1_C9`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C9.B.T<T1,(class G1_C9`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C9.B.T<T1,(class G1_C9`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C9.B.A<(class G1_C9`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C9.B.A<(class G1_C9`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C9.B.B<(class G1_C9`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C9.B.B<(class G1_C9`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1472`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<object>() ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::Method7<object>() ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod2350<object>() ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass0> callvirt instance string class G3_C1472`1<class BaseClass0>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G3_C1472`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<object>() ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::Method7<object>() ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod2350<object>() ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1472`1<class BaseClass1> callvirt instance string class G3_C1472`1<class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C496`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method5() ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod2350<object>() ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C496`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method5() ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass0,class BaseClass0> callvirt instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod2350<object>() ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C496`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod2350<object>() ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C496`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C9`2<class BaseClass1,class BaseClass1> callvirt instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<object>() ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method5() ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1337() ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C496`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1336() ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1472`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.T.T<class BaseClass1,class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.T<class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.B<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.B<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass0,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.A<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G2_C496.T.T<class BaseClass1,class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G2_C496.B.T<class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G2_C496.B.B<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.B<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G3_C1472`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass0,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.A<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G3_C1472.T<class BaseClass0,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G3_C1472.A<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass1,class BaseClass0,class G3_C1472`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.T<class BaseClass0,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.A<class G3_C1472`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.T<class BaseClass1,class G3_C1472`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.B<class G3_C1472`1<class BaseClass0>>(!!0,string) newobj instance void class G3_C1472`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.T.T<class BaseClass1,class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.T<class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.B<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.B<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass0,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.A<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G2_C496.T.T<class BaseClass1,class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G2_C496.B.T<class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G2_C496.B.B<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.B<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G3_C1472`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass0,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.A.A<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G3_C1472.T<class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G3_C1472::ClassMethod2350.MI.16343<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G3_C1472::Method7.16341<System.Object>()#" call void Generated1000::M.G3_C1472.B<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass1,class BaseClass0,class G3_C1472`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.T<class BaseClass0,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.A<class G3_C1472`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.T<class BaseClass1,class G3_C1472`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1472::Method7.MI.16342<System.Object>()#" call void Generated1000::M.IBase2.B.B<class G3_C1472`1<class BaseClass1>>(!!0,string) newobj instance void class G2_C496`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.T.T<class BaseClass0,class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.A.T<class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.A.A<class G2_C496`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.A<class G2_C496`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.A<class G2_C496`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.B<class G2_C496`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.T.T<class BaseClass0,class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.A.T<class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.A.A<class G2_C496`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.B<class G2_C496`2<class BaseClass0,class BaseClass0>>(!!0,string) newobj instance void class G2_C496`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.T.T<class BaseClass0,class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.A.T<class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.A.A<class G2_C496`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.A<class G2_C496`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass0,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.A<class G2_C496`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.B<class G2_C496`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.T.T<class BaseClass0,class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.A.T<class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.A.B<class G2_C496`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass1,class G2_C496`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.B<class G2_C496`2<class BaseClass0,class BaseClass1>>(!!0,string) newobj instance void class G2_C496`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.T.T<class BaseClass1,class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.T<class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.B<class G2_C496`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.B<class G2_C496`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.A<class G2_C496`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.T.T<class BaseClass1,class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.B.T<class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.B.A<class G2_C496`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.B<class G2_C496`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.A<class G2_C496`2<class BaseClass1,class BaseClass0>>(!!0,string) newobj instance void class G2_C496`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.T.T<class BaseClass1,class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.T<class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::Method4.9521()#G1_C9::Method5.4836()#G2_C496::Method6.9524<System.Object>()#G1_C9::Method7.4833<System.Object>()#" call void Generated1000::M.G1_C9.B.B<class G2_C496`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.B<class G2_C496`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.A<class G2_C496`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.T.T<class BaseClass1,class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.B.T<class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::ClassMethod1336.MI.9527()#G1_C9::ClassMethod1337.4841()#G1_C9::ClassMethod1338.4842<System.Object>()#G2_C496::ClassMethod1339.MI.9528<System.Object>()#G2_C496::ClassMethod2350.9526<System.Object>()#G2_C496::Method4.9521()#G2_C496::Method5.9522()#G2_C496::Method6.9524<System.Object>()#G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.G2_C496.B.B<class G2_C496`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.T<class BaseClass1,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method4.9521()#G2_C496::Method5.MI.9523()#G2_C496::Method6.9524<System.Object>()#" call void Generated1000::M.IBase1.B<class G2_C496`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.T<class BaseClass0,class G2_C496`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C496::Method7.9525<System.Object>()#" call void Generated1000::M.IBase2.A.A<class G2_C496`2<class BaseClass1,class BaseClass1>>(!!0,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1472`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1337() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1336() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::ClassMethod2350<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::Method5() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method5.9522()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::Method4() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::ClassMethod1339<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::ClassMethod1338<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::ClassMethod1337() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass0>::ClassMethod1336() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G3_C1472`1<class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass0>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G3_C1472`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1337() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1336() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::Method7.16341<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::ClassMethod2350<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::ClassMethod2350.MI.16343<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::Method5() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method5.9522()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::Method4() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::ClassMethod1339<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::ClassMethod1338<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::ClassMethod1337() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1472`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1472`1<class BaseClass1>::ClassMethod1336() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G3_C1472`1<class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1472`1<class BaseClass1>) ldstr "G3_C1472::Method7.MI.16342<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1472`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C496`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod2350<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass0>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C496`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod2350<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass0,class BaseClass1>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass0,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C496`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod2350<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass0>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass0>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C496`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G1_C9::Method5.4836()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C9`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C9`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G1_C9::Method7.4833<System.Object>()" ldstr "class G1_C9`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod2350<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::ClassMethod2350.9526<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method5.9522()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1339<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::ClassMethod1339.MI.9528<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1338<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G1_C9::ClassMethod1338.4842<System.Object>()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1337() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G1_C9::ClassMethod1337.4841()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C496`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C496`2<class BaseClass1,class BaseClass1>::ClassMethod1336() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::ClassMethod1336.MI.9527()" ldstr "class G2_C496`2<class BaseClass1,class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method4.9521()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method5.MI.9523()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method6.9524<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C496`2<class BaseClass1,class BaseClass1>) ldstr "G2_C496::Method7.9525<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G2_C496`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated1000::MethodCallingTest() call void Generated1000::ConstrainedCallsTest() call void Generated1000::StructConstrainedInterfaceCallsTest() call void Generated1000::CalliTest() ldc.i4 100 ret } }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/tests/GC/Scenarios/GCSimulator/GCSimulator_260.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestExecutionArguments>-t 3 -tp 0 -dz 17 -sdz 8500 -dc 10000 -sdc 5000 -lt 4 -f -dp 0.0 -dw 0.0</CLRTestExecutionArguments> <IsGCSimulatorTest>true</IsGCSimulatorTest> <CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GCSimulator.cs" /> <Compile Include="lifetimefx.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestExecutionArguments>-t 3 -tp 0 -dz 17 -sdz 8500 -dc 10000 -sdc 5000 -lt 4 -f -dp 0.0 -dw 0.0</CLRTestExecutionArguments> <IsGCSimulatorTest>true</IsGCSimulatorTest> <CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GCSimulator.cs" /> <Compile Include="lifetimefx.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/Projector.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Reflection.Context.Projection { internal abstract class Projector { [return: NotNullIfNotNull("values")] public IList<T>? Project<T>(IList<T>? values, Func<T, T> project) { if (values == null || values.Count == 0) return values; T[] projected = ProjectAll(values, project); return Array.AsReadOnly(projected); } [return: NotNullIfNotNull("values")] public T[]? Project<T>(T[]? values, Func<T, T> project) { if (values == null || values.Length == 0) return values; return ProjectAll(values, project); } public T Project<T>(T value, Func<T, T> project) { if (NeedsProjection(value)) { // NeedsProjection should guarantee this. Debug.Assert(!(value is IProjectable) || ((IProjectable)value).Projector != this); return project(value); } return value; } [return: NotNullIfNotNull("value")] public abstract TypeInfo? ProjectType(Type? value); [return: NotNullIfNotNull("value")] public abstract Assembly? ProjectAssembly(Assembly? value); [return: NotNullIfNotNull("value")] public abstract Module? ProjectModule(Module? value); [return: NotNullIfNotNull("value")] public abstract FieldInfo? ProjectField(FieldInfo? value); [return: NotNullIfNotNull("value")] public abstract EventInfo? ProjectEvent(EventInfo? value); [return: NotNullIfNotNull("value")] public abstract ConstructorInfo? ProjectConstructor(ConstructorInfo? value); [return: NotNullIfNotNull("value")] public abstract MethodInfo? ProjectMethod(MethodInfo? value); [return: NotNullIfNotNull("value")] public abstract MethodBase? ProjectMethodBase(MethodBase? value); [return: NotNullIfNotNull("value")] public abstract PropertyInfo? ProjectProperty(PropertyInfo? value); [return: NotNullIfNotNull("value")] public abstract ParameterInfo? ProjectParameter(ParameterInfo? value); [return: NotNullIfNotNull("value")] public abstract MethodBody? ProjectMethodBody(MethodBody? value); [return: NotNullIfNotNull("value")] public abstract LocalVariableInfo? ProjectLocalVariable(LocalVariableInfo? value); [return: NotNullIfNotNull("value")] public abstract ExceptionHandlingClause? ProjectExceptionHandlingClause(ExceptionHandlingClause? value); [return: NotNullIfNotNull("value")] public abstract CustomAttributeData? ProjectCustomAttributeData(CustomAttributeData? value); [return: NotNullIfNotNull("value")] public abstract ManifestResourceInfo? ProjectManifestResource(ManifestResourceInfo? value); public abstract CustomAttributeTypedArgument ProjectTypedArgument(CustomAttributeTypedArgument value); public abstract CustomAttributeNamedArgument ProjectNamedArgument(CustomAttributeNamedArgument value); public abstract InterfaceMapping ProjectInterfaceMapping(InterfaceMapping value); [return: NotNullIfNotNull("value")] public abstract MemberInfo? ProjectMember(MemberInfo? value); [return: NotNullIfNotNull("values")] public Type[]? Unproject(Type[]? values) { if (values == null) return null; Type[] newTypes = new Type[values.Length]; for (int i = 0; i < values.Length; i++) { newTypes[i] = Unproject(values[i]); } return newTypes; } [return: NotNullIfNotNull("value")] public Type? Unproject(Type? value) { if (value is ProjectingType projectingType) return projectingType.UnderlyingType; else return value; } public bool NeedsProjection([NotNullWhen(true)] object? value) { Debug.Assert(value != null); if (value == null) return false; if (value is IProjectable projector && projector == this) return false; // Already projected // Different context, so we need to project it return true; } //protected abstract object ExecuteProjection<T>(object value); //protected abstract IProjection GetProjector(Type t); private T[] ProjectAll<T>(IList<T> values, Func<T, T> project) { Debug.Assert(null != project); Debug.Assert(values != null && values.Count > 0); var projected = new T[values.Count]; for (int i = 0; i < projected.Length; i++) { T value = values[i]; Debug.Assert(NeedsProjection(value)); projected[i] = project(value); } return projected; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Reflection.Context.Projection { internal abstract class Projector { [return: NotNullIfNotNull("values")] public IList<T>? Project<T>(IList<T>? values, Func<T, T> project) { if (values == null || values.Count == 0) return values; T[] projected = ProjectAll(values, project); return Array.AsReadOnly(projected); } [return: NotNullIfNotNull("values")] public T[]? Project<T>(T[]? values, Func<T, T> project) { if (values == null || values.Length == 0) return values; return ProjectAll(values, project); } public T Project<T>(T value, Func<T, T> project) { if (NeedsProjection(value)) { // NeedsProjection should guarantee this. Debug.Assert(!(value is IProjectable) || ((IProjectable)value).Projector != this); return project(value); } return value; } [return: NotNullIfNotNull("value")] public abstract TypeInfo? ProjectType(Type? value); [return: NotNullIfNotNull("value")] public abstract Assembly? ProjectAssembly(Assembly? value); [return: NotNullIfNotNull("value")] public abstract Module? ProjectModule(Module? value); [return: NotNullIfNotNull("value")] public abstract FieldInfo? ProjectField(FieldInfo? value); [return: NotNullIfNotNull("value")] public abstract EventInfo? ProjectEvent(EventInfo? value); [return: NotNullIfNotNull("value")] public abstract ConstructorInfo? ProjectConstructor(ConstructorInfo? value); [return: NotNullIfNotNull("value")] public abstract MethodInfo? ProjectMethod(MethodInfo? value); [return: NotNullIfNotNull("value")] public abstract MethodBase? ProjectMethodBase(MethodBase? value); [return: NotNullIfNotNull("value")] public abstract PropertyInfo? ProjectProperty(PropertyInfo? value); [return: NotNullIfNotNull("value")] public abstract ParameterInfo? ProjectParameter(ParameterInfo? value); [return: NotNullIfNotNull("value")] public abstract MethodBody? ProjectMethodBody(MethodBody? value); [return: NotNullIfNotNull("value")] public abstract LocalVariableInfo? ProjectLocalVariable(LocalVariableInfo? value); [return: NotNullIfNotNull("value")] public abstract ExceptionHandlingClause? ProjectExceptionHandlingClause(ExceptionHandlingClause? value); [return: NotNullIfNotNull("value")] public abstract CustomAttributeData? ProjectCustomAttributeData(CustomAttributeData? value); [return: NotNullIfNotNull("value")] public abstract ManifestResourceInfo? ProjectManifestResource(ManifestResourceInfo? value); public abstract CustomAttributeTypedArgument ProjectTypedArgument(CustomAttributeTypedArgument value); public abstract CustomAttributeNamedArgument ProjectNamedArgument(CustomAttributeNamedArgument value); public abstract InterfaceMapping ProjectInterfaceMapping(InterfaceMapping value); [return: NotNullIfNotNull("value")] public abstract MemberInfo? ProjectMember(MemberInfo? value); [return: NotNullIfNotNull("values")] public Type[]? Unproject(Type[]? values) { if (values == null) return null; Type[] newTypes = new Type[values.Length]; for (int i = 0; i < values.Length; i++) { newTypes[i] = Unproject(values[i]); } return newTypes; } [return: NotNullIfNotNull("value")] public Type? Unproject(Type? value) { if (value is ProjectingType projectingType) return projectingType.UnderlyingType; else return value; } public bool NeedsProjection([NotNullWhen(true)] object? value) { Debug.Assert(value != null); if (value == null) return false; if (value is IProjectable projector && projector == this) return false; // Already projected // Different context, so we need to project it return true; } //protected abstract object ExecuteProjection<T>(object value); //protected abstract IProjection GetProjector(Type t); private T[] ProjectAll<T>(IList<T> values, Func<T, T> project) { Debug.Assert(null != project); Debug.Assert(values != null && values.Count > 0); var projected = new T[values.Count]; for (int i = 0; i < projected.Length; i++) { T value = values[i]; Debug.Assert(NeedsProjection(value)); projected[i] = project(value); } return projected; } } }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/installer/tests/Assets/TestProjects/AppWithCustomEntryPoints/AppWithCustomEntryPoints.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <OutputType>Exe</OutputType> <RuntimeIdentifier>$(TestTargetRid)</RuntimeIdentifier> <RuntimeFrameworkVersion>$(MNAVersion)</RuntimeFrameworkVersion> </PropertyGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <OutputType>Exe</OutputType> <RuntimeIdentifier>$(TestTargetRid)</RuntimeIdentifier> <RuntimeFrameworkVersion>$(MNAVersion)</RuntimeFrameworkVersion> </PropertyGroup> </Project>
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/OutputWindow.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; namespace System.IO.Compression { /// <summary> /// This class maintains a window for decompressed output. /// We need to keep this because the decompressed information can be /// a literal or a length/distance pair. For length/distance pair, /// we need to look back in the output window and copy bytes from there. /// We use a byte array of WindowSize circularly. /// </summary> internal sealed class OutputWindow { // With Deflate64 we can have up to a 65536 length as well as up to a 65538 distance. This means we need a Window that is at // least 131074 bytes long so we have space to retrieve up to a full 64kb in lookback and place it in our buffer without // overwriting existing data. OutputWindow requires that the WindowSize be an exponent of 2, so we round up to 2^18. private const int WindowSize = 262144; private const int WindowMask = 262143; private readonly byte[] _window = new byte[WindowSize]; // The window is 2^18 bytes private int _end; // this is the position to where we should write next byte private int _bytesUsed; // The number of bytes in the output window which is not consumed. internal void ClearBytesUsed() { _bytesUsed = 0; } /// <summary>Add a byte to output window.</summary> public void Write(byte b) { Debug.Assert(_bytesUsed < WindowSize, "Can't add byte when window is full!"); _window[_end++] = b; _end &= WindowMask; ++_bytesUsed; } public void WriteLengthDistance(int length, int distance) { Debug.Assert((_bytesUsed + length) <= WindowSize, "No Enough space"); // move backwards distance bytes in the output stream, // and copy length bytes from this position to the output stream. _bytesUsed += length; int copyStart = (_end - distance) & WindowMask; // start position for coping. int border = WindowSize - length; if (copyStart <= border && _end < border) { if (length <= distance) { Array.Copy(_window, copyStart, _window, _end, length); _end += length; } else { // The referenced string may overlap the current // position; for example, if the last 2 bytes decoded have values // X and Y, a string reference with <length = 5, distance = 2> // adds X,Y,X,Y,X to the output stream. while (length-- > 0) { _window[_end++] = _window[copyStart++]; } } } else { // copy byte by byte while (length-- > 0) { _window[_end++] = _window[copyStart++]; _end &= WindowMask; copyStart &= WindowMask; } } } /// <summary> /// Copy up to length of bytes from input directly. /// This is used for uncompressed block. /// </summary> public int CopyFrom(InputBuffer input, int length) { length = Math.Min(Math.Min(length, WindowSize - _bytesUsed), input.AvailableBytes); int copied; // We might need wrap around to copy all bytes. int tailLen = WindowSize - _end; if (length > tailLen) { // copy the first part copied = input.CopyTo(_window, _end, tailLen); if (copied == tailLen) { // only try to copy the second part if we have enough bytes in input copied += input.CopyTo(_window, 0, length - tailLen); } } else { // only one copy is needed if there is no wrap around. copied = input.CopyTo(_window, _end, length); } _end = (_end + copied) & WindowMask; _bytesUsed += copied; return copied; } /// <summary>Free space in output window.</summary> public int FreeBytes => WindowSize - _bytesUsed; /// <summary>Bytes not consumed in output window.</summary> public int AvailableBytes => _bytesUsed; /// <summary>Copy the decompressed bytes to output buffer.</summary> public int CopyTo(Span<byte> output) { int copy_end; if (output.Length > _bytesUsed) { // we can copy all the decompressed bytes out copy_end = _end; output = output.Slice(0, _bytesUsed); } else { copy_end = (_end - _bytesUsed + output.Length) & WindowMask; // copy length of bytes } int copied = output.Length; int tailLen = output.Length - copy_end; if (tailLen > 0) { // this means we need to copy two parts separately // copy the taillen bytes from the end of the output window _window.AsSpan(WindowSize - tailLen, tailLen).CopyTo(output); output = output.Slice(tailLen, copy_end); } _window.AsSpan(copy_end - output.Length, output.Length).CopyTo(output); _bytesUsed -= copied; Debug.Assert(_bytesUsed >= 0, "check this function and find why we copied more bytes than we have"); return copied; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; namespace System.IO.Compression { /// <summary> /// This class maintains a window for decompressed output. /// We need to keep this because the decompressed information can be /// a literal or a length/distance pair. For length/distance pair, /// we need to look back in the output window and copy bytes from there. /// We use a byte array of WindowSize circularly. /// </summary> internal sealed class OutputWindow { // With Deflate64 we can have up to a 65536 length as well as up to a 65538 distance. This means we need a Window that is at // least 131074 bytes long so we have space to retrieve up to a full 64kb in lookback and place it in our buffer without // overwriting existing data. OutputWindow requires that the WindowSize be an exponent of 2, so we round up to 2^18. private const int WindowSize = 262144; private const int WindowMask = 262143; private readonly byte[] _window = new byte[WindowSize]; // The window is 2^18 bytes private int _end; // this is the position to where we should write next byte private int _bytesUsed; // The number of bytes in the output window which is not consumed. internal void ClearBytesUsed() { _bytesUsed = 0; } /// <summary>Add a byte to output window.</summary> public void Write(byte b) { Debug.Assert(_bytesUsed < WindowSize, "Can't add byte when window is full!"); _window[_end++] = b; _end &= WindowMask; ++_bytesUsed; } public void WriteLengthDistance(int length, int distance) { Debug.Assert((_bytesUsed + length) <= WindowSize, "No Enough space"); // move backwards distance bytes in the output stream, // and copy length bytes from this position to the output stream. _bytesUsed += length; int copyStart = (_end - distance) & WindowMask; // start position for coping. int border = WindowSize - length; if (copyStart <= border && _end < border) { if (length <= distance) { Array.Copy(_window, copyStart, _window, _end, length); _end += length; } else { // The referenced string may overlap the current // position; for example, if the last 2 bytes decoded have values // X and Y, a string reference with <length = 5, distance = 2> // adds X,Y,X,Y,X to the output stream. while (length-- > 0) { _window[_end++] = _window[copyStart++]; } } } else { // copy byte by byte while (length-- > 0) { _window[_end++] = _window[copyStart++]; _end &= WindowMask; copyStart &= WindowMask; } } } /// <summary> /// Copy up to length of bytes from input directly. /// This is used for uncompressed block. /// </summary> public int CopyFrom(InputBuffer input, int length) { length = Math.Min(Math.Min(length, WindowSize - _bytesUsed), input.AvailableBytes); int copied; // We might need wrap around to copy all bytes. int tailLen = WindowSize - _end; if (length > tailLen) { // copy the first part copied = input.CopyTo(_window, _end, tailLen); if (copied == tailLen) { // only try to copy the second part if we have enough bytes in input copied += input.CopyTo(_window, 0, length - tailLen); } } else { // only one copy is needed if there is no wrap around. copied = input.CopyTo(_window, _end, length); } _end = (_end + copied) & WindowMask; _bytesUsed += copied; return copied; } /// <summary>Free space in output window.</summary> public int FreeBytes => WindowSize - _bytesUsed; /// <summary>Bytes not consumed in output window.</summary> public int AvailableBytes => _bytesUsed; /// <summary>Copy the decompressed bytes to output buffer.</summary> public int CopyTo(Span<byte> output) { int copy_end; if (output.Length > _bytesUsed) { // we can copy all the decompressed bytes out copy_end = _end; output = output.Slice(0, _bytesUsed); } else { copy_end = (_end - _bytesUsed + output.Length) & WindowMask; // copy length of bytes } int copied = output.Length; int tailLen = output.Length - copy_end; if (tailLen > 0) { // this means we need to copy two parts separately // copy the taillen bytes from the end of the output window _window.AsSpan(WindowSize - tailLen, tailLen).CopyTo(output); output = output.Slice(tailLen, copy_end); } _window.AsSpan(copy_end - output.Length, output.Length).CopyTo(output); _bytesUsed -= copied; Debug.Assert(_bytesUsed >= 0, "check this function and find why we copied more bytes than we have"); return copied; } } }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/EnvironmentName.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Extensions.Hosting { /// <summary> /// Commonly used environment names. /// <para> /// This type is obsolete and will be removed in a future version. /// The recommended alternative is Microsoft.Extensions.Hosting.Environments. /// </para> /// </summary> [System.Obsolete("EnvironmentName has been deprecated. Use Microsoft.Extensions.Hosting.Environments instead.")] public static class EnvironmentName { public static readonly string Development = "Development"; public static readonly string Staging = "Staging"; public static readonly string Production = "Production"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Extensions.Hosting { /// <summary> /// Commonly used environment names. /// <para> /// This type is obsolete and will be removed in a future version. /// The recommended alternative is Microsoft.Extensions.Hosting.Environments. /// </para> /// </summary> [System.Obsolete("EnvironmentName has been deprecated. Use Microsoft.Extensions.Hosting.Environments instead.")] public static class EnvironmentName { public static readonly string Development = "Development"; public static readonly string Staging = "Staging"; public static readonly string Production = "Production"; } }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAst.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Xml.Xsl.Qil; namespace System.Xml.Xsl.Xslt { using ContextInfo = XsltInput.ContextInfo; using XPathQilFactory = System.Xml.Xsl.XPath.XPathQilFactory; // Set of classes that represent XSLT AST // XSLT AST is a tree of nodes that represent content of xsl template. // All nodes are subclasses of QilNode. This was done to keep NodeCtor and Text ctors // the sames nodes thay will be in resulting QilExpression tree. // So we have: ElementCtor, AttributeCtor, QilTextCtor, CommentCtor, PICtor, NamespaceDecl, List. // Plus couple subclasses of XslNode that represent different xslt instructions // including artifitial: Sort, ExNamespaceDecl, UseAttributeSets internal enum XslNodeType { Unknown = 0, ApplyImports, ApplyTemplates, Attribute, AttributeSet, CallTemplate, Choose, Comment, Copy, CopyOf, Element, Error, ForEach, If, Key, List, LiteralAttribute, LiteralElement, Message, Nop, Number, Otherwise, Param, PI, Sort, Template, Text, UseAttributeSet, ValueOf, ValueOfDoe, Variable, WithParam, } internal sealed class NsDecl { public readonly NsDecl? Prev; public readonly string? Prefix; // Empty string denotes the default namespace, null - extension or excluded namespace public readonly string? NsUri; // null means "#all" -- all namespace defined above this one are excluded. public NsDecl(NsDecl? prev, string? prefix, string? nsUri) { Debug.Assert(nsUri != null || Prefix == null); this.Prev = prev; this.Prefix = prefix; this.NsUri = nsUri; } } internal class XslNode { public readonly XslNodeType NodeType; public ISourceLineInfo? SourceLine; public NsDecl? Namespaces; public readonly QilName? Name; // name or mode public readonly object? Arg; // select or test or terminate or stylesheet;-) public readonly XslVersion XslVersion; public XslFlags Flags; private List<XslNode>? _content; public XslNode(XslNodeType nodeType, QilName? name, object? arg, XslVersion xslVer) { this.NodeType = nodeType; this.Name = name; this.Arg = arg; this.XslVersion = xslVer; } public XslNode(XslNodeType nodeType) { this.NodeType = nodeType; this.XslVersion = XslVersion.Current; } public string? Select { get { return (string?)Arg; } } public bool ForwardsCompatible { get { return XslVersion == XslVersion.ForwardsCompatible; } } // -------------------------------- Content Management -------------------------------- private static readonly IList<XslNode> s_emptyList = new List<XslNode>().AsReadOnly(); public IList<XslNode> Content { get { return _content ?? s_emptyList; } } public void SetContent(List<XslNode>? content) { _content = content; } public void AddContent(XslNode node) { Debug.Assert(node != null); if (_content == null) { _content = new List<XslNode>(); } _content.Add(node); } public void InsertContent(IEnumerable<XslNode> collection) { if (_content == null) { _content = new List<XslNode>(collection); } else { _content.InsertRange(0, collection); } } internal string? TraceName { get { #if DEBUG System.Text.StringBuilder sb = new System.Text.StringBuilder(); string nodeTypeName = NodeType switch { XslNodeType.AttributeSet => "attribute-set", XslNodeType.Template => "template", XslNodeType.Param => "param", XslNodeType.Variable => "variable", XslNodeType.WithParam => "with-param", _ => NodeType.ToString(), }; sb.Append(nodeTypeName); if (Name != null) { sb.Append(' '); sb.Append(Name.QualifiedName); } ISourceLineInfo? lineInfo = SourceLine; if (lineInfo == null && NodeType == XslNodeType.AttributeSet) { lineInfo = Content[0].SourceLine; Debug.Assert(lineInfo != null); } if (lineInfo != null) { string fileName = SourceLineInfo.GetFileName(lineInfo.Uri!); int idx = fileName.LastIndexOf(System.IO.Path.DirectorySeparatorChar) + 1; sb.Append(" ("); sb.Append(fileName, idx, fileName.Length - idx); sb.Append(':'); sb.Append(lineInfo.Start.Line); sb.Append(')'); } return sb.ToString(); #else return null; #endif } } } internal abstract class ProtoTemplate : XslNode { public QilFunction? Function; // Compiled body public ProtoTemplate(XslNodeType nt, QilName? name, XslVersion xslVer) : base(nt, name, null, xslVer) { } public abstract string GetDebugName(); } internal enum CycleCheck { NotStarted = 0, Processing = 1, Completed = 2, } internal sealed class AttributeSet : ProtoTemplate { public CycleCheck CycleCheck; // Used to detect circular references public AttributeSet(QilName name, XslVersion xslVer) : base(XslNodeType.AttributeSet, name, xslVer) { } public override string GetDebugName() { StringBuilder dbgName = new StringBuilder(); dbgName.Append("<xsl:attribute-set name=\""); dbgName.Append(Name!.QualifiedName); dbgName.Append("\">"); return dbgName.ToString(); } public new void AddContent(XslNode node) { Debug.Assert(node != null && node.NodeType == XslNodeType.List); base.AddContent(node); } public void MergeContent(AttributeSet other) { InsertContent(other.Content); } } internal sealed class Template : ProtoTemplate { public readonly string? Match; public readonly QilName Mode; public readonly double Priority; public int ImportPrecedence; public int OrderNumber; public Template(QilName? name, string? match, QilName mode, double priority, XslVersion xslVer) : base(XslNodeType.Template, name, xslVer) { this.Match = match; this.Mode = mode; this.Priority = priority; } public override string GetDebugName() { StringBuilder dbgName = new StringBuilder(); dbgName.Append("<xsl:template"); if (Match != null) { dbgName.Append(" match=\""); dbgName.Append(Match); dbgName.Append('"'); } if (Name != null) { dbgName.Append(" name=\""); dbgName.Append(Name.QualifiedName); dbgName.Append('"'); } if (!double.IsNaN(Priority)) { dbgName.Append(" priority=\""); dbgName.Append(Priority.ToString(CultureInfo.InvariantCulture)); dbgName.Append('"'); } if (Mode.LocalName.Length != 0) { dbgName.Append(" mode=\""); dbgName.Append(Mode.QualifiedName); dbgName.Append('"'); } dbgName.Append('>'); return dbgName.ToString(); } } internal sealed class VarPar : XslNode { public XslFlags DefValueFlags; public QilNode? Value; // Contains value for WithParams and global VarPars public VarPar(XslNodeType nt, QilName name, string? select, XslVersion xslVer) : base(nt, name, select, xslVer) { } } internal sealed class Sort : XslNode { public readonly string? Lang; public readonly string? DataType; public readonly string? Order; public readonly string? CaseOrder; public Sort(string select, string? lang, string? dataType, string? order, string? caseOrder, XslVersion xslVer) : base(XslNodeType.Sort, null, select, xslVer) { this.Lang = lang; this.DataType = dataType; this.Order = order; this.CaseOrder = caseOrder; } } internal sealed class Keys : KeyedCollection<QilName, List<Key>> { protected override QilName GetKeyForItem(List<Key> list) { Debug.Assert(list != null && list.Count > 0); return list[0].Name!; } } internal sealed class Key : XslNode { public readonly string? Match; public readonly string? Use; public QilFunction? Function; public Key(QilName name, string? match, string? use, XslVersion xslVer) : base(XslNodeType.Key, name, null, xslVer) { // match and use can be null in case of incorrect stylesheet Debug.Assert(name != null); this.Match = match; this.Use = use; } public string GetDebugName() { StringBuilder dbgName = new StringBuilder(); dbgName.Append("<xsl:key name=\""); dbgName.Append(Name!.QualifiedName); dbgName.Append('"'); if (Match != null) { dbgName.Append(" match=\""); dbgName.Append(Match); dbgName.Append('"'); } if (Use != null) { dbgName.Append(" use=\""); dbgName.Append(Use); dbgName.Append('"'); } dbgName.Append('>'); return dbgName.ToString(); } } internal enum NumberLevel { Single, Multiple, Any, } internal sealed class Number : XslNode { public readonly NumberLevel Level; public readonly string? Count; public readonly string? From; public readonly string? Value; public readonly string Format; public readonly string? Lang; public readonly string? LetterValue; public readonly string? GroupingSeparator; public readonly string? GroupingSize; public Number(NumberLevel level, string? count, string? from, string? value, string format, string? lang, string? letterValue, string? groupingSeparator, string? groupingSize, XslVersion xslVer) : base(XslNodeType.Number, null, null, xslVer) { this.Level = level; this.Count = count; this.From = from; this.Value = value; this.Format = format; this.Lang = lang; this.LetterValue = letterValue; this.GroupingSeparator = groupingSeparator; this.GroupingSize = groupingSize; } } internal sealed class NodeCtor : XslNode { public readonly string NameAvt; public readonly string? NsAvt; public NodeCtor(XslNodeType nt, string nameAvt, string? nsAvt, XslVersion xslVer) : base(nt, null, null, xslVer) { this.NameAvt = nameAvt; this.NsAvt = nsAvt; } } internal sealed class Text : XslNode { public readonly SerializationHints Hints; public Text(string data, SerializationHints hints, XslVersion xslVer) : base(XslNodeType.Text, null, data, xslVer) { this.Hints = hints; } } internal sealed class XslNodeEx : XslNode { public readonly ISourceLineInfo? ElemNameLi; public readonly ISourceLineInfo? EndTagLi; public XslNodeEx(XslNodeType t, QilName? name, object? arg, ContextInfo ctxInfo, XslVersion xslVer) : base(t, name, arg, xslVer) { ElemNameLi = ctxInfo.elemNameLi; EndTagLi = ctxInfo.endTagLi; } public XslNodeEx(XslNodeType t, QilName? name, object? arg, XslVersion xslVer) : base(t, name, arg, xslVer) { } } internal static class AstFactory { public static XslNode XslNode(XslNodeType nodeType, QilName? name, string? arg, XslVersion xslVer) { return new XslNode(nodeType, name, arg, xslVer); } public static XslNode ApplyImports(QilName mode, Stylesheet? sheet, XslVersion xslVer) { return new XslNode(XslNodeType.ApplyImports, mode, sheet, xslVer); } public static XslNodeEx ApplyTemplates(QilName mode, string select, ContextInfo ctxInfo, XslVersion xslVer) { return new XslNodeEx(XslNodeType.ApplyTemplates, mode, select, ctxInfo, xslVer); } // Special node for start apply-templates public static XslNodeEx ApplyTemplates(QilName mode) { return new XslNodeEx(XslNodeType.ApplyTemplates, mode, /*select:*/null, XslVersion.Current); } public static NodeCtor Attribute(string nameAvt, string? nsAvt, XslVersion xslVer) { return new NodeCtor(XslNodeType.Attribute, nameAvt, nsAvt, xslVer); } public static AttributeSet AttributeSet(QilName name) { return new AttributeSet(name, XslVersion.Current); } public static XslNodeEx CallTemplate(QilName? name, ContextInfo ctxInfo) { return new XslNodeEx(XslNodeType.CallTemplate, name, null, ctxInfo, XslVersion.Current); } public static XslNode Choose() { return new XslNode(XslNodeType.Choose); } public static XslNode Comment() { return new XslNode(XslNodeType.Comment); } public static XslNode Copy() { return new XslNode(XslNodeType.Copy); } public static XslNode CopyOf(string? select, XslVersion xslVer) { return new XslNode(XslNodeType.CopyOf, null, select, xslVer); } public static NodeCtor Element(string nameAvt, string? nsAvt, XslVersion xslVer) { return new NodeCtor(XslNodeType.Element, nameAvt, nsAvt, xslVer); } public static XslNode Error(string message) { return new XslNode(XslNodeType.Error, null, message, XslVersion.Current); } public static XslNodeEx ForEach(string? select, ContextInfo ctxInfo, XslVersion xslVer) { return new XslNodeEx(XslNodeType.ForEach, null, select, ctxInfo, xslVer); } public static XslNode If(string? test, XslVersion xslVer) { return new XslNode(XslNodeType.If, null, test, xslVer); } public static Key Key(QilName name, string? match, string? use, XslVersion xslVer) { return new Key(name, match, use, xslVer); } public static XslNode List() { return new XslNode(XslNodeType.List); } public static XslNode LiteralAttribute(QilName name, string value, XslVersion xslVer) { return new XslNode(XslNodeType.LiteralAttribute, name, value, xslVer); } public static XslNode LiteralElement(QilName name) { return new XslNode(XslNodeType.LiteralElement, name, null, XslVersion.Current); } public static XslNode Message(bool term) { return new XslNode(XslNodeType.Message, null, term, XslVersion.Current); } public static XslNode Nop() { return new XslNode(XslNodeType.Nop); } public static Number Number(NumberLevel level, string? count, string? from, string? value, string format, string? lang, string? letterValue, string? groupingSeparator, string? groupingSize, XslVersion xslVer) { return new Number(level, count, from, value, format, lang, letterValue, groupingSeparator, groupingSize, xslVer); } public static XslNode Otherwise() { return new XslNode(XslNodeType.Otherwise); } public static XslNode PI(string name, XslVersion xslVer) { return new XslNode(XslNodeType.PI, null, name, xslVer); } public static Sort Sort(string select, string? lang, string? dataType, string? order, string? caseOrder, XslVersion xslVer) { return new Sort(select, lang, dataType, order, caseOrder, xslVer); } public static Template Template(QilName? name, string? match, QilName mode, double priority, XslVersion xslVer) { return new Template(name, match, mode, priority, xslVer); } public static XslNode Text(string data) { return new Text(data, SerializationHints.None, XslVersion.Current); } public static XslNode Text(string data, SerializationHints hints) { return new Text(data, hints, XslVersion.Current); } public static XslNode UseAttributeSet(QilName name) { return new XslNode(XslNodeType.UseAttributeSet, name, null, XslVersion.Current); } public static VarPar VarPar(XslNodeType nt, QilName name, string? select, XslVersion xslVer) { return new VarPar(nt, name, select, xslVer); } public static VarPar WithParam(QilName name) { return VarPar(XslNodeType.WithParam, name, /*select*/null, XslVersion.Current); } private static readonly QilFactory s_f = new QilFactory(); public static QilName QName(string local, string uri, string prefix) { return s_f.LiteralQName(local, uri, prefix); } public static QilName QName(string local) { return s_f.LiteralQName(local); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Xml.Xsl.Qil; namespace System.Xml.Xsl.Xslt { using ContextInfo = XsltInput.ContextInfo; using XPathQilFactory = System.Xml.Xsl.XPath.XPathQilFactory; // Set of classes that represent XSLT AST // XSLT AST is a tree of nodes that represent content of xsl template. // All nodes are subclasses of QilNode. This was done to keep NodeCtor and Text ctors // the sames nodes thay will be in resulting QilExpression tree. // So we have: ElementCtor, AttributeCtor, QilTextCtor, CommentCtor, PICtor, NamespaceDecl, List. // Plus couple subclasses of XslNode that represent different xslt instructions // including artifitial: Sort, ExNamespaceDecl, UseAttributeSets internal enum XslNodeType { Unknown = 0, ApplyImports, ApplyTemplates, Attribute, AttributeSet, CallTemplate, Choose, Comment, Copy, CopyOf, Element, Error, ForEach, If, Key, List, LiteralAttribute, LiteralElement, Message, Nop, Number, Otherwise, Param, PI, Sort, Template, Text, UseAttributeSet, ValueOf, ValueOfDoe, Variable, WithParam, } internal sealed class NsDecl { public readonly NsDecl? Prev; public readonly string? Prefix; // Empty string denotes the default namespace, null - extension or excluded namespace public readonly string? NsUri; // null means "#all" -- all namespace defined above this one are excluded. public NsDecl(NsDecl? prev, string? prefix, string? nsUri) { Debug.Assert(nsUri != null || Prefix == null); this.Prev = prev; this.Prefix = prefix; this.NsUri = nsUri; } } internal class XslNode { public readonly XslNodeType NodeType; public ISourceLineInfo? SourceLine; public NsDecl? Namespaces; public readonly QilName? Name; // name or mode public readonly object? Arg; // select or test or terminate or stylesheet;-) public readonly XslVersion XslVersion; public XslFlags Flags; private List<XslNode>? _content; public XslNode(XslNodeType nodeType, QilName? name, object? arg, XslVersion xslVer) { this.NodeType = nodeType; this.Name = name; this.Arg = arg; this.XslVersion = xslVer; } public XslNode(XslNodeType nodeType) { this.NodeType = nodeType; this.XslVersion = XslVersion.Current; } public string? Select { get { return (string?)Arg; } } public bool ForwardsCompatible { get { return XslVersion == XslVersion.ForwardsCompatible; } } // -------------------------------- Content Management -------------------------------- private static readonly IList<XslNode> s_emptyList = new List<XslNode>().AsReadOnly(); public IList<XslNode> Content { get { return _content ?? s_emptyList; } } public void SetContent(List<XslNode>? content) { _content = content; } public void AddContent(XslNode node) { Debug.Assert(node != null); if (_content == null) { _content = new List<XslNode>(); } _content.Add(node); } public void InsertContent(IEnumerable<XslNode> collection) { if (_content == null) { _content = new List<XslNode>(collection); } else { _content.InsertRange(0, collection); } } internal string? TraceName { get { #if DEBUG System.Text.StringBuilder sb = new System.Text.StringBuilder(); string nodeTypeName = NodeType switch { XslNodeType.AttributeSet => "attribute-set", XslNodeType.Template => "template", XslNodeType.Param => "param", XslNodeType.Variable => "variable", XslNodeType.WithParam => "with-param", _ => NodeType.ToString(), }; sb.Append(nodeTypeName); if (Name != null) { sb.Append(' '); sb.Append(Name.QualifiedName); } ISourceLineInfo? lineInfo = SourceLine; if (lineInfo == null && NodeType == XslNodeType.AttributeSet) { lineInfo = Content[0].SourceLine; Debug.Assert(lineInfo != null); } if (lineInfo != null) { string fileName = SourceLineInfo.GetFileName(lineInfo.Uri!); int idx = fileName.LastIndexOf(System.IO.Path.DirectorySeparatorChar) + 1; sb.Append(" ("); sb.Append(fileName, idx, fileName.Length - idx); sb.Append(':'); sb.Append(lineInfo.Start.Line); sb.Append(')'); } return sb.ToString(); #else return null; #endif } } } internal abstract class ProtoTemplate : XslNode { public QilFunction? Function; // Compiled body public ProtoTemplate(XslNodeType nt, QilName? name, XslVersion xslVer) : base(nt, name, null, xslVer) { } public abstract string GetDebugName(); } internal enum CycleCheck { NotStarted = 0, Processing = 1, Completed = 2, } internal sealed class AttributeSet : ProtoTemplate { public CycleCheck CycleCheck; // Used to detect circular references public AttributeSet(QilName name, XslVersion xslVer) : base(XslNodeType.AttributeSet, name, xslVer) { } public override string GetDebugName() { StringBuilder dbgName = new StringBuilder(); dbgName.Append("<xsl:attribute-set name=\""); dbgName.Append(Name!.QualifiedName); dbgName.Append("\">"); return dbgName.ToString(); } public new void AddContent(XslNode node) { Debug.Assert(node != null && node.NodeType == XslNodeType.List); base.AddContent(node); } public void MergeContent(AttributeSet other) { InsertContent(other.Content); } } internal sealed class Template : ProtoTemplate { public readonly string? Match; public readonly QilName Mode; public readonly double Priority; public int ImportPrecedence; public int OrderNumber; public Template(QilName? name, string? match, QilName mode, double priority, XslVersion xslVer) : base(XslNodeType.Template, name, xslVer) { this.Match = match; this.Mode = mode; this.Priority = priority; } public override string GetDebugName() { StringBuilder dbgName = new StringBuilder(); dbgName.Append("<xsl:template"); if (Match != null) { dbgName.Append(" match=\""); dbgName.Append(Match); dbgName.Append('"'); } if (Name != null) { dbgName.Append(" name=\""); dbgName.Append(Name.QualifiedName); dbgName.Append('"'); } if (!double.IsNaN(Priority)) { dbgName.Append(" priority=\""); dbgName.Append(Priority.ToString(CultureInfo.InvariantCulture)); dbgName.Append('"'); } if (Mode.LocalName.Length != 0) { dbgName.Append(" mode=\""); dbgName.Append(Mode.QualifiedName); dbgName.Append('"'); } dbgName.Append('>'); return dbgName.ToString(); } } internal sealed class VarPar : XslNode { public XslFlags DefValueFlags; public QilNode? Value; // Contains value for WithParams and global VarPars public VarPar(XslNodeType nt, QilName name, string? select, XslVersion xslVer) : base(nt, name, select, xslVer) { } } internal sealed class Sort : XslNode { public readonly string? Lang; public readonly string? DataType; public readonly string? Order; public readonly string? CaseOrder; public Sort(string select, string? lang, string? dataType, string? order, string? caseOrder, XslVersion xslVer) : base(XslNodeType.Sort, null, select, xslVer) { this.Lang = lang; this.DataType = dataType; this.Order = order; this.CaseOrder = caseOrder; } } internal sealed class Keys : KeyedCollection<QilName, List<Key>> { protected override QilName GetKeyForItem(List<Key> list) { Debug.Assert(list != null && list.Count > 0); return list[0].Name!; } } internal sealed class Key : XslNode { public readonly string? Match; public readonly string? Use; public QilFunction? Function; public Key(QilName name, string? match, string? use, XslVersion xslVer) : base(XslNodeType.Key, name, null, xslVer) { // match and use can be null in case of incorrect stylesheet Debug.Assert(name != null); this.Match = match; this.Use = use; } public string GetDebugName() { StringBuilder dbgName = new StringBuilder(); dbgName.Append("<xsl:key name=\""); dbgName.Append(Name!.QualifiedName); dbgName.Append('"'); if (Match != null) { dbgName.Append(" match=\""); dbgName.Append(Match); dbgName.Append('"'); } if (Use != null) { dbgName.Append(" use=\""); dbgName.Append(Use); dbgName.Append('"'); } dbgName.Append('>'); return dbgName.ToString(); } } internal enum NumberLevel { Single, Multiple, Any, } internal sealed class Number : XslNode { public readonly NumberLevel Level; public readonly string? Count; public readonly string? From; public readonly string? Value; public readonly string Format; public readonly string? Lang; public readonly string? LetterValue; public readonly string? GroupingSeparator; public readonly string? GroupingSize; public Number(NumberLevel level, string? count, string? from, string? value, string format, string? lang, string? letterValue, string? groupingSeparator, string? groupingSize, XslVersion xslVer) : base(XslNodeType.Number, null, null, xslVer) { this.Level = level; this.Count = count; this.From = from; this.Value = value; this.Format = format; this.Lang = lang; this.LetterValue = letterValue; this.GroupingSeparator = groupingSeparator; this.GroupingSize = groupingSize; } } internal sealed class NodeCtor : XslNode { public readonly string NameAvt; public readonly string? NsAvt; public NodeCtor(XslNodeType nt, string nameAvt, string? nsAvt, XslVersion xslVer) : base(nt, null, null, xslVer) { this.NameAvt = nameAvt; this.NsAvt = nsAvt; } } internal sealed class Text : XslNode { public readonly SerializationHints Hints; public Text(string data, SerializationHints hints, XslVersion xslVer) : base(XslNodeType.Text, null, data, xslVer) { this.Hints = hints; } } internal sealed class XslNodeEx : XslNode { public readonly ISourceLineInfo? ElemNameLi; public readonly ISourceLineInfo? EndTagLi; public XslNodeEx(XslNodeType t, QilName? name, object? arg, ContextInfo ctxInfo, XslVersion xslVer) : base(t, name, arg, xslVer) { ElemNameLi = ctxInfo.elemNameLi; EndTagLi = ctxInfo.endTagLi; } public XslNodeEx(XslNodeType t, QilName? name, object? arg, XslVersion xslVer) : base(t, name, arg, xslVer) { } } internal static class AstFactory { public static XslNode XslNode(XslNodeType nodeType, QilName? name, string? arg, XslVersion xslVer) { return new XslNode(nodeType, name, arg, xslVer); } public static XslNode ApplyImports(QilName mode, Stylesheet? sheet, XslVersion xslVer) { return new XslNode(XslNodeType.ApplyImports, mode, sheet, xslVer); } public static XslNodeEx ApplyTemplates(QilName mode, string select, ContextInfo ctxInfo, XslVersion xslVer) { return new XslNodeEx(XslNodeType.ApplyTemplates, mode, select, ctxInfo, xslVer); } // Special node for start apply-templates public static XslNodeEx ApplyTemplates(QilName mode) { return new XslNodeEx(XslNodeType.ApplyTemplates, mode, /*select:*/null, XslVersion.Current); } public static NodeCtor Attribute(string nameAvt, string? nsAvt, XslVersion xslVer) { return new NodeCtor(XslNodeType.Attribute, nameAvt, nsAvt, xslVer); } public static AttributeSet AttributeSet(QilName name) { return new AttributeSet(name, XslVersion.Current); } public static XslNodeEx CallTemplate(QilName? name, ContextInfo ctxInfo) { return new XslNodeEx(XslNodeType.CallTemplate, name, null, ctxInfo, XslVersion.Current); } public static XslNode Choose() { return new XslNode(XslNodeType.Choose); } public static XslNode Comment() { return new XslNode(XslNodeType.Comment); } public static XslNode Copy() { return new XslNode(XslNodeType.Copy); } public static XslNode CopyOf(string? select, XslVersion xslVer) { return new XslNode(XslNodeType.CopyOf, null, select, xslVer); } public static NodeCtor Element(string nameAvt, string? nsAvt, XslVersion xslVer) { return new NodeCtor(XslNodeType.Element, nameAvt, nsAvt, xslVer); } public static XslNode Error(string message) { return new XslNode(XslNodeType.Error, null, message, XslVersion.Current); } public static XslNodeEx ForEach(string? select, ContextInfo ctxInfo, XslVersion xslVer) { return new XslNodeEx(XslNodeType.ForEach, null, select, ctxInfo, xslVer); } public static XslNode If(string? test, XslVersion xslVer) { return new XslNode(XslNodeType.If, null, test, xslVer); } public static Key Key(QilName name, string? match, string? use, XslVersion xslVer) { return new Key(name, match, use, xslVer); } public static XslNode List() { return new XslNode(XslNodeType.List); } public static XslNode LiteralAttribute(QilName name, string value, XslVersion xslVer) { return new XslNode(XslNodeType.LiteralAttribute, name, value, xslVer); } public static XslNode LiteralElement(QilName name) { return new XslNode(XslNodeType.LiteralElement, name, null, XslVersion.Current); } public static XslNode Message(bool term) { return new XslNode(XslNodeType.Message, null, term, XslVersion.Current); } public static XslNode Nop() { return new XslNode(XslNodeType.Nop); } public static Number Number(NumberLevel level, string? count, string? from, string? value, string format, string? lang, string? letterValue, string? groupingSeparator, string? groupingSize, XslVersion xslVer) { return new Number(level, count, from, value, format, lang, letterValue, groupingSeparator, groupingSize, xslVer); } public static XslNode Otherwise() { return new XslNode(XslNodeType.Otherwise); } public static XslNode PI(string name, XslVersion xslVer) { return new XslNode(XslNodeType.PI, null, name, xslVer); } public static Sort Sort(string select, string? lang, string? dataType, string? order, string? caseOrder, XslVersion xslVer) { return new Sort(select, lang, dataType, order, caseOrder, xslVer); } public static Template Template(QilName? name, string? match, QilName mode, double priority, XslVersion xslVer) { return new Template(name, match, mode, priority, xslVer); } public static XslNode Text(string data) { return new Text(data, SerializationHints.None, XslVersion.Current); } public static XslNode Text(string data, SerializationHints hints) { return new Text(data, hints, XslVersion.Current); } public static XslNode UseAttributeSet(QilName name) { return new XslNode(XslNodeType.UseAttributeSet, name, null, XslVersion.Current); } public static VarPar VarPar(XslNodeType nt, QilName name, string? select, XslVersion xslVer) { return new VarPar(nt, name, select, xslVer); } public static VarPar WithParam(QilName name) { return VarPar(XslNodeType.WithParam, name, /*select*/null, XslVersion.Current); } private static readonly QilFactory s_f = new QilFactory(); public static QilName QName(string local, string uri, string prefix) { return s_f.LiteralQName(local, uri, prefix); } public static QilName QName(string local) { return s_f.LiteralQName(local); } } }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/tests/JIT/HardwareIntrinsics/X86/Sse41/BlendVariable.Byte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void BlendVariableByte() { var test = new SimpleTernaryOpTest__BlendVariableByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__BlendVariableByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] inArray3, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Byte, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public Vector128<Byte> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld3), ref Unsafe.As<Byte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__BlendVariableByte testClass) { var result = Sse41.BlendVariable(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__BlendVariableByte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) fixed (Vector128<Byte>* pFld3 = &_fld3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)), Sse2.LoadVector128((Byte*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Byte[] _data3 = new Byte[Op3ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private static Vector128<Byte> _clsVar3; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private Vector128<Byte> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__BlendVariableByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar3), ref Unsafe.As<Byte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleTernaryOpTest__BlendVariableByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld3), ref Unsafe.As<Byte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); } _dataTable = new DataTable(_data1, _data2, _data3, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.BlendVariable( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.BlendVariable( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.BlendVariable( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.BlendVariable( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) fixed (Vector128<Byte>* pClsVar3 = &_clsVar3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((Byte*)(pClsVar1)), Sse2.LoadVector128((Byte*)(pClsVar2)), Sse2.LoadVector128((Byte*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray3Ptr); var result = Sse41.BlendVariable(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var op3 = Sse2.LoadVector128((Byte*)(_dataTable.inArray3Ptr)); var result = Sse41.BlendVariable(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var op3 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray3Ptr)); var result = Sse41.BlendVariable(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__BlendVariableByte(); var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__BlendVariableByte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) fixed (Vector128<Byte>* pFld3 = &test._fld3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)), Sse2.LoadVector128((Byte*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.BlendVariable(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) fixed (Vector128<Byte>* pFld3 = &_fld3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)), Sse2.LoadVector128((Byte*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.BlendVariable( Sse2.LoadVector128((Byte*)(&test._fld1)), Sse2.LoadVector128((Byte*)(&test._fld2)), Sse2.LoadVector128((Byte*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, Vector128<Byte> op3, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] inArray3 = new Byte[Op3ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] inArray3 = new Byte[Op3ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Byte[] firstOp, Byte[] secondOp, Byte[] thirdOp, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (((thirdOp[0] >> 7) & 1) == 1 ? secondOp[0] != result[0] : firstOp[0] != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (((thirdOp[i] >> 7) & 1) == 1 ? secondOp[i] != result[i] : firstOp[i] != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.BlendVariable)}<Byte>(Vector128<Byte>, Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void BlendVariableByte() { var test = new SimpleTernaryOpTest__BlendVariableByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__BlendVariableByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] inArray3, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Byte, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public Vector128<Byte> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld3), ref Unsafe.As<Byte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__BlendVariableByte testClass) { var result = Sse41.BlendVariable(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__BlendVariableByte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) fixed (Vector128<Byte>* pFld3 = &_fld3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)), Sse2.LoadVector128((Byte*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Byte[] _data3 = new Byte[Op3ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private static Vector128<Byte> _clsVar3; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private Vector128<Byte> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__BlendVariableByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar3), ref Unsafe.As<Byte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleTernaryOpTest__BlendVariableByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld3), ref Unsafe.As<Byte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); } _dataTable = new DataTable(_data1, _data2, _data3, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.BlendVariable( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.BlendVariable( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.BlendVariable( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.BlendVariable( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) fixed (Vector128<Byte>* pClsVar3 = &_clsVar3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((Byte*)(pClsVar1)), Sse2.LoadVector128((Byte*)(pClsVar2)), Sse2.LoadVector128((Byte*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray3Ptr); var result = Sse41.BlendVariable(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var op3 = Sse2.LoadVector128((Byte*)(_dataTable.inArray3Ptr)); var result = Sse41.BlendVariable(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var op3 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray3Ptr)); var result = Sse41.BlendVariable(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__BlendVariableByte(); var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__BlendVariableByte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) fixed (Vector128<Byte>* pFld3 = &test._fld3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)), Sse2.LoadVector128((Byte*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.BlendVariable(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) fixed (Vector128<Byte>* pFld3 = &_fld3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)), Sse2.LoadVector128((Byte*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.BlendVariable( Sse2.LoadVector128((Byte*)(&test._fld1)), Sse2.LoadVector128((Byte*)(&test._fld2)), Sse2.LoadVector128((Byte*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, Vector128<Byte> op3, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] inArray3 = new Byte[Op3ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] inArray3 = new Byte[Op3ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Byte[] firstOp, Byte[] secondOp, Byte[] thirdOp, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (((thirdOp[0] >> 7) & 1) == 1 ? secondOp[0] != result[0] : firstOp[0] != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (((thirdOp[i] >> 7) & 1) == 1 ? secondOp[i] != result[i] : firstOp[i] != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.BlendVariable)}<Byte>(Vector128<Byte>, Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/coreclr/jit/assertionprop.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX AssertionProp XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif //------------------------------------------------------------------------ // Contains: Whether the range contains a given integral value, inclusive. // // Arguments: // value - the integral value in question // // Return Value: // "true" if the value is within the range's bounds, "false" otherwise. // bool IntegralRange::Contains(int64_t value) const { int64_t lowerBound = SymbolicToRealValue(m_lowerBound); int64_t upperBound = SymbolicToRealValue(m_upperBound); return (lowerBound <= value) && (value <= upperBound); } //------------------------------------------------------------------------ // SymbolicToRealValue: Convert a symbolic value to a 64-bit signed integer. // // Arguments: // value - the symbolic value in question // // Return Value: // Integer correspoding to the symbolic value. // /* static */ int64_t IntegralRange::SymbolicToRealValue(SymbolicIntegerValue value) { static const int64_t SymbolicToRealMap[]{INT64_MIN, INT32_MIN, INT16_MIN, INT8_MIN, 0, 1, INT8_MAX, UINT8_MAX, INT16_MAX, UINT16_MAX, INT32_MAX, UINT32_MAX, INT64_MAX}; assert(sizeof(SymbolicIntegerValue) == sizeof(int32_t)); assert(SymbolicToRealMap[static_cast<int32_t>(SymbolicIntegerValue::LongMin)] == INT64_MIN); assert(SymbolicToRealMap[static_cast<int32_t>(SymbolicIntegerValue::Zero)] == 0); assert(SymbolicToRealMap[static_cast<int32_t>(SymbolicIntegerValue::LongMax)] == INT64_MAX); return SymbolicToRealMap[static_cast<int32_t>(value)]; } //------------------------------------------------------------------------ // LowerBoundForType: Get the symbolic lower bound for a type. // // Arguments: // type - the integral type in question // // Return Value: // Symbolic value representing the smallest possible value "type" can represent. // /* static */ SymbolicIntegerValue IntegralRange::LowerBoundForType(var_types type) { switch (type) { case TYP_BOOL: case TYP_UBYTE: case TYP_USHORT: return SymbolicIntegerValue::Zero; case TYP_BYTE: return SymbolicIntegerValue::ByteMin; case TYP_SHORT: return SymbolicIntegerValue::ShortMin; case TYP_INT: return SymbolicIntegerValue::IntMin; case TYP_LONG: return SymbolicIntegerValue::LongMin; default: unreached(); } } //------------------------------------------------------------------------ // UpperBoundForType: Get the symbolic upper bound for a type. // // Arguments: // type - the integral type in question // // Return Value: // Symbolic value representing the largest possible value "type" can represent. // /* static */ SymbolicIntegerValue IntegralRange::UpperBoundForType(var_types type) { switch (type) { case TYP_BYTE: return SymbolicIntegerValue::ByteMax; case TYP_BOOL: case TYP_UBYTE: return SymbolicIntegerValue::UByteMax; case TYP_SHORT: return SymbolicIntegerValue::ShortMax; case TYP_USHORT: return SymbolicIntegerValue::UShortMax; case TYP_INT: return SymbolicIntegerValue::IntMax; case TYP_UINT: return SymbolicIntegerValue::UIntMax; case TYP_LONG: return SymbolicIntegerValue::LongMax; default: unreached(); } } //------------------------------------------------------------------------ // ForNode: Compute the integral range for a node. // // Arguments: // node - the node, of an integral type, in question // compiler - the Compiler, used to retrieve additional info // // Return Value: // The integral range this node produces. // /* static */ IntegralRange IntegralRange::ForNode(GenTree* node, Compiler* compiler) { assert(varTypeIsIntegral(node)); var_types rangeType = node->TypeGet(); switch (node->OperGet()) { case GT_EQ: case GT_NE: case GT_LT: case GT_LE: case GT_GE: case GT_GT: return {SymbolicIntegerValue::Zero, SymbolicIntegerValue::One}; case GT_ARR_LENGTH: return {SymbolicIntegerValue::Zero, SymbolicIntegerValue::IntMax}; case GT_CALL: if (node->AsCall()->NormalizesSmallTypesOnReturn()) { rangeType = static_cast<var_types>(node->AsCall()->gtReturnType); } break; case GT_LCL_VAR: if (compiler->lvaGetDesc(node->AsLclVar())->lvNormalizeOnStore()) { rangeType = compiler->lvaGetDesc(node->AsLclVar())->TypeGet(); } break; case GT_CAST: return ForCastOutput(node->AsCast()); #if defined(FEATURE_HW_INTRINSICS) case GT_HWINTRINSIC: switch (node->AsHWIntrinsic()->GetHWIntrinsicId()) { #if defined(TARGET_XARCH) case NI_BMI1_TrailingZeroCount: case NI_BMI1_X64_TrailingZeroCount: case NI_LZCNT_LeadingZeroCount: case NI_LZCNT_X64_LeadingZeroCount: case NI_POPCNT_PopCount: case NI_POPCNT_X64_PopCount: #elif defined(TARGET_ARM64) case NI_AdvSimd_PopCount: case NI_AdvSimd_LeadingZeroCount: case NI_AdvSimd_LeadingSignCount: case NI_ArmBase_LeadingZeroCount: case NI_ArmBase_Arm64_LeadingZeroCount: case NI_ArmBase_Arm64_LeadingSignCount: #else #error Unsupported platform #endif // TODO-Casts: specify more precise ranges once "IntegralRange" supports them. return {SymbolicIntegerValue::Zero, SymbolicIntegerValue::ByteMax}; default: break; } break; #endif // defined(FEATURE_HW_INTRINSICS) default: break; } return ForType(rangeType); } //------------------------------------------------------------------------ // ForCastInput: Get the non-overflowing input range for a cast. // // This routine computes the input range for a cast from // an integer to an integer for which it will not overflow. // See also the specification comment for IntegralRange. // // Arguments: // cast - the cast node for which the range will be computed // // Return Value: // The range this cast consumes without overflowing - see description. // /* static */ IntegralRange IntegralRange::ForCastInput(GenTreeCast* cast) { var_types fromType = genActualType(cast->CastOp()); var_types toType = cast->CastToType(); bool fromUnsigned = cast->IsUnsigned(); assert((fromType == TYP_INT) || (fromType == TYP_LONG) || varTypeIsGC(fromType)); assert(varTypeIsIntegral(toType)); // Cast from a GC type is the same as a cast from TYP_I_IMPL for our purposes. if (varTypeIsGC(fromType)) { fromType = TYP_I_IMPL; } if (!cast->gtOverflow()) { // CAST(small type <- uint/int/ulong/long) - [TO_TYPE_MIN..TO_TYPE_MAX] if (varTypeIsSmall(toType)) { return {LowerBoundForType(toType), UpperBoundForType(toType)}; } // We choose to say here that representation-changing casts never overflow. // It does not really matter what we do here because representation-changing // non-overflowing casts cannot be deleted from the IR in any case. // CAST(uint/int <- uint/int) - [INT_MIN..INT_MAX] // CAST(uint/int <- ulong/long) - [LONG_MIN..LONG_MAX] // CAST(ulong/long <- uint/int) - [INT_MIN..INT_MAX] // CAST(ulong/long <- ulong/long) - [LONG_MIN..LONG_MAX] return ForType(fromType); } SymbolicIntegerValue lowerBound; SymbolicIntegerValue upperBound; // CAST_OVF(small type <- int/long) - [TO_TYPE_MIN..TO_TYPE_MAX] // CAST_OVF(small type <- uint/ulong) - [0..TO_TYPE_MAX] if (varTypeIsSmall(toType)) { lowerBound = fromUnsigned ? SymbolicIntegerValue::Zero : LowerBoundForType(toType); upperBound = UpperBoundForType(toType); } else { switch (toType) { // CAST_OVF(uint <- uint) - [INT_MIN..INT_MAX] // CAST_OVF(uint <- int) - [0..INT_MAX] // CAST_OVF(uint <- ulong/long) - [0..UINT_MAX] case TYP_UINT: if (fromType == TYP_LONG) { lowerBound = SymbolicIntegerValue::Zero; upperBound = SymbolicIntegerValue::UIntMax; } else { lowerBound = fromUnsigned ? SymbolicIntegerValue::IntMin : SymbolicIntegerValue::Zero; upperBound = SymbolicIntegerValue::IntMax; } break; // CAST_OVF(int <- uint/ulong) - [0..INT_MAX] // CAST_OVF(int <- int/long) - [INT_MIN..INT_MAX] case TYP_INT: lowerBound = fromUnsigned ? SymbolicIntegerValue::Zero : SymbolicIntegerValue::IntMin; upperBound = SymbolicIntegerValue::IntMax; break; // CAST_OVF(ulong <- uint) - [INT_MIN..INT_MAX] // CAST_OVF(ulong <- int) - [0..INT_MAX] // CAST_OVF(ulong <- ulong) - [LONG_MIN..LONG_MAX] // CAST_OVF(ulong <- long) - [0..LONG_MAX] case TYP_ULONG: lowerBound = fromUnsigned ? LowerBoundForType(fromType) : SymbolicIntegerValue::Zero; upperBound = UpperBoundForType(fromType); break; // CAST_OVF(long <- uint/int) - [INT_MIN..INT_MAX] // CAST_OVF(long <- ulong) - [0..LONG_MAX] // CAST_OVF(long <- long) - [LONG_MIN..LONG_MAX] case TYP_LONG: if (fromUnsigned && (fromType == TYP_LONG)) { lowerBound = SymbolicIntegerValue::Zero; } else { lowerBound = LowerBoundForType(fromType); } upperBound = UpperBoundForType(fromType); break; default: unreached(); } } return {lowerBound, upperBound}; } //------------------------------------------------------------------------ // ForCastOutput: Get the output range for a cast. // // This method is the "output" counterpart to ForCastInput, it returns // a range produced by a cast (by definition, non-overflowing one). // The output range is the same for representation-preserving casts, but // can be different for others. One example is CAST_OVF(uint <- long). // The input range is [0..UINT_MAX], while the output is [INT_MIN..INT_MAX]. // Unlike ForCastInput, this method supports casts from floating point types. // // Arguments: // cast - the cast node for which the range will be computed // // Return Value: // The range this cast produces - see description. // /* static */ IntegralRange IntegralRange::ForCastOutput(GenTreeCast* cast) { var_types fromType = genActualType(cast->CastOp()); var_types toType = cast->CastToType(); bool fromUnsigned = cast->IsUnsigned(); assert((fromType == TYP_INT) || (fromType == TYP_LONG) || varTypeIsFloating(fromType) || varTypeIsGC(fromType)); assert(varTypeIsIntegral(toType)); // CAST/CAST_OVF(small type <- float/double) - [TO_TYPE_MIN..TO_TYPE_MAX] // CAST/CAST_OVF(uint/int <- float/double) - [INT_MIN..INT_MAX] // CAST/CAST_OVF(ulong/long <- float/double) - [LONG_MIN..LONG_MAX] if (varTypeIsFloating(fromType)) { if (!varTypeIsSmall(toType)) { toType = genActualType(toType); } return IntegralRange::ForType(toType); } // Cast from a GC type is the same as a cast from TYP_I_IMPL for our purposes. if (varTypeIsGC(fromType)) { fromType = TYP_I_IMPL; } if (varTypeIsSmall(toType) || (genActualType(toType) == fromType)) { return ForCastInput(cast); } // CAST(uint/int <- ulong/long) - [INT_MIN..INT_MAX] // CAST(ulong/long <- uint) - [0..UINT_MAX] // CAST(ulong/long <- int) - [INT_MIN..INT_MAX] if (!cast->gtOverflow()) { if ((fromType == TYP_INT) && fromUnsigned) { return {SymbolicIntegerValue::Zero, SymbolicIntegerValue::UIntMax}; } return {SymbolicIntegerValue::IntMin, SymbolicIntegerValue::IntMax}; } SymbolicIntegerValue lowerBound; SymbolicIntegerValue upperBound; switch (toType) { // CAST_OVF(uint <- ulong) - [INT_MIN..INT_MAX] // CAST_OVF(uint <- long) - [INT_MIN..INT_MAX] case TYP_UINT: lowerBound = SymbolicIntegerValue::IntMin; upperBound = SymbolicIntegerValue::IntMax; break; // CAST_OVF(int <- ulong) - [0..INT_MAX] // CAST_OVF(int <- long) - [INT_MIN..INT_MAX] case TYP_INT: lowerBound = fromUnsigned ? SymbolicIntegerValue::Zero : SymbolicIntegerValue::IntMin; upperBound = SymbolicIntegerValue::IntMax; break; // CAST_OVF(ulong <- uint) - [0..UINT_MAX] // CAST_OVF(ulong <- int) - [0..INT_MAX] case TYP_ULONG: lowerBound = SymbolicIntegerValue::Zero; upperBound = fromUnsigned ? SymbolicIntegerValue::UIntMax : SymbolicIntegerValue::IntMax; break; // CAST_OVF(long <- uint) - [0..UINT_MAX] // CAST_OVF(long <- int) - [INT_MIN..INT_MAX] case TYP_LONG: lowerBound = fromUnsigned ? SymbolicIntegerValue::Zero : SymbolicIntegerValue::IntMin; upperBound = fromUnsigned ? SymbolicIntegerValue::UIntMax : SymbolicIntegerValue::IntMax; break; default: unreached(); } return {lowerBound, upperBound}; } #ifdef DEBUG /* static */ void IntegralRange::Print(IntegralRange range) { printf("[%lld", SymbolicToRealValue(range.m_lowerBound)); printf(".."); printf("%lld]", SymbolicToRealValue(range.m_upperBound)); } #endif // DEBUG /***************************************************************************** * * Helper passed to Compiler::fgWalkTreePre() to find the Asgn node for optAddCopies() */ /* static */ Compiler::fgWalkResult Compiler::optAddCopiesCallback(GenTree** pTree, fgWalkData* data) { GenTree* tree = *pTree; if (tree->OperIs(GT_ASG)) { GenTree* op1 = tree->AsOp()->gtOp1; Compiler* comp = data->compiler; if ((op1->gtOper == GT_LCL_VAR) && (op1->AsLclVarCommon()->GetLclNum() == comp->optAddCopyLclNum)) { comp->optAddCopyAsgnNode = tree; return WALK_ABORT; } } return WALK_CONTINUE; } /***************************************************************************** * * Add new copies before Assertion Prop. */ void Compiler::optAddCopies() { unsigned lclNum; LclVarDsc* varDsc; #ifdef DEBUG if (verbose) { printf("\n*************** In optAddCopies()\n\n"); } if (verboseTrees) { printf("Blocks/Trees at start of phase\n"); fgDispBasicBlocks(true); } #endif // Don't add any copies if we have reached the tracking limit. if (lvaHaveManyLocals()) { return; } for (lclNum = 0, varDsc = lvaTable; lclNum < lvaCount; lclNum++, varDsc++) { var_types typ = varDsc->TypeGet(); // We only add copies for non temp local variables // that have a single def and that can possibly be enregistered if (varDsc->lvIsTemp || !varDsc->lvSingleDef || !varTypeIsEnregisterable(typ)) { continue; } /* For lvNormalizeOnLoad(), we need to add a cast to the copy-assignment like "copyLclNum = int(varDsc)" and optAssertionGen() only tracks simple assignments. The same goes for lvNormalizedOnStore as the cast is generated in fgMorphSmpOpAsg. This boils down to not having a copy until optAssertionGen handles this*/ if (varDsc->lvNormalizeOnLoad() || varDsc->lvNormalizeOnStore()) { continue; } if (varTypeIsSmall(varDsc->TypeGet()) || typ == TYP_BOOL) { continue; } // If locals must be initialized to zero, that initialization counts as a second definition. // VB in particular allows usage of variables not explicitly initialized. // Note that this effectively disables this optimization for all local variables // as C# sets InitLocals all the time starting in Whidbey. if (!varDsc->lvIsParam && info.compInitMem) { continue; } // On x86 we may want to add a copy for an incoming double parameter // because we can ensure that the copy we make is double aligned // where as we can never ensure the alignment of an incoming double parameter // // On all other platforms we will never need to make a copy // for an incoming double parameter bool isFloatParam = false; #ifdef TARGET_X86 isFloatParam = varDsc->lvIsParam && varTypeIsFloating(typ); #endif if (!isFloatParam && !varDsc->lvVolatileHint) { continue; } // We don't want to add a copy for a variable that is part of a struct if (varDsc->lvIsStructField) { continue; } // We require that the weighted ref count be significant. if (varDsc->lvRefCntWtd() <= (BB_LOOP_WEIGHT_SCALE * BB_UNITY_WEIGHT / 2)) { continue; } // For parameters, we only want to add a copy for the heavier-than-average // uses instead of adding a copy to cover every single use. // 'paramImportantUseDom' is the set of blocks that dominate the // heavier-than-average uses of a parameter. // Initial value is all blocks. BlockSet paramImportantUseDom(BlockSetOps::MakeFull(this)); // This will be threshold for determining heavier-than-average uses weight_t paramAvgWtdRefDiv2 = (varDsc->lvRefCntWtd() + varDsc->lvRefCnt() / 2) / (varDsc->lvRefCnt() * 2); bool paramFoundImportantUse = false; #ifdef DEBUG if (verbose) { printf("Trying to add a copy for V%02u %s, avg_wtd = %s\n", lclNum, varDsc->lvIsParam ? "an arg" : "a local", refCntWtd2str(paramAvgWtdRefDiv2)); } #endif // // We must have a ref in a block that is dominated only by the entry block // if (BlockSetOps::MayBeUninit(varDsc->lvRefBlks)) { // No references continue; } bool isDominatedByFirstBB = false; BlockSetOps::Iter iter(this, varDsc->lvRefBlks); unsigned bbNum = 0; while (iter.NextElem(&bbNum)) { /* Find the block 'bbNum' */ BasicBlock* block = fgFirstBB; while (block && (block->bbNum != bbNum)) { block = block->bbNext; } noway_assert(block && (block->bbNum == bbNum)); bool importantUseInBlock = (varDsc->lvIsParam) && (block->getBBWeight(this) > paramAvgWtdRefDiv2); bool isPreHeaderBlock = ((block->bbFlags & BBF_LOOP_PREHEADER) != 0); BlockSet blockDom(BlockSetOps::UninitVal()); BlockSet blockDomSub0(BlockSetOps::UninitVal()); if (block->bbIDom == nullptr && isPreHeaderBlock) { // Loop Preheader blocks that we insert will have a bbDom set that is nullptr // but we can instead use the bNext successor block's dominator information noway_assert(block->bbNext != nullptr); BlockSetOps::AssignNoCopy(this, blockDom, fgGetDominatorSet(block->bbNext)); } else { BlockSetOps::AssignNoCopy(this, blockDom, fgGetDominatorSet(block)); } if (!BlockSetOps::IsEmpty(this, blockDom)) { BlockSetOps::Assign(this, blockDomSub0, blockDom); if (isPreHeaderBlock) { // We must clear bbNext block number from the dominator set BlockSetOps::RemoveElemD(this, blockDomSub0, block->bbNext->bbNum); } /* Is this block dominated by fgFirstBB? */ if (BlockSetOps::IsMember(this, blockDomSub0, fgFirstBB->bbNum)) { isDominatedByFirstBB = true; } } #ifdef DEBUG if (verbose) { printf(" Referenced in " FMT_BB ", bbWeight is %s", bbNum, refCntWtd2str(block->getBBWeight(this))); if (isDominatedByFirstBB) { printf(", which is dominated by BB01"); } if (importantUseInBlock) { printf(", ImportantUse"); } printf("\n"); } #endif /* If this is a heavier-than-average block, then track which blocks dominate this use of the parameter. */ if (importantUseInBlock) { paramFoundImportantUse = true; BlockSetOps::IntersectionD(this, paramImportantUseDom, blockDomSub0); // Clear blocks that do not dominate } } // We should have found at least one heavier-than-averageDiv2 block. if (varDsc->lvIsParam) { if (!paramFoundImportantUse) { continue; } } // For us to add a new copy: // we require that we have a floating point parameter // or a lvVolatile variable that is always reached from the first BB // and we have at least one block available in paramImportantUseDom // bool doCopy = (isFloatParam || (isDominatedByFirstBB && varDsc->lvVolatileHint)) && !BlockSetOps::IsEmpty(this, paramImportantUseDom); // Under stress mode we expand the number of candidates // to include parameters of any type // or any variable that is always reached from the first BB // if (compStressCompile(STRESS_GENERIC_VARN, 30)) { // Ensure that we preserve the invariants required by the subsequent code. if (varDsc->lvIsParam || isDominatedByFirstBB) { doCopy = true; } } if (!doCopy) { continue; } Statement* stmt; unsigned copyLclNum = lvaGrabTemp(false DEBUGARG("optAddCopies")); // Because lvaGrabTemp may have reallocated the lvaTable, ensure varDsc is still in sync. varDsc = lvaGetDesc(lclNum); // Set lvType on the new Temp Lcl Var lvaGetDesc(copyLclNum)->lvType = typ; #ifdef DEBUG if (verbose) { printf("\n Finding the best place to insert the assignment V%02i=V%02i\n", copyLclNum, lclNum); } #endif if (varDsc->lvIsParam) { noway_assert(varDsc->lvDefStmt == nullptr || varDsc->lvIsStructField); // Create a new copy assignment tree GenTree* copyAsgn = gtNewTempAssign(copyLclNum, gtNewLclvNode(lclNum, typ)); /* Find the best block to insert the new assignment */ /* We will choose the lowest weighted block, and within */ /* those block, the highest numbered block which */ /* dominates all the uses of the local variable */ /* Our default is to use the first block */ BasicBlock* bestBlock = fgFirstBB; weight_t bestWeight = bestBlock->getBBWeight(this); BasicBlock* block = bestBlock; #ifdef DEBUG if (verbose) { printf(" Starting at " FMT_BB ", bbWeight is %s", block->bbNum, refCntWtd2str(block->getBBWeight(this))); printf(", bestWeight is %s\n", refCntWtd2str(bestWeight)); } #endif /* We have already calculated paramImportantUseDom above. */ BlockSetOps::Iter iter(this, paramImportantUseDom); unsigned bbNum = 0; while (iter.NextElem(&bbNum)) { /* Advance block to point to 'bbNum' */ /* This assumes that the iterator returns block number is increasing lexical order. */ while (block && (block->bbNum != bbNum)) { block = block->bbNext; } noway_assert(block && (block->bbNum == bbNum)); #ifdef DEBUG if (verbose) { printf(" Considering " FMT_BB ", bbWeight is %s", block->bbNum, refCntWtd2str(block->getBBWeight(this))); printf(", bestWeight is %s\n", refCntWtd2str(bestWeight)); } #endif // Does this block have a smaller bbWeight value? if (block->getBBWeight(this) > bestWeight) { #ifdef DEBUG if (verbose) { printf("bbWeight too high\n"); } #endif continue; } // Don't use blocks that are exception handlers because // inserting a new first statement will interface with // the CATCHARG if (handlerGetsXcptnObj(block->bbCatchTyp)) { #ifdef DEBUG if (verbose) { printf("Catch block\n"); } #endif continue; } // Don't use the BBJ_ALWAYS block marked with BBF_KEEP_BBJ_ALWAYS. These // are used by EH code. The JIT can not generate code for such a block. if (block->bbFlags & BBF_KEEP_BBJ_ALWAYS) { #if defined(FEATURE_EH_FUNCLETS) // With funclets, this is only used for BBJ_CALLFINALLY/BBJ_ALWAYS pairs. For x86, it is also used // as the "final step" block for leaving finallys. assert(block->isBBCallAlwaysPairTail()); #endif // FEATURE_EH_FUNCLETS #ifdef DEBUG if (verbose) { printf("Internal EH BBJ_ALWAYS block\n"); } #endif continue; } // This block will be the new candidate for the insert point // for the new assignment CLANG_FORMAT_COMMENT_ANCHOR; #ifdef DEBUG if (verbose) { printf("new bestBlock\n"); } #endif bestBlock = block; bestWeight = block->getBBWeight(this); } // If there is a use of the variable in this block // then we insert the assignment at the beginning // otherwise we insert the statement at the end CLANG_FORMAT_COMMENT_ANCHOR; #ifdef DEBUG if (verbose) { printf(" Insert copy at the %s of " FMT_BB "\n", (BlockSetOps::IsEmpty(this, paramImportantUseDom) || BlockSetOps::IsMember(this, varDsc->lvRefBlks, bestBlock->bbNum)) ? "start" : "end", bestBlock->bbNum); } #endif if (BlockSetOps::IsEmpty(this, paramImportantUseDom) || BlockSetOps::IsMember(this, varDsc->lvRefBlks, bestBlock->bbNum)) { stmt = fgNewStmtAtBeg(bestBlock, copyAsgn); } else { stmt = fgNewStmtNearEnd(bestBlock, copyAsgn); } } else { noway_assert(varDsc->lvDefStmt != nullptr); /* Locate the assignment to varDsc in the lvDefStmt */ stmt = varDsc->lvDefStmt; optAddCopyLclNum = lclNum; // in optAddCopyAsgnNode = nullptr; // out fgWalkTreePre(stmt->GetRootNodePointer(), Compiler::optAddCopiesCallback, (void*)this, false); noway_assert(optAddCopyAsgnNode); GenTree* tree = optAddCopyAsgnNode; GenTree* op1 = tree->AsOp()->gtOp1; noway_assert(tree && op1 && tree->OperIs(GT_ASG) && (op1->gtOper == GT_LCL_VAR) && (op1->AsLclVarCommon()->GetLclNum() == lclNum)); /* Assign the old expression into the new temp */ GenTree* newAsgn = gtNewTempAssign(copyLclNum, tree->AsOp()->gtOp2); /* Copy the new temp to op1 */ GenTree* copyAsgn = gtNewAssignNode(op1, gtNewLclvNode(copyLclNum, typ)); /* Change the tree to a GT_COMMA with the two assignments as child nodes */ tree->gtBashToNOP(); tree->ChangeOper(GT_COMMA); tree->AsOp()->gtOp1 = newAsgn; tree->AsOp()->gtOp2 = copyAsgn; tree->gtFlags |= (newAsgn->gtFlags & GTF_ALL_EFFECT); tree->gtFlags |= (copyAsgn->gtFlags & GTF_ALL_EFFECT); } #ifdef DEBUG if (verbose) { printf("\nIntroducing a new copy for V%02u\n", lclNum); gtDispTree(stmt->GetRootNode()); printf("\n"); } #endif } } //------------------------------------------------------------------------------ // GetAssertionDep: Retrieve the assertions on this local variable // // Arguments: // lclNum - The local var id. // // Return Value: // The dependent assertions (assertions using the value of the local var) // of the local var. // ASSERT_TP& Compiler::GetAssertionDep(unsigned lclNum) { JitExpandArray<ASSERT_TP>& dep = *optAssertionDep; if (dep[lclNum] == nullptr) { dep[lclNum] = BitVecOps::MakeEmpty(apTraits); } return dep[lclNum]; } /***************************************************************************** * * Initialize the assertion prop bitset traits and the default bitsets. */ void Compiler::optAssertionTraitsInit(AssertionIndex assertionCount) { apTraits = new (this, CMK_AssertionProp) BitVecTraits(assertionCount, this); apFull = BitVecOps::MakeFull(apTraits); } /***************************************************************************** * * Initialize the assertion prop tracking logic. */ void Compiler::optAssertionInit(bool isLocalProp) { // Use a function countFunc to determine a proper maximum assertion count for the // method being compiled. The function is linear to the IL size for small and // moderate methods. For large methods, considering throughput impact, we track no // more than 64 assertions. // Note this tracks at most only 256 assertions. static const AssertionIndex countFunc[] = {64, 128, 256, 64}; static const unsigned lowerBound = 0; static const unsigned upperBound = ArrLen(countFunc) - 1; const unsigned codeSize = info.compILCodeSize / 512; optMaxAssertionCount = countFunc[isLocalProp ? lowerBound : min(upperBound, codeSize)]; optLocalAssertionProp = isLocalProp; optAssertionTabPrivate = new (this, CMK_AssertionProp) AssertionDsc[optMaxAssertionCount]; optComplementaryAssertionMap = new (this, CMK_AssertionProp) AssertionIndex[optMaxAssertionCount + 1](); // zero-inited (NO_ASSERTION_INDEX) assert(NO_ASSERTION_INDEX == 0); if (!isLocalProp) { optValueNumToAsserts = new (getAllocator(CMK_AssertionProp)) ValueNumToAssertsMap(getAllocator(CMK_AssertionProp)); } if (optAssertionDep == nullptr) { optAssertionDep = new (this, CMK_AssertionProp) JitExpandArray<ASSERT_TP>(getAllocator(CMK_AssertionProp), max(1, lvaCount)); } optAssertionTraitsInit(optMaxAssertionCount); optAssertionCount = 0; optAssertionPropagated = false; bbJtrueAssertionOut = nullptr; } #ifdef DEBUG void Compiler::optPrintAssertion(AssertionDsc* curAssertion, AssertionIndex assertionIndex /* = 0 */) { if (curAssertion->op1.kind == O1K_EXACT_TYPE) { printf("Type "); } else if (curAssertion->op1.kind == O1K_ARR_BND) { printf("ArrBnds "); } else if (curAssertion->op1.kind == O1K_SUBTYPE) { printf("Subtype "); } else if (curAssertion->op2.kind == O2K_LCLVAR_COPY) { printf("Copy "); } else if ((curAssertion->op2.kind == O2K_CONST_INT) || (curAssertion->op2.kind == O2K_CONST_LONG) || (curAssertion->op2.kind == O2K_CONST_DOUBLE) || (curAssertion->op2.kind == O2K_ZEROOBJ)) { printf("Constant "); } else if (curAssertion->op2.kind == O2K_SUBRANGE) { printf("Subrange "); } else { printf("?assertion classification? "); } printf("Assertion: "); if (!optLocalAssertionProp) { printf("(" FMT_VN "," FMT_VN ") ", curAssertion->op1.vn, curAssertion->op2.vn); } if ((curAssertion->op1.kind == O1K_LCLVAR) || (curAssertion->op1.kind == O1K_EXACT_TYPE) || (curAssertion->op1.kind == O1K_SUBTYPE)) { printf("V%02u", curAssertion->op1.lcl.lclNum); if (curAssertion->op1.lcl.ssaNum != SsaConfig::RESERVED_SSA_NUM) { printf(".%02u", curAssertion->op1.lcl.ssaNum); } } else if (curAssertion->op1.kind == O1K_ARR_BND) { printf("[idx:"); vnStore->vnDump(this, curAssertion->op1.bnd.vnIdx); printf(";len:"); vnStore->vnDump(this, curAssertion->op1.bnd.vnLen); printf("]"); } else if (curAssertion->op1.kind == O1K_BOUND_OPER_BND) { printf("Oper_Bnd"); vnStore->vnDump(this, curAssertion->op1.vn); } else if (curAssertion->op1.kind == O1K_BOUND_LOOP_BND) { printf("Loop_Bnd"); vnStore->vnDump(this, curAssertion->op1.vn); } else if (curAssertion->op1.kind == O1K_CONSTANT_LOOP_BND) { printf("Const_Loop_Bnd"); vnStore->vnDump(this, curAssertion->op1.vn); } else if (curAssertion->op1.kind == O1K_CONSTANT_LOOP_BND_UN) { printf("Const_Loop_Bnd_Un"); vnStore->vnDump(this, curAssertion->op1.vn); } else if (curAssertion->op1.kind == O1K_VALUE_NUMBER) { printf("Value_Number"); vnStore->vnDump(this, curAssertion->op1.vn); } else { printf("?op1.kind?"); } if (curAssertion->assertionKind == OAK_SUBRANGE) { printf(" in "); } else if (curAssertion->assertionKind == OAK_EQUAL) { if (curAssertion->op1.kind == O1K_LCLVAR) { printf(" == "); } else { printf(" is "); } } else if (curAssertion->assertionKind == OAK_NO_THROW) { printf(" in range "); } else if (curAssertion->assertionKind == OAK_NOT_EQUAL) { if (curAssertion->op1.kind == O1K_LCLVAR) { printf(" != "); } else { printf(" is not "); } } else { printf(" ?assertionKind? "); } if (curAssertion->op1.kind != O1K_ARR_BND) { switch (curAssertion->op2.kind) { case O2K_LCLVAR_COPY: printf("V%02u", curAssertion->op2.lcl.lclNum); if (curAssertion->op1.lcl.ssaNum != SsaConfig::RESERVED_SSA_NUM) { printf(".%02u", curAssertion->op1.lcl.ssaNum); } if (curAssertion->op2.zeroOffsetFieldSeq != nullptr) { printf(" Zero"); gtDispFieldSeq(curAssertion->op2.zeroOffsetFieldSeq); } break; case O2K_CONST_INT: case O2K_IND_CNS_INT: if (curAssertion->op1.kind == O1K_EXACT_TYPE) { printf("Exact Type MT(%08X)", dspPtr(curAssertion->op2.u1.iconVal)); assert(curAssertion->op2.u1.iconFlags != GTF_EMPTY); } else if (curAssertion->op1.kind == O1K_SUBTYPE) { printf("MT(%08X)", dspPtr(curAssertion->op2.u1.iconVal)); assert(curAssertion->op2.u1.iconFlags != GTF_EMPTY); } else if ((curAssertion->op1.kind == O1K_BOUND_OPER_BND) || (curAssertion->op1.kind == O1K_BOUND_LOOP_BND) || (curAssertion->op1.kind == O1K_CONSTANT_LOOP_BND) || (curAssertion->op1.kind == O1K_CONSTANT_LOOP_BND_UN)) { assert(!optLocalAssertionProp); vnStore->vnDump(this, curAssertion->op2.vn); } else { var_types op1Type; if (curAssertion->op1.kind == O1K_VALUE_NUMBER) { op1Type = vnStore->TypeOfVN(curAssertion->op1.vn); } else { unsigned lclNum = curAssertion->op1.lcl.lclNum; op1Type = lvaGetDesc(lclNum)->lvType; } if (op1Type == TYP_REF) { assert(curAssertion->op2.u1.iconVal == 0); printf("null"); } else { if ((curAssertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK) != 0) { printf("[%08p]", dspPtr(curAssertion->op2.u1.iconVal)); } else { printf("%d", curAssertion->op2.u1.iconVal); } } } break; case O2K_CONST_LONG: printf("0x%016llx", curAssertion->op2.lconVal); break; case O2K_CONST_DOUBLE: if (*((__int64*)&curAssertion->op2.dconVal) == (__int64)I64(0x8000000000000000)) { printf("-0.00000"); } else { printf("%#lg", curAssertion->op2.dconVal); } break; case O2K_ZEROOBJ: printf("ZeroObj"); break; case O2K_SUBRANGE: IntegralRange::Print(curAssertion->op2.u2); break; default: printf("?op2.kind?"); break; } } if (assertionIndex > 0) { printf(", index = "); optPrintAssertionIndex(assertionIndex); } printf("\n"); } void Compiler::optPrintAssertionIndex(AssertionIndex index) { if (index == NO_ASSERTION_INDEX) { printf("#NA"); return; } printf("#%02u", index); } void Compiler::optPrintAssertionIndices(ASSERT_TP assertions) { if (BitVecOps::IsEmpty(apTraits, assertions)) { optPrintAssertionIndex(NO_ASSERTION_INDEX); return; } BitVecOps::Iter iter(apTraits, assertions); unsigned bitIndex = 0; if (iter.NextElem(&bitIndex)) { optPrintAssertionIndex(static_cast<AssertionIndex>(bitIndex + 1)); while (iter.NextElem(&bitIndex)) { printf(" "); optPrintAssertionIndex(static_cast<AssertionIndex>(bitIndex + 1)); } } } #endif // DEBUG /* static */ void Compiler::optDumpAssertionIndices(const char* header, ASSERT_TP assertions, const char* footer /* = nullptr */) { #ifdef DEBUG Compiler* compiler = JitTls::GetCompiler(); if (compiler->verbose) { printf(header); compiler->optPrintAssertionIndices(assertions); if (footer != nullptr) { printf(footer); } } #endif // DEBUG } /* static */ void Compiler::optDumpAssertionIndices(ASSERT_TP assertions, const char* footer /* = nullptr */) { optDumpAssertionIndices("", assertions, footer); } /****************************************************************************** * * Helper to retrieve the "assertIndex" assertion. Note that assertIndex 0 * is NO_ASSERTION_INDEX and "optAssertionCount" is the last valid index. * */ Compiler::AssertionDsc* Compiler::optGetAssertion(AssertionIndex assertIndex) { assert(NO_ASSERTION_INDEX == 0); assert(assertIndex != NO_ASSERTION_INDEX); assert(assertIndex <= optAssertionCount); AssertionDsc* assertion = &optAssertionTabPrivate[assertIndex - 1]; #ifdef DEBUG optDebugCheckAssertion(assertion); #endif return assertion; } //------------------------------------------------------------------------ // optCreateAssertion: Create an (op1 assertionKind op2) assertion. // // Arguments: // op1 - the first assertion operand // op2 - the second assertion operand // assertionKind - the assertion kind // helperCallArgs - when true this indicates that the assertion operands // are the arguments of a type cast helper call such as // CORINFO_HELP_ISINSTANCEOFCLASS // Return Value: // The new assertion index or NO_ASSERTION_INDEX if a new assertion // was not created. // // Notes: // Assertion creation may fail either because the provided assertion // operands aren't supported or because the assertion table is full. // AssertionIndex Compiler::optCreateAssertion(GenTree* op1, GenTree* op2, optAssertionKind assertionKind, bool helperCallArgs) { assert(op1 != nullptr); assert(!helperCallArgs || (op2 != nullptr)); AssertionDsc assertion = {OAK_INVALID}; assert(assertion.assertionKind == OAK_INVALID); if (op1->OperIs(GT_BOUNDS_CHECK)) { if (assertionKind == OAK_NO_THROW) { GenTreeBoundsChk* arrBndsChk = op1->AsBoundsChk(); assertion.assertionKind = assertionKind; assertion.op1.kind = O1K_ARR_BND; assertion.op1.bnd.vnIdx = vnStore->VNConservativeNormalValue(arrBndsChk->GetIndex()->gtVNPair); assertion.op1.bnd.vnLen = vnStore->VNConservativeNormalValue(arrBndsChk->GetArrayLength()->gtVNPair); goto DONE_ASSERTION; } } // // Are we trying to make a non-null assertion? // if (op2 == nullptr) { // // Must be an OAK_NOT_EQUAL assertion // noway_assert(assertionKind == OAK_NOT_EQUAL); // // Set op1 to the instance pointer of the indirection // ssize_t offset = 0; while ((op1->gtOper == GT_ADD) && (op1->gtType == TYP_BYREF)) { if (op1->gtGetOp2()->IsCnsIntOrI()) { offset += op1->gtGetOp2()->AsIntCon()->gtIconVal; op1 = op1->gtGetOp1(); } else if (op1->gtGetOp1()->IsCnsIntOrI()) { offset += op1->gtGetOp1()->AsIntCon()->gtIconVal; op1 = op1->gtGetOp2(); } else { break; } } if (fgIsBigOffset(offset) || op1->gtOper != GT_LCL_VAR) { goto DONE_ASSERTION; // Don't make an assertion } unsigned lclNum = op1->AsLclVarCommon()->GetLclNum(); LclVarDsc* lclVar = lvaGetDesc(lclNum); ValueNum vn; // // We only perform null-checks on GC refs // so only make non-null assertions about GC refs or byrefs if we can't determine // the corresponding ref. // if (lclVar->TypeGet() != TYP_REF) { if (optLocalAssertionProp || (lclVar->TypeGet() != TYP_BYREF)) { goto DONE_ASSERTION; // Don't make an assertion } vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); VNFuncApp funcAttr; // Try to get value number corresponding to the GC ref of the indirection while (vnStore->GetVNFunc(vn, &funcAttr) && (funcAttr.m_func == (VNFunc)GT_ADD) && (vnStore->TypeOfVN(vn) == TYP_BYREF)) { if (vnStore->IsVNConstant(funcAttr.m_args[1]) && varTypeIsIntegral(vnStore->TypeOfVN(funcAttr.m_args[1]))) { offset += vnStore->CoercedConstantValue<ssize_t>(funcAttr.m_args[1]); vn = funcAttr.m_args[0]; } else if (vnStore->IsVNConstant(funcAttr.m_args[0]) && varTypeIsIntegral(vnStore->TypeOfVN(funcAttr.m_args[0]))) { offset += vnStore->CoercedConstantValue<ssize_t>(funcAttr.m_args[0]); vn = funcAttr.m_args[1]; } else { break; } } if (fgIsBigOffset(offset)) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op1.kind = O1K_VALUE_NUMBER; } else { // If the local variable has its address exposed then bail if (lclVar->IsAddressExposed()) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op1.kind = O1K_LCLVAR; assertion.op1.lcl.lclNum = lclNum; assertion.op1.lcl.ssaNum = op1->AsLclVarCommon()->GetSsaNum(); vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); } assertion.op1.vn = vn; assertion.assertionKind = assertionKind; assertion.op2.kind = O2K_CONST_INT; assertion.op2.vn = ValueNumStore::VNForNull(); assertion.op2.u1.iconVal = 0; assertion.op2.u1.iconFlags = GTF_EMPTY; #ifdef TARGET_64BIT assertion.op2.u1.iconFlags |= GTF_ASSERTION_PROP_LONG; // Signify that this is really TYP_LONG #endif // TARGET_64BIT } // // Are we making an assertion about a local variable? // else if (op1->gtOper == GT_LCL_VAR) { unsigned lclNum = op1->AsLclVarCommon()->GetLclNum(); LclVarDsc* lclVar = lvaGetDesc(lclNum); // If the local variable has its address exposed then bail if (lclVar->IsAddressExposed()) { goto DONE_ASSERTION; // Don't make an assertion } if (helperCallArgs) { // // Must either be an OAK_EQUAL or an OAK_NOT_EQUAL assertion // if ((assertionKind != OAK_EQUAL) && (assertionKind != OAK_NOT_EQUAL)) { goto DONE_ASSERTION; // Don't make an assertion } if (op2->gtOper == GT_IND) { op2 = op2->AsOp()->gtOp1; assertion.op2.kind = O2K_IND_CNS_INT; } else { assertion.op2.kind = O2K_CONST_INT; } if (op2->gtOper != GT_CNS_INT) { goto DONE_ASSERTION; // Don't make an assertion } // // TODO-CQ: Check for Sealed class and change kind to O1K_EXACT_TYPE // And consider the special cases, like CORINFO_FLG_SHAREDINST or CORINFO_FLG_VARIANCE // where a class can be sealed, but they don't behave as exact types because casts to // non-base types sometimes still succeed. // assertion.op1.kind = O1K_SUBTYPE; assertion.op1.lcl.lclNum = lclNum; assertion.op1.vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); assertion.op1.lcl.ssaNum = op1->AsLclVarCommon()->GetSsaNum(); assertion.op2.u1.iconVal = op2->AsIntCon()->gtIconVal; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); assertion.op2.u1.iconFlags = op2->GetIconHandleFlag(); // // Ok everything has been set and the assertion looks good // assertion.assertionKind = assertionKind; } else // !helperCallArgs { /* Skip over a GT_COMMA node(s), if necessary */ while (op2->gtOper == GT_COMMA) { op2 = op2->AsOp()->gtOp2; } assertion.op1.kind = O1K_LCLVAR; assertion.op1.lcl.lclNum = lclNum; assertion.op1.vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); assertion.op1.lcl.ssaNum = op1->AsLclVarCommon()->GetSsaNum(); switch (op2->gtOper) { optOp2Kind op2Kind; // // Constant Assertions // case GT_CNS_INT: if (varTypeIsStruct(op1)) { assert(op2->IsIntegralConst(0)); op2Kind = O2K_ZEROOBJ; } else { op2Kind = O2K_CONST_INT; } goto CNS_COMMON; case GT_CNS_LNG: op2Kind = O2K_CONST_LONG; goto CNS_COMMON; case GT_CNS_DBL: op2Kind = O2K_CONST_DOUBLE; goto CNS_COMMON; CNS_COMMON: { // // Must either be an OAK_EQUAL or an OAK_NOT_EQUAL assertion // if ((assertionKind != OAK_EQUAL) && (assertionKind != OAK_NOT_EQUAL)) { goto DONE_ASSERTION; // Don't make an assertion } // If the LclVar is a TYP_LONG then we only make // assertions where op2 is also TYP_LONG // if ((lclVar->TypeGet() == TYP_LONG) && (op2->TypeGet() != TYP_LONG)) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op2.kind = op2Kind; assertion.op2.lconVal = 0; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); if (op2->gtOper == GT_CNS_INT) { #ifdef TARGET_ARM // Do not Constant-Prop large constants for ARM // TODO-CrossBitness: we wouldn't need the cast below if GenTreeIntCon::gtIconVal had // target_ssize_t type. if (!codeGen->validImmForMov((target_ssize_t)op2->AsIntCon()->gtIconVal)) { goto DONE_ASSERTION; // Don't make an assertion } #endif // TARGET_ARM assertion.op2.u1.iconVal = op2->AsIntCon()->gtIconVal; assertion.op2.u1.iconFlags = op2->GetIconHandleFlag(); #ifdef TARGET_64BIT if (op2->TypeGet() == TYP_LONG || op2->TypeGet() == TYP_BYREF) { assertion.op2.u1.iconFlags |= GTF_ASSERTION_PROP_LONG; // Signify that this is really TYP_LONG } #endif // TARGET_64BIT } else if (op2->gtOper == GT_CNS_LNG) { assertion.op2.lconVal = op2->AsLngCon()->gtLconVal; } else { noway_assert(op2->gtOper == GT_CNS_DBL); /* If we have an NaN value then don't record it */ if (_isnan(op2->AsDblCon()->gtDconVal)) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op2.dconVal = op2->AsDblCon()->gtDconVal; } // // Ok everything has been set and the assertion looks good // assertion.assertionKind = assertionKind; goto DONE_ASSERTION; } // // Copy Assertions // case GT_LCL_VAR: { // // Must either be an OAK_EQUAL or an OAK_NOT_EQUAL assertion // if ((assertionKind != OAK_EQUAL) && (assertionKind != OAK_NOT_EQUAL)) { goto DONE_ASSERTION; // Don't make an assertion } unsigned lclNum2 = op2->AsLclVarCommon()->GetLclNum(); LclVarDsc* lclVar2 = lvaGetDesc(lclNum2); // If the two locals are the same then bail if (lclNum == lclNum2) { goto DONE_ASSERTION; // Don't make an assertion } // If the types are different then bail */ if (lclVar->lvType != lclVar2->lvType) { goto DONE_ASSERTION; // Don't make an assertion } // If we're making a copy of a "normalize on load" lclvar then the destination // has to be "normalize on load" as well, otherwise we risk skipping normalization. if (lclVar2->lvNormalizeOnLoad() && !lclVar->lvNormalizeOnLoad()) { goto DONE_ASSERTION; // Don't make an assertion } // If the local variable has its address exposed then bail if (lclVar2->IsAddressExposed()) { goto DONE_ASSERTION; // Don't make an assertion } FieldSeqNode* zeroOffsetFieldSeq = nullptr; GetZeroOffsetFieldMap()->Lookup(op2, &zeroOffsetFieldSeq); assertion.op2.kind = O2K_LCLVAR_COPY; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); assertion.op2.lcl.lclNum = lclNum2; assertion.op2.lcl.ssaNum = op2->AsLclVarCommon()->GetSsaNum(); assertion.op2.zeroOffsetFieldSeq = zeroOffsetFieldSeq; // Ok everything has been set and the assertion looks good assertion.assertionKind = assertionKind; goto DONE_ASSERTION; } default: break; } // Try and see if we can make a subrange assertion. if (((assertionKind == OAK_SUBRANGE) || (assertionKind == OAK_EQUAL)) && varTypeIsIntegral(op2)) { IntegralRange nodeRange = IntegralRange::ForNode(op2, this); IntegralRange typeRange = IntegralRange::ForType(genActualType(op2)); assert(typeRange.Contains(nodeRange)); if (!typeRange.Equals(nodeRange)) { assertion.op2.kind = O2K_SUBRANGE; assertion.assertionKind = OAK_SUBRANGE; assertion.op2.u2 = nodeRange; } } } } // // Are we making an IsType assertion? // else if (op1->gtOper == GT_IND) { op1 = op1->AsOp()->gtOp1; // // Is this an indirection of a local variable? // if (op1->gtOper == GT_LCL_VAR) { unsigned lclNum = op1->AsLclVarCommon()->GetLclNum(); // If the local variable is not in SSA then bail if (!lvaInSsa(lclNum)) { goto DONE_ASSERTION; } // If we have an typeHnd indirection then op1 must be a TYP_REF // and the indirection must produce a TYP_I // if (op1->gtType != TYP_REF) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op1.kind = O1K_EXACT_TYPE; assertion.op1.lcl.lclNum = lclNum; assertion.op1.vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); assertion.op1.lcl.ssaNum = op1->AsLclVarCommon()->GetSsaNum(); assert((assertion.op1.lcl.ssaNum == SsaConfig::RESERVED_SSA_NUM) || (assertion.op1.vn == vnStore->VNConservativeNormalValue( lvaGetDesc(lclNum)->GetPerSsaData(assertion.op1.lcl.ssaNum)->m_vnPair))); ssize_t cnsValue = 0; GenTreeFlags iconFlags = GTF_EMPTY; // Ngen case if (op2->gtOper == GT_IND) { if (!optIsTreeKnownIntValue(!optLocalAssertionProp, op2->AsOp()->gtOp1, &cnsValue, &iconFlags)) { goto DONE_ASSERTION; // Don't make an assertion } assertion.assertionKind = assertionKind; assertion.op2.kind = O2K_IND_CNS_INT; assertion.op2.u1.iconVal = cnsValue; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->AsOp()->gtOp1->gtVNPair); /* iconFlags should only contain bits in GTF_ICON_HDL_MASK */ assert((iconFlags & ~GTF_ICON_HDL_MASK) == 0); assertion.op2.u1.iconFlags = iconFlags; #ifdef TARGET_64BIT if (op2->AsOp()->gtOp1->TypeGet() == TYP_LONG) { assertion.op2.u1.iconFlags |= GTF_ASSERTION_PROP_LONG; // Signify that this is really TYP_LONG } #endif // TARGET_64BIT } // JIT case else if (optIsTreeKnownIntValue(!optLocalAssertionProp, op2, &cnsValue, &iconFlags)) { assertion.assertionKind = assertionKind; assertion.op2.kind = O2K_CONST_INT; assertion.op2.u1.iconVal = cnsValue; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); /* iconFlags should only contain bits in GTF_ICON_HDL_MASK */ assert((iconFlags & ~GTF_ICON_HDL_MASK) == 0); assertion.op2.u1.iconFlags = iconFlags; #ifdef TARGET_64BIT if (op2->TypeGet() == TYP_LONG) { assertion.op2.u1.iconFlags |= GTF_ASSERTION_PROP_LONG; // Signify that this is really TYP_LONG } #endif // TARGET_64BIT } else { goto DONE_ASSERTION; // Don't make an assertion } } } DONE_ASSERTION: return optFinalizeCreatingAssertion(&assertion); } //------------------------------------------------------------------------ // optFinalizeCreatingAssertion: Add the assertion, if well-formed, to the table. // // Checks that in global assertion propagation assertions do not have missing // value and SSA numbers. // // Arguments: // assertion - assertion to check and add to the table // // Return Value: // Index of the assertion if it was successfully created, NO_ASSERTION_INDEX otherwise. // AssertionIndex Compiler::optFinalizeCreatingAssertion(AssertionDsc* assertion) { if (assertion->assertionKind == OAK_INVALID) { return NO_ASSERTION_INDEX; } if (!optLocalAssertionProp) { if ((assertion->op1.vn == ValueNumStore::NoVN) || (assertion->op2.vn == ValueNumStore::NoVN) || (assertion->op1.vn == ValueNumStore::VNForVoid()) || (assertion->op2.vn == ValueNumStore::VNForVoid())) { return NO_ASSERTION_INDEX; } // TODO: only copy assertions rely on valid SSA number so we could generate more assertions here if ((assertion->op1.kind != O1K_VALUE_NUMBER) && (assertion->op1.lcl.ssaNum == SsaConfig::RESERVED_SSA_NUM)) { return NO_ASSERTION_INDEX; } } // Now add the assertion to our assertion table noway_assert(assertion->op1.kind != O1K_INVALID); noway_assert((assertion->op1.kind == O1K_ARR_BND) || (assertion->op2.kind != O2K_INVALID)); return optAddAssertion(assertion); } /***************************************************************************** * * If tree is a constant node holding an integral value, retrieve the value in * pConstant. If the method returns true, pConstant holds the appropriate * constant. Set "vnBased" to true to indicate local or global assertion prop. * "pFlags" indicates if the constant is a handle marked by GTF_ICON_HDL_MASK. */ bool Compiler::optIsTreeKnownIntValue(bool vnBased, GenTree* tree, ssize_t* pConstant, GenTreeFlags* pFlags) { // Is Local assertion prop? if (!vnBased) { if (tree->OperGet() == GT_CNS_INT) { *pConstant = tree->AsIntCon()->IconValue(); *pFlags = tree->GetIconHandleFlag(); return true; } #ifdef TARGET_64BIT // Just to be clear, get it from gtLconVal rather than // overlapping gtIconVal. else if (tree->OperGet() == GT_CNS_LNG) { *pConstant = tree->AsLngCon()->gtLconVal; *pFlags = tree->GetIconHandleFlag(); return true; } #endif return false; } // Global assertion prop ValueNum vn = vnStore->VNConservativeNormalValue(tree->gtVNPair); if (!vnStore->IsVNConstant(vn)) { return false; } // ValueNumber 'vn' indicates that this node evaluates to a constant var_types vnType = vnStore->TypeOfVN(vn); if (vnType == TYP_INT) { *pConstant = vnStore->ConstantValue<int>(vn); *pFlags = vnStore->IsVNHandle(vn) ? vnStore->GetHandleFlags(vn) : GTF_EMPTY; return true; } #ifdef TARGET_64BIT else if (vnType == TYP_LONG) { *pConstant = vnStore->ConstantValue<INT64>(vn); *pFlags = vnStore->IsVNHandle(vn) ? vnStore->GetHandleFlags(vn) : GTF_EMPTY; return true; } #endif return false; } #ifdef DEBUG /***************************************************************************** * * Print the assertions related to a VN for all VNs. * */ void Compiler::optPrintVnAssertionMapping() { printf("\nVN Assertion Mapping\n"); printf("---------------------\n"); for (ValueNumToAssertsMap::KeyIterator ki = optValueNumToAsserts->Begin(); !ki.Equal(optValueNumToAsserts->End()); ++ki) { printf("(%d => ", ki.Get()); printf("%s)\n", BitVecOps::ToString(apTraits, ki.GetValue())); } } #endif /***************************************************************************** * * Maintain a map "optValueNumToAsserts" i.e., vn -> to set of assertions * about that VN. Given "assertions" about a "vn" add it to the previously * mapped assertions about that "vn." */ void Compiler::optAddVnAssertionMapping(ValueNum vn, AssertionIndex index) { ASSERT_TP* cur = optValueNumToAsserts->LookupPointer(vn); if (cur == nullptr) { optValueNumToAsserts->Set(vn, BitVecOps::MakeSingleton(apTraits, index - 1)); } else { BitVecOps::AddElemD(apTraits, *cur, index - 1); } } /***************************************************************************** * Statically if we know that this assertion's VN involves a NaN don't bother * wasting an assertion table slot. */ bool Compiler::optAssertionVnInvolvesNan(AssertionDsc* assertion) { if (optLocalAssertionProp) { return false; } static const int SZ = 2; ValueNum vns[SZ] = {assertion->op1.vn, assertion->op2.vn}; for (int i = 0; i < SZ; ++i) { if (vnStore->IsVNConstant(vns[i])) { var_types type = vnStore->TypeOfVN(vns[i]); if ((type == TYP_FLOAT && _isnan(vnStore->ConstantValue<float>(vns[i])) != 0) || (type == TYP_DOUBLE && _isnan(vnStore->ConstantValue<double>(vns[i])) != 0)) { return true; } } } return false; } /***************************************************************************** * * Given an assertion add it to the assertion table * * If it is already in the assertion table return the assertionIndex that * we use to refer to this element. * Otherwise add it to the assertion table ad return the assertionIndex that * we use to refer to this element. * If we need to add to the table and the table is full return the value zero */ AssertionIndex Compiler::optAddAssertion(AssertionDsc* newAssertion) { noway_assert(newAssertion->assertionKind != OAK_INVALID); // Even though the propagation step takes care of NaN, just a check // to make sure there is no slot involving a NaN. if (optAssertionVnInvolvesNan(newAssertion)) { JITDUMP("Assertion involved Nan not adding\n"); return NO_ASSERTION_INDEX; } // Check if exists already, so we can skip adding new one. Search backwards. for (AssertionIndex index = optAssertionCount; index >= 1; index--) { AssertionDsc* curAssertion = optGetAssertion(index); if (curAssertion->Equals(newAssertion, !optLocalAssertionProp)) { return index; } } // Check if we are within max count. if (optAssertionCount >= optMaxAssertionCount) { return NO_ASSERTION_INDEX; } optAssertionTabPrivate[optAssertionCount] = *newAssertion; optAssertionCount++; #ifdef DEBUG if (verbose) { printf("GenTreeNode creates assertion:\n"); gtDispTree(optAssertionPropCurrentTree, nullptr, nullptr, true); printf(optLocalAssertionProp ? "In " FMT_BB " New Local " : "In " FMT_BB " New Global ", compCurBB->bbNum); optPrintAssertion(newAssertion, optAssertionCount); } #endif // DEBUG // Assertion mask bits are [index + 1]. if (optLocalAssertionProp) { assert(newAssertion->op1.kind == O1K_LCLVAR); // Mark the variables this index depends on unsigned lclNum = newAssertion->op1.lcl.lclNum; BitVecOps::AddElemD(apTraits, GetAssertionDep(lclNum), optAssertionCount - 1); if (newAssertion->op2.kind == O2K_LCLVAR_COPY) { lclNum = newAssertion->op2.lcl.lclNum; BitVecOps::AddElemD(apTraits, GetAssertionDep(lclNum), optAssertionCount - 1); } } else // If global assertion prop, then add it to the dependents map. { optAddVnAssertionMapping(newAssertion->op1.vn, optAssertionCount); if (newAssertion->op2.kind == O2K_LCLVAR_COPY) { optAddVnAssertionMapping(newAssertion->op2.vn, optAssertionCount); } } #ifdef DEBUG optDebugCheckAssertions(optAssertionCount); #endif return optAssertionCount; } #ifdef DEBUG void Compiler::optDebugCheckAssertion(AssertionDsc* assertion) { assert(assertion->assertionKind < OAK_COUNT); assert(assertion->op1.kind < O1K_COUNT); assert(assertion->op2.kind < O2K_COUNT); // It would be good to check that op1.vn and op2.vn are valid value numbers. switch (assertion->op1.kind) { case O1K_LCLVAR: case O1K_EXACT_TYPE: case O1K_SUBTYPE: assert(optLocalAssertionProp || lvaGetDesc(assertion->op1.lcl.lclNum)->lvPerSsaData.IsValidSsaNum(assertion->op1.lcl.ssaNum)); break; case O1K_ARR_BND: // It would be good to check that bnd.vnIdx and bnd.vnLen are valid value numbers. break; case O1K_BOUND_OPER_BND: case O1K_BOUND_LOOP_BND: case O1K_CONSTANT_LOOP_BND: case O1K_CONSTANT_LOOP_BND_UN: case O1K_VALUE_NUMBER: assert(!optLocalAssertionProp); break; default: break; } switch (assertion->op2.kind) { case O2K_IND_CNS_INT: case O2K_CONST_INT: { // The only flags that can be set are those in the GTF_ICON_HDL_MASK, or GTF_ASSERTION_PROP_LONG, which is // used to indicate a long constant. #ifdef TARGET_64BIT assert((assertion->op2.u1.iconFlags & ~(GTF_ICON_HDL_MASK | GTF_ASSERTION_PROP_LONG)) == 0); #else assert((assertion->op2.u1.iconFlags & ~GTF_ICON_HDL_MASK) == 0); #endif switch (assertion->op1.kind) { case O1K_EXACT_TYPE: case O1K_SUBTYPE: assert(assertion->op2.u1.iconFlags != GTF_EMPTY); break; case O1K_LCLVAR: assert((lvaGetDesc(assertion->op1.lcl.lclNum)->lvType != TYP_REF) || (assertion->op2.u1.iconVal == 0) || doesMethodHaveFrozenString()); break; case O1K_VALUE_NUMBER: assert((vnStore->TypeOfVN(assertion->op1.vn) != TYP_REF) || (assertion->op2.u1.iconVal == 0)); break; default: break; } } break; case O2K_CONST_LONG: { // All handles should be represented by O2K_CONST_INT, // so no handle bits should be set here. assert((assertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK) == 0); } break; case O2K_ZEROOBJ: { // We only make these assertion for assignments (not control flow). assert(assertion->assertionKind == OAK_EQUAL); // We use "optLocalAssertionIsEqualOrNotEqual" to find these. assert(assertion->op2.u1.iconVal == 0); } break; default: // for all other 'assertion->op2.kind' values we don't check anything break; } } /***************************************************************************** * * Verify that assertion prop related assumptions are valid. If "index" * is 0 (i.e., NO_ASSERTION_INDEX) then verify all assertions in the table. * If "index" is between 1 and optAssertionCount, then verify the assertion * desc corresponding to "index." */ void Compiler::optDebugCheckAssertions(AssertionIndex index) { AssertionIndex start = (index == NO_ASSERTION_INDEX) ? 1 : index; AssertionIndex end = (index == NO_ASSERTION_INDEX) ? optAssertionCount : index; for (AssertionIndex ind = start; ind <= end; ++ind) { AssertionDsc* assertion = optGetAssertion(ind); optDebugCheckAssertion(assertion); } } #endif //------------------------------------------------------------------------ // optCreateComplementaryAssertion: Create an assertion that is the complementary // of the specified assertion. // // Arguments: // assertionIndex - the index of the assertion // op1 - the first assertion operand // op2 - the second assertion operand // helperCallArgs - when true this indicates that the assertion operands // are the arguments of a type cast helper call such as // CORINFO_HELP_ISINSTANCEOFCLASS // // Notes: // The created complementary assertion is associated with the original // assertion such that it can be found by optFindComplementary. // void Compiler::optCreateComplementaryAssertion(AssertionIndex assertionIndex, GenTree* op1, GenTree* op2, bool helperCallArgs) { if (assertionIndex == NO_ASSERTION_INDEX) { return; } AssertionDsc& candidateAssertion = *optGetAssertion(assertionIndex); if ((candidateAssertion.op1.kind == O1K_BOUND_OPER_BND) || (candidateAssertion.op1.kind == O1K_BOUND_LOOP_BND) || (candidateAssertion.op1.kind == O1K_CONSTANT_LOOP_BND) || (candidateAssertion.op1.kind == O1K_CONSTANT_LOOP_BND_UN)) { AssertionDsc dsc = candidateAssertion; dsc.assertionKind = dsc.assertionKind == OAK_EQUAL ? OAK_NOT_EQUAL : OAK_EQUAL; optAddAssertion(&dsc); return; } if (candidateAssertion.assertionKind == OAK_EQUAL) { AssertionIndex index = optCreateAssertion(op1, op2, OAK_NOT_EQUAL, helperCallArgs); optMapComplementary(index, assertionIndex); } else if (candidateAssertion.assertionKind == OAK_NOT_EQUAL) { AssertionIndex index = optCreateAssertion(op1, op2, OAK_EQUAL, helperCallArgs); optMapComplementary(index, assertionIndex); } // Are we making a subtype or exact type assertion? if ((candidateAssertion.op1.kind == O1K_SUBTYPE) || (candidateAssertion.op1.kind == O1K_EXACT_TYPE)) { optCreateAssertion(op1, nullptr, OAK_NOT_EQUAL); } } // optAssertionGenCast: Create a tentative subrange assertion for a cast. // // This function will try to create an assertion that the cast's operand // is within the "input" range for the cast, so that this assertion can // later be proven via implication and the cast removed. Such assertions // are only generated during global propagation, and only for LCL_VARs. // // Arguments: // cast - the cast node for which to create the assertion // // Return Value: // Index of the generated assertion, or NO_ASSERTION_INDEX if it was not // legal, profitable, or possible to create one. // AssertionIndex Compiler::optAssertionGenCast(GenTreeCast* cast) { if (optLocalAssertionProp || !varTypeIsIntegral(cast) || !varTypeIsIntegral(cast->CastOp())) { return NO_ASSERTION_INDEX; } // This condition exists to preverve previous behavior. if (!cast->CastOp()->OperIs(GT_LCL_VAR)) { return NO_ASSERTION_INDEX; } GenTreeLclVar* lclVar = cast->CastOp()->AsLclVar(); LclVarDsc* varDsc = lvaGetDesc(lclVar); // It is not useful to make assertions about address-exposed variables, they will never be proven. if (varDsc->IsAddressExposed()) { return NO_ASSERTION_INDEX; } // A representation-changing cast cannot be simplified if it is not checked. if (!cast->gtOverflow() && (genActualType(cast) != genActualType(lclVar))) { return NO_ASSERTION_INDEX; } AssertionDsc assertion = {OAK_SUBRANGE}; assertion.op1.kind = O1K_LCLVAR; assertion.op1.vn = vnStore->VNConservativeNormalValue(lclVar->gtVNPair); assertion.op1.lcl.lclNum = lclVar->GetLclNum(); assertion.op1.lcl.ssaNum = lclVar->GetSsaNum(); assertion.op2.kind = O2K_SUBRANGE; assertion.op2.u2 = IntegralRange::ForCastInput(cast); return optFinalizeCreatingAssertion(&assertion); } //------------------------------------------------------------------------ // optCreateJtrueAssertions: Create assertions about a JTRUE's relop operands. // // Arguments: // op1 - the first assertion operand // op2 - the second assertion operand // assertionKind - the assertion kind // helperCallArgs - when true this indicates that the assertion operands // are the arguments of a type cast helper call such as // CORINFO_HELP_ISINSTANCEOFCLASS // Return Value: // The new assertion index or NO_ASSERTION_INDEX if a new assertion // was not created. // // Notes: // Assertion creation may fail either because the provided assertion // operands aren't supported or because the assertion table is full. // If an assertion is created succesfully then an attempt is made to also // create a second, complementary assertion. This may too fail, for the // same reasons as the first one. // AssertionIndex Compiler::optCreateJtrueAssertions(GenTree* op1, GenTree* op2, Compiler::optAssertionKind assertionKind, bool helperCallArgs) { AssertionIndex assertionIndex = optCreateAssertion(op1, op2, assertionKind, helperCallArgs); // Don't bother if we don't have an assertion on the JTrue False path. Current implementation // allows for a complementary only if there is an assertion on the False path (tree->HasAssertion()). if (assertionIndex != NO_ASSERTION_INDEX) { optCreateComplementaryAssertion(assertionIndex, op1, op2, helperCallArgs); } return assertionIndex; } AssertionInfo Compiler::optCreateJTrueBoundsAssertion(GenTree* tree) { GenTree* relop = tree->gtGetOp1(); if (!relop->OperIsCompare()) { return NO_ASSERTION_INDEX; } GenTree* op1 = relop->gtGetOp1(); GenTree* op2 = relop->gtGetOp2(); ValueNum op1VN = vnStore->VNConservativeNormalValue(op1->gtVNPair); ValueNum op2VN = vnStore->VNConservativeNormalValue(op2->gtVNPair); ValueNum relopVN = vnStore->VNConservativeNormalValue(relop->gtVNPair); bool hasTestAgainstZero = (relop->gtOper == GT_EQ || relop->gtOper == GT_NE) && (op2VN == vnStore->VNZeroForType(op2->TypeGet())); ValueNumStore::UnsignedCompareCheckedBoundInfo unsignedCompareBnd; // Cases where op1 holds the upper bound arithmetic and op2 is 0. // Loop condition like: "i < bnd +/-k == 0" // Assertion: "i < bnd +/- k == 0" if (hasTestAgainstZero && vnStore->IsVNCompareCheckedBoundArith(op1VN)) { AssertionDsc dsc; dsc.assertionKind = relop->gtOper == GT_EQ ? OAK_EQUAL : OAK_NOT_EQUAL; dsc.op1.kind = O1K_BOUND_OPER_BND; dsc.op1.vn = op1VN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(op2->TypeGet()); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Cases where op1 holds the lhs of the condition and op2 holds the bound arithmetic. // Loop condition like: "i < bnd +/-k" // Assertion: "i < bnd +/- k != 0" else if (vnStore->IsVNCompareCheckedBoundArith(relopVN)) { AssertionDsc dsc; dsc.assertionKind = OAK_NOT_EQUAL; dsc.op1.kind = O1K_BOUND_OPER_BND; dsc.op1.vn = relopVN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(op2->TypeGet()); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Cases where op1 holds the upper bound and op2 is 0. // Loop condition like: "i < bnd == 0" // Assertion: "i < bnd == false" else if (hasTestAgainstZero && vnStore->IsVNCompareCheckedBound(op1VN)) { AssertionDsc dsc; dsc.assertionKind = relop->gtOper == GT_EQ ? OAK_EQUAL : OAK_NOT_EQUAL; dsc.op1.kind = O1K_BOUND_LOOP_BND; dsc.op1.vn = op1VN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(op2->TypeGet()); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Cases where op1 holds the lhs of the condition op2 holds the bound. // Loop condition like "i < bnd" // Assertion: "i < bnd != 0" else if (vnStore->IsVNCompareCheckedBound(relopVN)) { AssertionDsc dsc; dsc.assertionKind = OAK_NOT_EQUAL; dsc.op1.kind = O1K_BOUND_LOOP_BND; dsc.op1.vn = relopVN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(TYP_INT); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Loop condition like "(uint)i < (uint)bnd" or equivalent // Assertion: "no throw" since this condition guarantees that i is both >= 0 and < bnd (on the appropiate edge) else if (vnStore->IsVNUnsignedCompareCheckedBound(relopVN, &unsignedCompareBnd)) { assert(unsignedCompareBnd.vnIdx != ValueNumStore::NoVN); assert((unsignedCompareBnd.cmpOper == VNF_LT_UN) || (unsignedCompareBnd.cmpOper == VNF_GE_UN)); assert(vnStore->IsVNCheckedBound(unsignedCompareBnd.vnBound)); AssertionDsc dsc; dsc.assertionKind = OAK_NO_THROW; dsc.op1.kind = O1K_ARR_BND; dsc.op1.vn = relopVN; dsc.op1.bnd.vnIdx = unsignedCompareBnd.vnIdx; dsc.op1.bnd.vnLen = vnStore->VNNormalValue(unsignedCompareBnd.vnBound); dsc.op2.kind = O2K_INVALID; dsc.op2.vn = ValueNumStore::NoVN; AssertionIndex index = optAddAssertion(&dsc); if (unsignedCompareBnd.cmpOper == VNF_GE_UN) { // By default JTRUE generated assertions hold on the "jump" edge. We have i >= bnd but we're really // after i < bnd so we need to change the assertion edge to "next". return AssertionInfo::ForNextEdge(index); } return index; } // Cases where op1 holds the condition bound check and op2 is 0. // Loop condition like: "i < 100 == 0" // Assertion: "i < 100 == false" else if (hasTestAgainstZero && vnStore->IsVNConstantBound(op1VN)) { AssertionDsc dsc; dsc.assertionKind = relop->gtOper == GT_EQ ? OAK_EQUAL : OAK_NOT_EQUAL; dsc.op1.kind = O1K_CONSTANT_LOOP_BND; dsc.op1.vn = op1VN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(op2->TypeGet()); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Cases where op1 holds the lhs of the condition op2 holds rhs. // Loop condition like "i < 100" // Assertion: "i < 100 != 0" else if (vnStore->IsVNConstantBound(relopVN)) { AssertionDsc dsc; dsc.assertionKind = OAK_NOT_EQUAL; dsc.op1.kind = O1K_CONSTANT_LOOP_BND; dsc.op1.vn = relopVN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(TYP_INT); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } else if (vnStore->IsVNConstantBoundUnsigned(relopVN)) { AssertionDsc dsc; dsc.assertionKind = OAK_NOT_EQUAL; dsc.op1.kind = O1K_CONSTANT_LOOP_BND_UN; dsc.op1.vn = relopVN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(TYP_INT); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Compute assertions for the JTrue node. */ AssertionInfo Compiler::optAssertionGenJtrue(GenTree* tree) { // Only create assertions for JTRUE when we are in the global phase if (optLocalAssertionProp) { return NO_ASSERTION_INDEX; } GenTree* relop = tree->AsOp()->gtOp1; if (!relop->OperIsCompare()) { return NO_ASSERTION_INDEX; } Compiler::optAssertionKind assertionKind = OAK_INVALID; AssertionInfo info = optCreateJTrueBoundsAssertion(tree); if (info.HasAssertion()) { return info; } // Find assertion kind. switch (relop->gtOper) { case GT_EQ: assertionKind = OAK_EQUAL; break; case GT_NE: assertionKind = OAK_NOT_EQUAL; break; default: // TODO-CQ: add other relop operands. Disabled for now to measure perf // and not occupy assertion table slots. We'll add them when used. return NO_ASSERTION_INDEX; } // Look through any CSEs so we see the actual trees providing values, if possible. // This is important for exact type assertions, which need to see the GT_IND. // GenTree* op1 = relop->AsOp()->gtOp1->gtCommaAssignVal(); GenTree* op2 = relop->AsOp()->gtOp2->gtCommaAssignVal(); // Check for op1 or op2 to be lcl var and if so, keep it in op1. if ((op1->gtOper != GT_LCL_VAR) && (op2->gtOper == GT_LCL_VAR)) { std::swap(op1, op2); } ValueNum op1VN = vnStore->VNConservativeNormalValue(op1->gtVNPair); ValueNum op2VN = vnStore->VNConservativeNormalValue(op2->gtVNPair); // If op1 is lcl and op2 is const or lcl, create assertion. if ((op1->gtOper == GT_LCL_VAR) && (op2->OperIsConst() || (op2->gtOper == GT_LCL_VAR))) // Fix for Dev10 851483 { return optCreateJtrueAssertions(op1, op2, assertionKind); } else if (vnStore->IsVNCheckedBound(op1VN) && vnStore->IsVNInt32Constant(op2VN)) { assert(relop->OperIs(GT_EQ, GT_NE)); int con = vnStore->ConstantValue<int>(op2VN); if (con >= 0) { AssertionDsc dsc; // For arr.Length != 0, we know that 0 is a valid index // For arr.Length == con, we know that con - 1 is the greatest valid index if (con == 0) { dsc.assertionKind = OAK_NOT_EQUAL; dsc.op1.bnd.vnIdx = vnStore->VNForIntCon(0); } else { dsc.assertionKind = OAK_EQUAL; dsc.op1.bnd.vnIdx = vnStore->VNForIntCon(con - 1); } dsc.op1.vn = op1VN; dsc.op1.kind = O1K_ARR_BND; dsc.op1.bnd.vnLen = op1VN; dsc.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); dsc.op2.kind = O2K_CONST_INT; dsc.op2.u1.iconFlags = GTF_EMPTY; dsc.op2.u1.iconVal = 0; // when con is not zero, create an assertion on the arr.Length == con edge // when con is zero, create an assertion on the arr.Length != 0 edge AssertionIndex index = optAddAssertion(&dsc); if (relop->OperIs(GT_NE) != (con == 0)) { return AssertionInfo::ForNextEdge(index); } else { return index; } } } // Check op1 and op2 for an indirection of a GT_LCL_VAR and keep it in op1. if (((op1->gtOper != GT_IND) || (op1->AsOp()->gtOp1->gtOper != GT_LCL_VAR)) && ((op2->gtOper == GT_IND) && (op2->AsOp()->gtOp1->gtOper == GT_LCL_VAR))) { std::swap(op1, op2); } // If op1 is ind, then extract op1's oper. if ((op1->gtOper == GT_IND) && (op1->AsOp()->gtOp1->gtOper == GT_LCL_VAR)) { return optCreateJtrueAssertions(op1, op2, assertionKind); } // Look for a call to an IsInstanceOf helper compared to a nullptr if ((op2->gtOper != GT_CNS_INT) && (op1->gtOper == GT_CNS_INT)) { std::swap(op1, op2); } // Validate op1 and op2 if ((op1->gtOper != GT_CALL) || (op1->AsCall()->gtCallType != CT_HELPER) || (op1->TypeGet() != TYP_REF) || // op1 (op2->gtOper != GT_CNS_INT) || (op2->AsIntCon()->gtIconVal != 0)) // op2 { return NO_ASSERTION_INDEX; } GenTreeCall* call = op1->AsCall(); // Note CORINFO_HELP_READYTORUN_ISINSTANCEOF does not have the same argument pattern. // In particular, it is not possible to deduce what class is being tested from its args. // // Also note The CASTCLASS helpers won't appear in predicates as they throw on failure. // So the helper list here is smaller than the one in optAssertionProp_Call. if ((call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFINTERFACE)) || (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFARRAY)) || (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFCLASS)) || (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFANY))) { fgArgInfo* const argInfo = call->fgArgInfo; GenTree* objectNode = argInfo->GetArgNode(1); GenTree* methodTableNode = argInfo->GetArgNode(0); assert(objectNode->TypeGet() == TYP_REF); assert(methodTableNode->TypeGet() == TYP_I_IMPL); // Reverse the assertion assert((assertionKind == OAK_EQUAL) || (assertionKind == OAK_NOT_EQUAL)); assertionKind = (assertionKind == OAK_EQUAL) ? OAK_NOT_EQUAL : OAK_EQUAL; if (objectNode->OperIs(GT_LCL_VAR)) { return optCreateJtrueAssertions(objectNode, methodTableNode, assertionKind, /* helperCallArgs */ true); } } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Create an assertion on the phi node if some information can be gleaned * from all of the constituent phi operands. * */ AssertionIndex Compiler::optAssertionGenPhiDefn(GenTree* tree) { if (!tree->IsPhiDefn()) { return NO_ASSERTION_INDEX; } // Try to find if all phi arguments are known to be non-null. bool isNonNull = true; for (GenTreePhi::Use& use : tree->AsOp()->gtGetOp2()->AsPhi()->Uses()) { if (!vnStore->IsKnownNonNull(use.GetNode()->gtVNPair.GetConservative())) { isNonNull = false; break; } } // All phi arguments are non-null implies phi rhs is non-null. if (isNonNull) { return optCreateAssertion(tree->AsOp()->gtOp1, nullptr, OAK_NOT_EQUAL); } return NO_ASSERTION_INDEX; } /***************************************************************************** * * If this statement creates a value assignment or assertion * then assign an index to the given value assignment by adding * it to the lookup table, if necessary. */ void Compiler::optAssertionGen(GenTree* tree) { tree->ClearAssertion(); // If there are QMARKs in the IR, we won't generate assertions // for conditionally executed code. // if (optLocalAssertionProp && ((tree->gtFlags & GTF_COLON_COND) != 0)) { return; } #ifdef DEBUG optAssertionPropCurrentTree = tree; #endif // For most of the assertions that we create below // the assertion is true after the tree is processed bool assertionProven = true; AssertionInfo assertionInfo; switch (tree->gtOper) { case GT_ASG: // An indirect store - we can create a non-null assertion. Note that we do not lose out // on the dataflow assertions here as local propagation only deals with LCL_VAR LHSs. if (tree->AsOp()->gtGetOp1()->OperIsIndir()) { assertionInfo = optCreateAssertion(tree->AsOp()->gtGetOp1()->AsIndir()->Addr(), nullptr, OAK_NOT_EQUAL); } // VN takes care of non local assertions for assignments and data flow. else if (optLocalAssertionProp) { assertionInfo = optCreateAssertion(tree->AsOp()->gtOp1, tree->AsOp()->gtOp2, OAK_EQUAL); } else { assertionInfo = optAssertionGenPhiDefn(tree); } break; case GT_OBJ: case GT_BLK: case GT_IND: // R-value indirections create non-null assertions, but not all indirections are R-values. // Those under ADDR nodes or on the LHS of ASGs are "locations", and will not end up // dereferencing their operands. We cannot reliably detect them here, however, and so // will have to rely on the conservative approximation of the GTF_NO_CSE flag. if (tree->CanCSE()) { assertionInfo = optCreateAssertion(tree->AsIndir()->Addr(), nullptr, OAK_NOT_EQUAL); } break; case GT_ARR_LENGTH: // An array length is an (always R-value) indirection (but doesn't derive from GenTreeIndir). assertionInfo = optCreateAssertion(tree->AsArrLen()->ArrRef(), nullptr, OAK_NOT_EQUAL); break; case GT_NULLCHECK: // Explicit null checks always create non-null assertions. assertionInfo = optCreateAssertion(tree->AsIndir()->Addr(), nullptr, OAK_NOT_EQUAL); break; case GT_INTRINSIC: if (tree->AsIntrinsic()->gtIntrinsicName == NI_System_Object_GetType) { assertionInfo = optCreateAssertion(tree->AsIntrinsic()->gtGetOp1(), nullptr, OAK_NOT_EQUAL); } break; case GT_BOUNDS_CHECK: if (!optLocalAssertionProp) { assertionInfo = optCreateAssertion(tree, nullptr, OAK_NO_THROW); } break; case GT_ARR_ELEM: // An array element reference can create a non-null assertion assertionInfo = optCreateAssertion(tree->AsArrElem()->gtArrObj, nullptr, OAK_NOT_EQUAL); break; case GT_CALL: { // A virtual call can create a non-null assertion. We transform some virtual calls into non-virtual calls // with a GTF_CALL_NULLCHECK flag set. // Ignore tail calls because they have 'this` pointer in the regular arg list and an implicit null check. GenTreeCall* const call = tree->AsCall(); if (call->NeedsNullCheck() || (call->IsVirtual() && !call->IsTailCall())) { // Retrieve the 'this' arg. GenTree* thisArg = gtGetThisArg(call); assert(thisArg != nullptr); assertionInfo = optCreateAssertion(thisArg, nullptr, OAK_NOT_EQUAL); } } break; case GT_CAST: // This represets an assertion that we would like to prove to be true. // If we can prove this assertion true then we can eliminate this cast. // We only create this assertion for global assertion propagation. assertionInfo = optAssertionGenCast(tree->AsCast()); assertionProven = false; break; case GT_JTRUE: assertionInfo = optAssertionGenJtrue(tree); break; default: // All other gtOper node kinds, leave 'assertionIndex' = NO_ASSERTION_INDEX break; } // For global assertion prop we must store the assertion number in the tree node if (assertionInfo.HasAssertion() && assertionProven && !optLocalAssertionProp) { tree->SetAssertionInfo(assertionInfo); } } /***************************************************************************** * * Maps a complementary assertion to its original assertion so it can be * retrieved faster. */ void Compiler::optMapComplementary(AssertionIndex assertionIndex, AssertionIndex index) { if (assertionIndex == NO_ASSERTION_INDEX || index == NO_ASSERTION_INDEX) { return; } assert(assertionIndex <= optMaxAssertionCount); assert(index <= optMaxAssertionCount); optComplementaryAssertionMap[assertionIndex] = index; optComplementaryAssertionMap[index] = assertionIndex; } /***************************************************************************** * * Given an assertion index, return the assertion index of the complementary * assertion or 0 if one does not exist. */ AssertionIndex Compiler::optFindComplementary(AssertionIndex assertIndex) { if (assertIndex == NO_ASSERTION_INDEX) { return NO_ASSERTION_INDEX; } AssertionDsc* inputAssertion = optGetAssertion(assertIndex); // Must be an equal or not equal assertion. if (inputAssertion->assertionKind != OAK_EQUAL && inputAssertion->assertionKind != OAK_NOT_EQUAL) { return NO_ASSERTION_INDEX; } AssertionIndex index = optComplementaryAssertionMap[assertIndex]; if (index != NO_ASSERTION_INDEX && index <= optAssertionCount) { return index; } for (AssertionIndex index = 1; index <= optAssertionCount; ++index) { // Make sure assertion kinds are complementary and op1, op2 kinds match. AssertionDsc* curAssertion = optGetAssertion(index); if (curAssertion->Complementary(inputAssertion, !optLocalAssertionProp)) { optMapComplementary(assertIndex, index); return index; } } return NO_ASSERTION_INDEX; } //------------------------------------------------------------------------ // optAssertionIsSubrange: Find a subrange assertion for the given range and tree. // // This function will return the index of the first assertion in "assertions" // which claims that the value of "tree" is withing the bounds of the provided // "range" (i. e. "range.Contains(assertedRange)"). // // Arguments: // tree - the tree for which to find the assertion // range - range the subrange of which to look for // assertions - the set of assertions // // Return Value: // Index of the found assertion, NO_ASSERTION_INDEX otherwise. // AssertionIndex Compiler::optAssertionIsSubrange(GenTree* tree, IntegralRange range, ASSERT_VALARG_TP assertions) { if (!optLocalAssertionProp && BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } for (AssertionIndex index = 1; index <= optAssertionCount; index++) { AssertionDsc* curAssertion = optGetAssertion(index); if ((optLocalAssertionProp || BitVecOps::IsMember(apTraits, assertions, index - 1)) && // either local prop or use propagated assertions (curAssertion->assertionKind == OAK_SUBRANGE) && (curAssertion->op1.kind == O1K_LCLVAR)) { // For local assertion prop use comparison on locals, and use comparison on vns for global prop. bool isEqual = optLocalAssertionProp ? (curAssertion->op1.lcl.lclNum == tree->AsLclVarCommon()->GetLclNum()) : (curAssertion->op1.vn == vnStore->VNConservativeNormalValue(tree->gtVNPair)); if (!isEqual) { continue; } if (range.Contains(curAssertion->op2.u2)) { return index; } } } return NO_ASSERTION_INDEX; } /********************************************************************************** * * Given a "tree" that is usually arg1 of a isinst/cast kind of GT_CALL (a class * handle), and "methodTableArg" which is a const int (a class handle), then search * if there is an assertion in "assertions", that asserts the equality of the two * class handles and then returns the index of the assertion. If one such assertion * could not be found, then it returns NO_ASSERTION_INDEX. * */ AssertionIndex Compiler::optAssertionIsSubtype(GenTree* tree, GenTree* methodTableArg, ASSERT_VALARG_TP assertions) { if (!optLocalAssertionProp && BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } for (AssertionIndex index = 1; index <= optAssertionCount; index++) { if (!optLocalAssertionProp && !BitVecOps::IsMember(apTraits, assertions, index - 1)) { continue; } AssertionDsc* curAssertion = optGetAssertion(index); if (curAssertion->assertionKind != OAK_EQUAL || (curAssertion->op1.kind != O1K_SUBTYPE && curAssertion->op1.kind != O1K_EXACT_TYPE)) { continue; } // If local assertion prop use "lcl" based comparison, if global assertion prop use vn based comparison. if ((optLocalAssertionProp) ? (curAssertion->op1.lcl.lclNum != tree->AsLclVarCommon()->GetLclNum()) : (curAssertion->op1.vn != vnStore->VNConservativeNormalValue(tree->gtVNPair))) { continue; } if (curAssertion->op2.kind == O2K_IND_CNS_INT) { if (methodTableArg->gtOper != GT_IND) { continue; } methodTableArg = methodTableArg->AsOp()->gtOp1; } else if (curAssertion->op2.kind != O2K_CONST_INT) { continue; } ssize_t methodTableVal = 0; GenTreeFlags iconFlags = GTF_EMPTY; if (!optIsTreeKnownIntValue(!optLocalAssertionProp, methodTableArg, &methodTableVal, &iconFlags)) { continue; } if (curAssertion->op2.u1.iconVal == methodTableVal) { return index; } } return NO_ASSERTION_INDEX; } //------------------------------------------------------------------------------ // optVNConstantPropOnTree: Substitutes tree with an evaluated constant while // managing side-effects. // // Arguments: // block - The block containing the tree. // stmt - The statement in the block containing the tree. // tree - The tree node whose value is known at compile time. // The tree should have a constant value number. // // Return Value: // Returns a potentially new or a transformed tree node. // Returns nullptr when no transformation is possible. // // Description: // Transforms a tree node if its result evaluates to a constant. The // transformation can be a "ChangeOper" to a constant or a new constant node // with extracted side-effects. // // Before replacing or substituting the "tree" with a constant, extracts any // side effects from the "tree" and creates a comma separated side effect list // and then appends the transformed node at the end of the list. // This comma separated list is then returned. // // For JTrue nodes, side effects are not put into a comma separated list. If // the relop will evaluate to "true" or "false" statically, then the side-effects // will be put into new statements, presuming the JTrue will be folded away. // GenTree* Compiler::optVNConstantPropOnTree(BasicBlock* block, GenTree* tree) { if (tree->OperGet() == GT_JTRUE) { // Treat JTRUE separately to extract side effects into respective statements rather // than using a COMMA separated op1. return optVNConstantPropOnJTrue(block, tree); } // If relop is part of JTRUE, this should be optimized as part of the parent JTRUE. // Or if relop is part of QMARK or anything else, we simply bail here. else if (tree->OperIsCompare() && (tree->gtFlags & GTF_RELOP_JMP_USED)) { return nullptr; } // We want to use the Normal ValueNumber when checking for constants. ValueNumPair vnPair = tree->gtVNPair; ValueNum vnCns = vnStore->VNConservativeNormalValue(vnPair); // Check if node evaluates to a constant or Vector.Zero. if (!vnStore->IsVNConstant(vnCns) && !vnStore->IsVNVectorZero(vnCns)) { return nullptr; } GenTree* conValTree = nullptr; switch (vnStore->TypeOfVN(vnCns)) { case TYP_FLOAT: { float value = vnStore->ConstantValue<float>(vnCns); if (tree->TypeGet() == TYP_INT) { // Same sized reinterpretation of bits to integer conValTree = gtNewIconNode(*(reinterpret_cast<int*>(&value))); } else { // Implicit assignment conversion to float or double assert(varTypeIsFloating(tree->TypeGet())); conValTree = gtNewDconNode(value, tree->TypeGet()); } break; } case TYP_DOUBLE: { double value = vnStore->ConstantValue<double>(vnCns); if (tree->TypeGet() == TYP_LONG) { conValTree = gtNewLconNode(*(reinterpret_cast<INT64*>(&value))); } else { // Implicit assignment conversion to float or double assert(varTypeIsFloating(tree->TypeGet())); conValTree = gtNewDconNode(value, tree->TypeGet()); } break; } case TYP_LONG: { INT64 value = vnStore->ConstantValue<INT64>(vnCns); #ifdef TARGET_64BIT if (vnStore->IsVNHandle(vnCns)) { // Don't perform constant folding that involves a handle that needs // to be recorded as a relocation with the VM. if (!opts.compReloc) { conValTree = gtNewIconHandleNode(value, vnStore->GetHandleFlags(vnCns)); } } else #endif { switch (tree->TypeGet()) { case TYP_INT: // Implicit assignment conversion to smaller integer conValTree = gtNewIconNode(static_cast<int>(value)); break; case TYP_LONG: // Same type no conversion required conValTree = gtNewLconNode(value); break; case TYP_FLOAT: // No implicit conversions from long to float and value numbering will // not propagate through memory reinterpretations of different size. unreached(); break; case TYP_DOUBLE: // Same sized reinterpretation of bits to double conValTree = gtNewDconNode(*(reinterpret_cast<double*>(&value))); break; default: // Do not support such optimization. break; } } } break; case TYP_REF: { assert(vnStore->ConstantValue<size_t>(vnCns) == 0); // Support onle ref(ref(0)), do not support other forms (e.g byref(ref(0)). if (tree->TypeGet() == TYP_REF) { conValTree = gtNewIconNode(0, TYP_REF); } } break; case TYP_INT: { int value = vnStore->ConstantValue<int>(vnCns); #ifndef TARGET_64BIT if (vnStore->IsVNHandle(vnCns)) { // Don't perform constant folding that involves a handle that needs // to be recorded as a relocation with the VM. if (!opts.compReloc) { conValTree = gtNewIconHandleNode(value, vnStore->GetHandleFlags(vnCns)); } } else #endif { switch (tree->TypeGet()) { case TYP_REF: case TYP_INT: // Same type no conversion required conValTree = gtNewIconNode(value); break; case TYP_LONG: // Implicit assignment conversion to larger integer conValTree = gtNewLconNode(value); break; case TYP_FLOAT: // Same sized reinterpretation of bits to float conValTree = gtNewDconNode(*reinterpret_cast<float*>(&value), TYP_FLOAT); break; case TYP_DOUBLE: // No implicit conversions from int to double and value numbering will // not propagate through memory reinterpretations of different size. unreached(); break; case TYP_BOOL: case TYP_BYTE: case TYP_UBYTE: case TYP_SHORT: case TYP_USHORT: assert(FitsIn(tree->TypeGet(), value)); conValTree = gtNewIconNode(value); break; default: // Do not support (e.g. byref(const int)). break; } } } break; #if FEATURE_HW_INTRINSICS case TYP_SIMD8: case TYP_SIMD12: case TYP_SIMD16: case TYP_SIMD32: { assert(vnStore->IsVNVectorZero(vnCns)); VNSimdTypeInfo vnInfo = vnStore->GetVectorZeroSimdTypeOfVN(vnCns); assert(vnInfo.m_simdBaseJitType != CORINFO_TYPE_UNDEF); assert(vnInfo.m_simdSize != 0); assert(getSIMDTypeForSize(vnInfo.m_simdSize) == vnStore->TypeOfVN(vnCns)); conValTree = gtNewSimdZeroNode(tree->TypeGet(), vnInfo.m_simdBaseJitType, vnInfo.m_simdSize, true); } break; #endif case TYP_BYREF: // Do not support const byref optimization. break; default: // We do not record constants of other types. unreached(); break; } if (conValTree != nullptr) { // Were able to optimize. conValTree->gtVNPair = vnPair; GenTree* sideEffList = optExtractSideEffListFromConst(tree); if (sideEffList != nullptr) { // Replace as COMMA(side_effects, const value tree); assert((sideEffList->gtFlags & GTF_SIDE_EFFECT) != 0); return gtNewOperNode(GT_COMMA, conValTree->TypeGet(), sideEffList, conValTree); } else { // No side effects, replace as const value tree. return conValTree; } } else { // Was not able to optimize. return nullptr; } } //------------------------------------------------------------------------------ // optConstantAssertionProp: Possibly substitute a constant for a local use // // Arguments: // curAssertion - assertion to propagate // tree - tree to possibly modify // stmt - statement containing the tree // index - index of this assertion in the assertion table // // Returns: // Updated tree (may be the input tree, modified in place), or nullptr // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optConstantAssertionProp(AssertionDsc* curAssertion, GenTreeLclVarCommon* tree, Statement* stmt DEBUGARG(AssertionIndex index)) { const unsigned lclNum = tree->GetLclNum(); if (lclNumIsCSE(lclNum)) { return nullptr; } GenTree* newTree = tree; // Update 'newTree' with the new value from our table // Typically newTree == tree and we are updating the node in place switch (curAssertion->op2.kind) { case O2K_CONST_DOUBLE: // There could be a positive zero and a negative zero, so don't propagate zeroes. if (curAssertion->op2.dconVal == 0.0) { return nullptr; } newTree->BashToConst(curAssertion->op2.dconVal, tree->TypeGet()); break; case O2K_CONST_LONG: if (newTree->TypeIs(TYP_LONG)) { newTree->BashToConst(curAssertion->op2.lconVal); } else { newTree->BashToConst(static_cast<int32_t>(curAssertion->op2.lconVal)); } break; case O2K_CONST_INT: // Don't propagate handles if we need to report relocs. if (opts.compReloc && ((curAssertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK) != 0)) { return nullptr; } if (curAssertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK) { // Here we have to allocate a new 'large' node to replace the old one newTree = gtNewIconHandleNode(curAssertion->op2.u1.iconVal, curAssertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK); } else { bool isArrIndex = ((tree->gtFlags & GTF_VAR_ARR_INDEX) != 0); assert(varTypeIsIntegralOrI(tree)); newTree->BashToConst(curAssertion->op2.u1.iconVal, genActualType(tree)); // If we're doing an array index address, assume any constant propagated contributes to the index. if (isArrIndex) { newTree->AsIntCon()->gtFieldSeq = GetFieldSeqStore()->CreateSingleton(FieldSeqStore::ConstantIndexPseudoField); } newTree->gtFlags &= ~GTF_VAR_ARR_INDEX; } break; default: return nullptr; } if (!optLocalAssertionProp) { assert(newTree->OperIsConst()); // We should have a simple Constant node for newTree assert(vnStore->IsVNConstant(curAssertion->op2.vn)); // The value number stored for op2 should be a valid // VN representing the constant newTree->gtVNPair.SetBoth(curAssertion->op2.vn); // Set the ValueNumPair to the constant VN from op2 // of the assertion } #ifdef DEBUG if (verbose) { printf("\nAssertion prop in " FMT_BB ":\n", compCurBB->bbNum); optPrintAssertion(curAssertion, index); gtDispTree(newTree, nullptr, nullptr, true); } #endif return optAssertionProp_Update(newTree, tree, stmt); } //------------------------------------------------------------------------------ // optZeroObjAssertionProp: Find and propagate a ZEROOBJ assertion for the given tree. // // Arguments: // assertions - set of live assertions // tree - the tree to possibly replace, in-place, with a zero // // Returns: // Whether propagation took place. // // Notes: // Because not all users of struct nodes support "zero" operands, instead of // propagating ZEROOBJ on locals, we propagate it on their parents. // bool Compiler::optZeroObjAssertionProp(GenTree* tree, ASSERT_VALARG_TP assertions) { assert(varTypeIsStruct(tree)); // We only make ZEROOBJ assertions in local propagation. if (!optLocalAssertionProp) { return false; } if (!tree->OperIs(GT_LCL_VAR) || lvaGetDesc(tree->AsLclVar())->IsAddressExposed()) { return false; } unsigned lclNum = tree->AsLclVar()->GetLclNum(); AssertionIndex assertionIndex = optLocalAssertionIsEqualOrNotEqual(O1K_LCLVAR, lclNum, O2K_ZEROOBJ, 0, assertions); if (assertionIndex == NO_ASSERTION_INDEX) { return false; } AssertionDsc* assertion = optGetAssertion(assertionIndex); JITDUMP("\nAssertion prop in " FMT_BB ":\n", compCurBB->bbNum); JITDUMPEXEC(optPrintAssertion(assertion, assertionIndex)); DISPNODE(tree); tree->BashToZeroConst(TYP_INT); JITDUMP(" =>\n"); DISPNODE(tree); return true; } //------------------------------------------------------------------------------ // optAssertionProp_LclVarTypeCheck: verify compatible types for copy prop // // Arguments: // tree - tree to possibly modify // lclVarDsc - local accessed by tree // copyVarDsc - local to possibly copy prop into tree // // Returns: // True if copy prop is safe. // // Notes: // Before substituting copyVar for lclVar, make sure using copyVar doesn't widen access. // bool Compiler::optAssertionProp_LclVarTypeCheck(GenTree* tree, LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc) { /* Small struct field locals are stored using the exact width and loaded widened (i.e. lvNormalizeOnStore==false lvNormalizeOnLoad==true), because the field locals might end up embedded in the parent struct local with the exact width. In other words, a store to a short field local should always done using an exact width store [00254538] 0x0009 ------------ const int 0x1234 [002545B8] 0x000B -A--G--NR--- = short [00254570] 0x000A D------N---- lclVar short V43 tmp40 mov word ptr [L_043], 0x1234 Now, if we copy prop, say a short field local V43, to another short local V34 for the following tree: [04E18650] 0x0001 ------------ lclVar int V34 tmp31 [04E19714] 0x0002 -A---------- = int [04E196DC] 0x0001 D------N---- lclVar int V36 tmp33 We will end with this tree: [04E18650] 0x0001 ------------ lclVar int V43 tmp40 [04E19714] 0x0002 -A-----NR--- = int [04E196DC] 0x0001 D------N---- lclVar int V36 tmp33 EAX And eventually causing a fetch of 4-byte out from [L_043] :( mov EAX, dword ptr [L_043] The following check is to make sure we only perform the copy prop when we don't retrieve the wider value. */ if (copyVarDsc->lvIsStructField) { var_types varType = (var_types)copyVarDsc->lvType; // Make sure we don't retrieve the wider value. return !varTypeIsSmall(varType) || (varType == tree->TypeGet()); } // Called in the context of a single copy assertion, so the types should have been // taken care by the assertion gen logic for other cases. Just return true. return true; } //------------------------------------------------------------------------ // optCopyAssertionProp: copy prop use of one local with another // // Arguments: // curAssertion - assertion triggering the possible copy // tree - tree use to consider replacing // stmt - statment containing the tree // index - index of the assertion // // Returns: // Updated tree, or nullptr // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optCopyAssertionProp(AssertionDsc* curAssertion, GenTreeLclVarCommon* tree, Statement* stmt DEBUGARG(AssertionIndex index)) { const AssertionDsc::AssertionDscOp1& op1 = curAssertion->op1; const AssertionDsc::AssertionDscOp2& op2 = curAssertion->op2; noway_assert(op1.lcl.lclNum != op2.lcl.lclNum); const unsigned lclNum = tree->GetLclNum(); // Make sure one of the lclNum of the assertion matches with that of the tree. if (op1.lcl.lclNum != lclNum && op2.lcl.lclNum != lclNum) { return nullptr; } // Extract the matching lclNum and ssaNum, as well as the field sequence. unsigned copyLclNum; unsigned copySsaNum; FieldSeqNode* zeroOffsetFieldSeq; if (op1.lcl.lclNum == lclNum) { copyLclNum = op2.lcl.lclNum; copySsaNum = op2.lcl.ssaNum; zeroOffsetFieldSeq = op2.zeroOffsetFieldSeq; } else { copyLclNum = op1.lcl.lclNum; copySsaNum = op1.lcl.ssaNum; zeroOffsetFieldSeq = nullptr; // Only the RHS of an assignment can have a FldSeq. assert(optLocalAssertionProp); // Were we to perform replacements in global propagation, that makes copy // assertions for control flow ("if (a == b) { ... }"), where both operands // could have a FldSeq, we'd need to save it for "op1" too. } if (!optLocalAssertionProp) { // Extract the ssaNum of the matching lclNum. unsigned ssaNum = (op1.lcl.lclNum == lclNum) ? op1.lcl.ssaNum : op2.lcl.ssaNum; if (ssaNum != tree->GetSsaNum()) { return nullptr; } } LclVarDsc* const copyVarDsc = lvaGetDesc(copyLclNum); LclVarDsc* const lclVarDsc = lvaGetDesc(lclNum); // Make sure the types are compatible. if (!optAssertionProp_LclVarTypeCheck(tree, lclVarDsc, copyVarDsc)) { return nullptr; } // Make sure we can perform this copy prop. if (optCopyProp_LclVarScore(lclVarDsc, copyVarDsc, curAssertion->op1.lcl.lclNum == lclNum) <= 0) { return nullptr; } tree->SetLclNum(copyLclNum); tree->SetSsaNum(copySsaNum); // The sequence we are propagating (if any) represents the inner fields. if (zeroOffsetFieldSeq != nullptr) { FieldSeqNode* outerZeroOffsetFieldSeq = nullptr; if (GetZeroOffsetFieldMap()->Lookup(tree, &outerZeroOffsetFieldSeq)) { zeroOffsetFieldSeq = GetFieldSeqStore()->Append(zeroOffsetFieldSeq, outerZeroOffsetFieldSeq); GetZeroOffsetFieldMap()->Remove(tree); } fgAddFieldSeqForZeroOffset(tree, zeroOffsetFieldSeq); } #ifdef DEBUG if (verbose) { printf("\nAssertion prop in " FMT_BB ":\n", compCurBB->bbNum); optPrintAssertion(curAssertion, index); DISPNODE(tree); } #endif // Update and morph the tree. return optAssertionProp_Update(tree, tree, stmt); } //------------------------------------------------------------------------ // optAssertionProp_LclVar: try and optimize a local var use via assertions // // Arguments: // assertions - set of live assertions // tree - local use to optimize // stmt - statement containing the tree // // Returns: // Updated tree, or nullptr // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optAssertionProp_LclVar(ASSERT_VALARG_TP assertions, GenTreeLclVarCommon* tree, Statement* stmt) { // If we have a var definition then bail or // If this is the address of the var then it will have the GTF_DONT_CSE // flag set and we don't want to to assertion prop on it. if (tree->gtFlags & (GTF_VAR_DEF | GTF_DONT_CSE)) { return nullptr; } BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } // See if the variable is equal to a constant or another variable. AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if (curAssertion->assertionKind != OAK_EQUAL || curAssertion->op1.kind != O1K_LCLVAR) { continue; } // Copy prop. if (curAssertion->op2.kind == O2K_LCLVAR_COPY) { // Cannot do copy prop during global assertion prop because of no knowledge // of kill sets. We will still make a == b copy assertions during the global phase to allow // for any implied assertions that can be retrieved. Because implied assertions look for // matching SSA numbers (i.e., if a0 == b1 and b1 == c0 then a0 == c0) they don't need kill sets. if (optLocalAssertionProp) { // Perform copy assertion prop. GenTree* newTree = optCopyAssertionProp(curAssertion, tree, stmt DEBUGARG(assertionIndex)); if (newTree != nullptr) { return newTree; } } continue; } // There are no constant assertions for structs. // if (varTypeIsStruct(tree)) { continue; } // Constant prop. // // The case where the tree type could be different than the LclVar type is caused by // gtFoldExpr, specifically the case of a cast, where the fold operation changes the type of the LclVar // node. In such a case is not safe to perform the substitution since later on the JIT will assert mismatching // types between trees. const unsigned lclNum = tree->GetLclNum(); if (curAssertion->op1.lcl.lclNum == lclNum) { LclVarDsc* const lclDsc = lvaGetDesc(lclNum); // Verify types match if (tree->TypeGet() == lclDsc->lvType) { // If local assertion prop, just perform constant prop. if (optLocalAssertionProp) { return optConstantAssertionProp(curAssertion, tree, stmt DEBUGARG(assertionIndex)); } // If global assertion, perform constant propagation only if the VN's match. if (curAssertion->op1.vn == vnStore->VNConservativeNormalValue(tree->gtVNPair)) { return optConstantAssertionProp(curAssertion, tree, stmt DEBUGARG(assertionIndex)); } } } } return nullptr; } //------------------------------------------------------------------------ // optAssertionProp_Asg: Try and optimize an assignment via assertions. // // Propagates ZEROOBJ for the RHS. // // Arguments: // assertions - set of live assertions // asg - the store to optimize // stmt - statement containing "asg" // // Returns: // Updated "asg", or "nullptr" // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optAssertionProp_Asg(ASSERT_VALARG_TP assertions, GenTreeOp* asg, Statement* stmt) { GenTree* rhs = asg->gtGetOp2(); if (asg->OperIsCopyBlkOp() && varTypeIsStruct(rhs)) { if (optZeroObjAssertionProp(rhs, assertions)) { return optAssertionProp_Update(asg, asg, stmt); } } return nullptr; } //------------------------------------------------------------------------ // optAssertionProp_Return: Try and optimize a GT_RETURN via assertions. // // Propagates ZEROOBJ for the return value. // // Arguments: // assertions - set of live assertions // ret - the return node to optimize // stmt - statement containing "ret" // // Returns: // Updated "ret", or "nullptr" // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optAssertionProp_Return(ASSERT_VALARG_TP assertions, GenTreeUnOp* ret, Statement* stmt) { GenTree* retValue = ret->gtGetOp1(); // Only propagate zeroes that lowering can deal with. if (!ret->TypeIs(TYP_VOID) && varTypeIsStruct(retValue) && !varTypeIsStruct(info.compRetNativeType)) { if (optZeroObjAssertionProp(retValue, assertions)) { return optAssertionProp_Update(ret, ret, stmt); } } return nullptr; } /***************************************************************************** * * Given a set of "assertions" to search, find an assertion that matches * op1Kind and lclNum, op2Kind and the constant value and is either equal or * not equal assertion. */ AssertionIndex Compiler::optLocalAssertionIsEqualOrNotEqual( optOp1Kind op1Kind, unsigned lclNum, optOp2Kind op2Kind, ssize_t cnsVal, ASSERT_VALARG_TP assertions) { noway_assert((op1Kind == O1K_LCLVAR) || (op1Kind == O1K_EXACT_TYPE) || (op1Kind == O1K_SUBTYPE)); noway_assert((op2Kind == O2K_CONST_INT) || (op2Kind == O2K_IND_CNS_INT) || (op2Kind == O2K_ZEROOBJ)); if (!optLocalAssertionProp && BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } for (AssertionIndex index = 1; index <= optAssertionCount; ++index) { AssertionDsc* curAssertion = optGetAssertion(index); if (optLocalAssertionProp || BitVecOps::IsMember(apTraits, assertions, index - 1)) { if ((curAssertion->assertionKind != OAK_EQUAL) && (curAssertion->assertionKind != OAK_NOT_EQUAL)) { continue; } if ((curAssertion->op1.kind == op1Kind) && (curAssertion->op1.lcl.lclNum == lclNum) && (curAssertion->op2.kind == op2Kind)) { bool constantIsEqual = (curAssertion->op2.u1.iconVal == cnsVal); bool assertionIsEqual = (curAssertion->assertionKind == OAK_EQUAL); if (constantIsEqual || assertionIsEqual) { return index; } } } } return NO_ASSERTION_INDEX; } //------------------------------------------------------------------------ // optGlobalAssertionIsEqualOrNotEqual: Look for an assertion in the specified // set that is one of op1 == op1, op1 != op2, or *op1 == op2, // where equality is based on value numbers. // // Arguments: // assertions: bit vector describing set of assertions // op1, op2: the treen nodes in question // // Returns: // Index of first matching assertion, or NO_ASSERTION_INDEX if no // assertions in the set are matches. // // Notes: // Assertions based on *op1 are the result of exact type tests and are // only returned when op1 is a local var with ref type and the assertion // is an exact type equality. // AssertionIndex Compiler::optGlobalAssertionIsEqualOrNotEqual(ASSERT_VALARG_TP assertions, GenTree* op1, GenTree* op2) { if (BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if ((curAssertion->assertionKind != OAK_EQUAL && curAssertion->assertionKind != OAK_NOT_EQUAL)) { continue; } if ((curAssertion->op1.vn == vnStore->VNConservativeNormalValue(op1->gtVNPair)) && (curAssertion->op2.vn == vnStore->VNConservativeNormalValue(op2->gtVNPair))) { return assertionIndex; } // Look for matching exact type assertions based on vtable accesses if ((curAssertion->assertionKind == OAK_EQUAL) && (curAssertion->op1.kind == O1K_EXACT_TYPE) && op1->OperIs(GT_IND)) { GenTree* indirAddr = op1->AsIndir()->Addr(); if (indirAddr->OperIs(GT_LCL_VAR) && (indirAddr->TypeGet() == TYP_REF)) { // op1 is accessing vtable of a ref type local var if ((curAssertion->op1.vn == vnStore->VNConservativeNormalValue(indirAddr->gtVNPair)) && (curAssertion->op2.vn == vnStore->VNConservativeNormalValue(op2->gtVNPair))) { return assertionIndex; } } } } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Given a set of "assertions" to search for, find an assertion that is either * op == 0 or op != 0 * */ AssertionIndex Compiler::optGlobalAssertionIsEqualOrNotEqualZero(ASSERT_VALARG_TP assertions, GenTree* op1) { if (BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if ((curAssertion->assertionKind != OAK_EQUAL && curAssertion->assertionKind != OAK_NOT_EQUAL)) { continue; } if ((curAssertion->op1.vn == vnStore->VNConservativeNormalValue(op1->gtVNPair)) && (curAssertion->op2.vn == vnStore->VNZeroForType(op1->TypeGet()))) { return assertionIndex; } } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Given a tree consisting of a RelOp and a set of available assertions * we try to propagate an assertion and modify the RelOp tree if we can. * We pass in the root of the tree via 'stmt', for local copy prop 'stmt' will be nullptr * Returns the modified tree, or nullptr if no assertion prop took place */ GenTree* Compiler::optAssertionProp_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { assert(tree->OperIsCompare()); if (!optLocalAssertionProp) { // If global assertion prop then use value numbering. return optAssertionPropGlobal_RelOp(assertions, tree, stmt); } // // Currently only GT_EQ or GT_NE are supported Relops for local AssertionProp // if ((tree->gtOper != GT_EQ) && (tree->gtOper != GT_NE)) { return nullptr; } // If local assertion prop then use variable based prop. return optAssertionPropLocal_RelOp(assertions, tree, stmt); } //------------------------------------------------------------------------ // optAssertionProp: try and optimize a relop via assertion propagation // // Arguments: // assertions - set of live assertions // tree - tree to possibly optimize // stmt - statement containing the tree // // Returns: // The modified tree, or nullptr if no assertion prop took place. // GenTree* Compiler::optAssertionPropGlobal_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { GenTree* newTree = tree; GenTree* op1 = tree->AsOp()->gtOp1; GenTree* op2 = tree->AsOp()->gtOp2; // Look for assertions of the form (tree EQ/NE 0) AssertionIndex index = optGlobalAssertionIsEqualOrNotEqualZero(assertions, tree); if (index != NO_ASSERTION_INDEX) { // We know that this relop is either 0 or != 0 (1) AssertionDsc* curAssertion = optGetAssertion(index); #ifdef DEBUG if (verbose) { printf("\nVN relop based constant assertion prop in " FMT_BB ":\n", compCurBB->bbNum); printf("Assertion index=#%02u: ", index); printTreeID(tree); printf(" %s 0\n", (curAssertion->assertionKind == OAK_EQUAL) ? "==" : "!="); } #endif // Bail out if tree is not side effect free. if ((tree->gtFlags & GTF_SIDE_EFFECT) != 0) { JITDUMP("sorry, blocked by side effects\n"); return nullptr; } if (curAssertion->assertionKind == OAK_EQUAL) { tree->BashToConst(0); } else { tree->BashToConst(1); } newTree = fgMorphTree(tree); DISPTREE(newTree); return optAssertionProp_Update(newTree, tree, stmt); } // Else check if we have an equality check involving a local or an indir if (!tree->OperIs(GT_EQ, GT_NE)) { return nullptr; } // Bail out if tree is not side effect free. if ((tree->gtFlags & GTF_SIDE_EFFECT) != 0) { return nullptr; } if (!op1->OperIs(GT_LCL_VAR, GT_IND)) { return nullptr; } // Find an equal or not equal assertion involving "op1" and "op2". index = optGlobalAssertionIsEqualOrNotEqual(assertions, op1, op2); if (index == NO_ASSERTION_INDEX) { return nullptr; } AssertionDsc* curAssertion = optGetAssertion(index); bool assertionKindIsEqual = (curAssertion->assertionKind == OAK_EQUAL); // Allow or not to reverse condition for OAK_NOT_EQUAL assertions. bool allowReverse = true; // If the assertion involves "op2" and it is a constant, then check if "op1" also has a constant value. ValueNum vnCns = vnStore->VNConservativeNormalValue(op2->gtVNPair); if (vnStore->IsVNConstant(vnCns)) { #ifdef DEBUG if (verbose) { printf("\nVN relop based constant assertion prop in " FMT_BB ":\n", compCurBB->bbNum); printf("Assertion index=#%02u: ", index); printTreeID(op1); printf(" %s ", assertionKindIsEqual ? "==" : "!="); if (genActualType(op1->TypeGet()) == TYP_INT) { printf("%d\n", vnStore->ConstantValue<int>(vnCns)); } else if (op1->TypeGet() == TYP_LONG) { printf("%I64d\n", vnStore->ConstantValue<INT64>(vnCns)); } else if (op1->TypeGet() == TYP_DOUBLE) { printf("%f\n", vnStore->ConstantValue<double>(vnCns)); } else if (op1->TypeGet() == TYP_FLOAT) { printf("%f\n", vnStore->ConstantValue<float>(vnCns)); } else if (op1->TypeGet() == TYP_REF) { // The only constant of TYP_REF that ValueNumbering supports is 'null' assert(vnStore->ConstantValue<size_t>(vnCns) == 0); printf("null\n"); } else if (op1->TypeGet() == TYP_BYREF) { printf("%d (byref)\n", static_cast<target_ssize_t>(vnStore->ConstantValue<size_t>(vnCns))); } else { printf("??unknown\n"); } gtDispTree(tree, nullptr, nullptr, true); } #endif // Change the oper to const. if (genActualType(op1->TypeGet()) == TYP_INT) { op1->BashToConst(vnStore->ConstantValue<int>(vnCns)); if (vnStore->IsVNHandle(vnCns)) { op1->gtFlags |= (vnStore->GetHandleFlags(vnCns) & GTF_ICON_HDL_MASK); } } else if (op1->TypeGet() == TYP_LONG) { op1->BashToConst(vnStore->ConstantValue<INT64>(vnCns)); if (vnStore->IsVNHandle(vnCns)) { op1->gtFlags |= (vnStore->GetHandleFlags(vnCns) & GTF_ICON_HDL_MASK); } } else if (op1->TypeGet() == TYP_DOUBLE) { double constant = vnStore->ConstantValue<double>(vnCns); op1->BashToConst(constant); // Nothing can be equal to NaN. So if IL had "op1 == NaN", then we already made op1 NaN, // which will yield a false correctly. Instead if IL had "op1 != NaN", then we already // made op1 NaN which will yield a true correctly. Note that this is irrespective of the // assertion we have made. allowReverse = (_isnan(constant) == 0); } else if (op1->TypeGet() == TYP_FLOAT) { float constant = vnStore->ConstantValue<float>(vnCns); op1->BashToConst(constant); // See comments for TYP_DOUBLE. allowReverse = (_isnan(constant) == 0); } else if (op1->TypeGet() == TYP_REF) { op1->BashToConst(0, TYP_REF); // The only constant of TYP_REF that ValueNumbering supports is 'null' noway_assert(vnStore->ConstantValue<size_t>(vnCns) == 0); } else if (op1->TypeGet() == TYP_BYREF) { op1->BashToConst(static_cast<target_ssize_t>(vnStore->ConstantValue<size_t>(vnCns)), TYP_BYREF); } else { noway_assert(!"unknown type in Global_RelOp"); } op1->gtVNPair.SetBoth(vnCns); // Preserve the ValueNumPair, as BashToConst will clear it. // set foldResult to either 0 or 1 bool foldResult = assertionKindIsEqual; if (tree->gtOper == GT_NE) { foldResult = !foldResult; } // Set the value number on the relop to 1 (true) or 0 (false) if (foldResult) { tree->gtVNPair.SetBoth(vnStore->VNOneForType(TYP_INT)); } else { tree->gtVNPair.SetBoth(vnStore->VNZeroForType(TYP_INT)); } } // If the assertion involves "op2" and "op1" is also a local var, then just morph the tree. else if (op2->gtOper == GT_LCL_VAR) { #ifdef DEBUG if (verbose) { printf("\nVN relop based copy assertion prop in " FMT_BB ":\n", compCurBB->bbNum); printf("Assertion index=#%02u: V%02d.%02d %s V%02d.%02d\n", index, op1->AsLclVar()->GetLclNum(), op1->AsLclVar()->GetSsaNum(), (curAssertion->assertionKind == OAK_EQUAL) ? "==" : "!=", op2->AsLclVar()->GetLclNum(), op2->AsLclVar()->GetSsaNum()); gtDispTree(tree, nullptr, nullptr, true); } #endif // If floating point, don't just substitute op1 with op2, this won't work if // op2 is NaN. Just turn it into a "true" or "false" yielding expression. if (op1->TypeIs(TYP_FLOAT, TYP_DOUBLE)) { // Note we can't trust the OAK_EQUAL as the value could end up being a NaN // violating the assertion. However, we create OAK_EQUAL assertions for floating // point only on JTrue nodes, so if the condition held earlier, it will hold // now. We don't create OAK_EQUAL assertion on floating point from GT_ASG // because we depend on value num which would constant prop the NaN. op1->BashToConst(0.0, op1->TypeGet()); op2->BashToConst(0.0, op2->TypeGet()); } // Change the op1 LclVar to the op2 LclVar else { noway_assert(varTypeIsIntegralOrI(op1->TypeGet())); op1->AsLclVarCommon()->SetLclNum(op2->AsLclVarCommon()->GetLclNum()); op1->AsLclVarCommon()->SetSsaNum(op2->AsLclVarCommon()->GetSsaNum()); } } else { return nullptr; } // Finally reverse the condition, if we have a not equal assertion. if (allowReverse && curAssertion->assertionKind == OAK_NOT_EQUAL) { gtReverseCond(tree); } newTree = fgMorphTree(tree); #ifdef DEBUG if (verbose) { gtDispTree(newTree, nullptr, nullptr, true); } #endif return optAssertionProp_Update(newTree, tree, stmt); } /************************************************************************************* * * Given the set of "assertions" to look up a relop assertion about the relop "tree", * perform local variable name based relop assertion propagation on the tree. * */ GenTree* Compiler::optAssertionPropLocal_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { assert(tree->OperGet() == GT_EQ || tree->OperGet() == GT_NE); GenTree* op1 = tree->AsOp()->gtOp1; GenTree* op2 = tree->AsOp()->gtOp2; // For Local AssertionProp we only can fold when op1 is a GT_LCL_VAR if (op1->gtOper != GT_LCL_VAR) { return nullptr; } // For Local AssertionProp we only can fold when op2 is a GT_CNS_INT if (op2->gtOper != GT_CNS_INT) { return nullptr; } optOp1Kind op1Kind = O1K_LCLVAR; optOp2Kind op2Kind = O2K_CONST_INT; ssize_t cnsVal = op2->AsIntCon()->gtIconVal; var_types cmpType = op1->TypeGet(); // Don't try to fold/optimize Floating Compares; there are multiple zero values. if (varTypeIsFloating(cmpType)) { return nullptr; } // Find an equal or not equal assertion about op1 var. unsigned lclNum = op1->AsLclVarCommon()->GetLclNum(); noway_assert(lclNum < lvaCount); AssertionIndex index = optLocalAssertionIsEqualOrNotEqual(op1Kind, lclNum, op2Kind, cnsVal, assertions); if (index == NO_ASSERTION_INDEX) { return nullptr; } AssertionDsc* curAssertion = optGetAssertion(index); bool assertionKindIsEqual = (curAssertion->assertionKind == OAK_EQUAL); bool constantIsEqual = false; if (genTypeSize(cmpType) == TARGET_POINTER_SIZE) { constantIsEqual = (curAssertion->op2.u1.iconVal == cnsVal); } #ifdef TARGET_64BIT else if (genTypeSize(cmpType) == sizeof(INT32)) { // Compare the low 32-bits only constantIsEqual = (((INT32)curAssertion->op2.u1.iconVal) == ((INT32)cnsVal)); } #endif else { // We currently don't fold/optimize when the GT_LCL_VAR has been cast to a small type return nullptr; } noway_assert(constantIsEqual || assertionKindIsEqual); #ifdef DEBUG if (verbose) { printf("\nAssertion prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); gtDispTree(tree, nullptr, nullptr, true); } #endif // Return either CNS_INT 0 or CNS_INT 1. bool foldResult = (constantIsEqual == assertionKindIsEqual); if (tree->gtOper == GT_NE) { foldResult = !foldResult; } op2->AsIntCon()->gtIconVal = foldResult; op2->gtType = TYP_INT; return optAssertionProp_Update(op2, tree, stmt); } //------------------------------------------------------------------------ // optAssertionProp_Cast: Propagate assertion for a cast, possibly removing it. // // The function use "optAssertionIsSubrange" to find an assertion which claims the // cast's operand (only locals are supported) is a subrange of the "input" range // for the cast, as computed by "IntegralRange::ForCastInput", and, if such // assertion is found, act on it - either remove the cast if it is not changing // representation, or try to remove the GTF_OVERFLOW flag from it. // // Arguments: // assertions - the set of live assertions // cast - the cast for which to propagate the assertions // stmt - statement "cast" is a part of, "nullptr" for local prop // // Return Value: // The, possibly modified, cast tree or "nullptr" if no propagation took place. // GenTree* Compiler::optAssertionProp_Cast(ASSERT_VALARG_TP assertions, GenTreeCast* cast, Statement* stmt) { GenTree* op1 = cast->CastOp(); // Bail if we have a cast involving floating point or GC types. if (!varTypeIsIntegral(cast) || !varTypeIsIntegral(op1)) { return nullptr; } // Skip over a GT_COMMA node(s), if necessary to get to the lcl. GenTree* lcl = op1->gtEffectiveVal(); // If we don't have a cast of a LCL_VAR then bail. if (!lcl->OperIs(GT_LCL_VAR)) { return nullptr; } IntegralRange range = IntegralRange::ForCastInput(cast); AssertionIndex index = optAssertionIsSubrange(lcl, range, assertions); if (index != NO_ASSERTION_INDEX) { LclVarDsc* varDsc = lvaGetDesc(lcl->AsLclVarCommon()); // Representation-changing casts cannot be removed. if ((genActualType(cast) != genActualType(lcl))) { // Can we just remove the GTF_OVERFLOW flag? if (!cast->gtOverflow()) { return nullptr; } #ifdef DEBUG if (verbose) { printf("\nSubrange prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); DISPNODE(cast); } #endif cast->ClearOverflow(); return optAssertionProp_Update(cast, cast, stmt); } // We might need to retype a "normalize on load" local back to its original small type // so that codegen recognizes it needs to use narrow loads if the local ends up in memory. if (varDsc->lvNormalizeOnLoad()) { // The Jit is known to play somewhat loose with small types, so let's restrict this code // to the pattern we know is "safe and sound", i. e. CAST(type <- LCL_VAR(int, V00 type)). if ((varDsc->TypeGet() != cast->CastToType()) || !lcl->TypeIs(TYP_INT)) { return nullptr; } op1->ChangeType(varDsc->TypeGet()); } #ifdef DEBUG if (verbose) { printf("\nSubrange prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); DISPNODE(cast); } #endif return optAssertionProp_Update(op1, cast, stmt); } return nullptr; } /***************************************************************************** * * Given a tree with an array bounds check node, eliminate it because it was * checked already in the program. */ GenTree* Compiler::optAssertionProp_Comma(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { // Remove the bounds check as part of the GT_COMMA node since we need parent pointer to remove nodes. // When processing visits the bounds check, it sets the throw kind to None if the check is redundant. if (tree->gtGetOp1()->OperIs(GT_BOUNDS_CHECK) && ((tree->gtGetOp1()->gtFlags & GTF_CHK_INDEX_INBND) != 0)) { optRemoveCommaBasedRangeCheck(tree, stmt); return optAssertionProp_Update(tree, tree, stmt); } return nullptr; } //------------------------------------------------------------------------ // optAssertionProp_Ind: see if we can prove the indirection can't cause // and exception. // // Arguments: // assertions - set of live assertions // tree - tree to possibly optimize // stmt - statement containing the tree // // Returns: // The modified tree, or nullptr if no assertion prop took place. // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optAssertionProp_Ind(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { assert(tree->OperIsIndir()); if (!(tree->gtFlags & GTF_EXCEPT)) { return nullptr; } // Check for add of a constant. GenTree* op1 = tree->AsIndir()->Addr(); if ((op1->gtOper == GT_ADD) && (op1->AsOp()->gtOp2->gtOper == GT_CNS_INT)) { op1 = op1->AsOp()->gtOp1; } if (op1->gtOper != GT_LCL_VAR) { return nullptr; } #ifdef DEBUG bool vnBased = false; AssertionIndex index = NO_ASSERTION_INDEX; #endif if (optAssertionIsNonNull(op1, assertions DEBUGARG(&vnBased) DEBUGARG(&index))) { #ifdef DEBUG if (verbose) { (vnBased) ? printf("\nVN based non-null prop in " FMT_BB ":\n", compCurBB->bbNum) : printf("\nNon-null prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); gtDispTree(tree, nullptr, nullptr, true); } #endif tree->gtFlags &= ~GTF_EXCEPT; tree->gtFlags |= GTF_IND_NONFAULTING; // Set this flag to prevent reordering tree->gtFlags |= GTF_ORDER_SIDEEFF; return optAssertionProp_Update(tree, tree, stmt); } return nullptr; } //------------------------------------------------------------------------ // optAssertionIsNonNull: see if we can prove a tree's value will be non-null // based on assertions // // Arguments: // op - tree to check // assertions - set of live assertions // pVnBased - [out] set to true if value numbers were used // pIndex - [out] the assertion used in the proof // // Returns: // true if the tree's value will be non-null // // Notes: // Sets "pVnBased" if the assertion is value number based. If no matching // assertions are found from the table, then returns "NO_ASSERTION_INDEX." // // If both VN and assertion table yield a matching assertion, "pVnBased" // is only set and the return value is "NO_ASSERTION_INDEX." // bool Compiler::optAssertionIsNonNull(GenTree* op, ASSERT_VALARG_TP assertions DEBUGARG(bool* pVnBased) DEBUGARG(AssertionIndex* pIndex)) { bool vnBased = (!optLocalAssertionProp && vnStore->IsKnownNonNull(op->gtVNPair.GetConservative())); #ifdef DEBUG *pVnBased = vnBased; #endif if (vnBased) { #ifdef DEBUG *pIndex = NO_ASSERTION_INDEX; #endif return true; } AssertionIndex index = optAssertionIsNonNullInternal(op, assertions DEBUGARG(pVnBased)); #ifdef DEBUG *pIndex = index; #endif return index != NO_ASSERTION_INDEX; } //------------------------------------------------------------------------ // optAssertionIsNonNullInternal: see if we can prove a tree's value will // be non-null based on assertions // // Arguments: // op - tree to check // assertions - set of live assertions // pVnBased - [out] set to true if value numbers were used // // Returns: // index of assertion, or NO_ASSERTION_INDEX // AssertionIndex Compiler::optAssertionIsNonNullInternal(GenTree* op, ASSERT_VALARG_TP assertions DEBUGARG(bool* pVnBased)) { #ifdef DEBUG // Initialize the out param // *pVnBased = false; #endif // If local assertion prop use lcl comparison, else use VN comparison. if (!optLocalAssertionProp) { if (BitVecOps::MayBeUninit(assertions) || BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } // Look at both the top-level vn, and // the vn we get by stripping off any constant adds. // ValueNum vn = vnStore->VNConservativeNormalValue(op->gtVNPair); ValueNum vnBase = vn; VNFuncApp funcAttr; while (vnStore->GetVNFunc(vnBase, &funcAttr) && (funcAttr.m_func == (VNFunc)GT_ADD)) { if (vnStore->IsVNConstant(funcAttr.m_args[1]) && varTypeIsIntegral(vnStore->TypeOfVN(funcAttr.m_args[1]))) { vnBase = funcAttr.m_args[0]; } else if (vnStore->IsVNConstant(funcAttr.m_args[0]) && varTypeIsIntegral(vnStore->TypeOfVN(funcAttr.m_args[0]))) { vnBase = funcAttr.m_args[1]; } else { break; } } // Check each assertion to find if we have a vn != null assertion. // BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if (curAssertion->assertionKind != OAK_NOT_EQUAL) { continue; } if (curAssertion->op2.vn != ValueNumStore::VNForNull()) { continue; } if ((curAssertion->op1.vn != vn) && (curAssertion->op1.vn != vnBase)) { continue; } #ifdef DEBUG *pVnBased = true; #endif return assertionIndex; } } else { unsigned lclNum = op->AsLclVarCommon()->GetLclNum(); // Check each assertion to find if we have a variable == or != null assertion. for (AssertionIndex index = 1; index <= optAssertionCount; index++) { AssertionDsc* curAssertion = optGetAssertion(index); if ((curAssertion->assertionKind == OAK_NOT_EQUAL) && // kind (curAssertion->op1.kind == O1K_LCLVAR) && // op1 (curAssertion->op2.kind == O2K_CONST_INT) && // op2 (curAssertion->op1.lcl.lclNum == lclNum) && (curAssertion->op2.u1.iconVal == 0)) { return index; } } } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Given a tree consisting of a call and a set of available assertions, we * try to propagate a non-null assertion and modify the Call tree if we can. * Returns the modified tree, or nullptr if no assertion prop took place. * */ GenTree* Compiler::optNonNullAssertionProp_Call(ASSERT_VALARG_TP assertions, GenTreeCall* call) { if ((call->gtFlags & GTF_CALL_NULLCHECK) == 0) { return nullptr; } GenTree* op1 = gtGetThisArg(call); noway_assert(op1 != nullptr); if (op1->gtOper != GT_LCL_VAR) { return nullptr; } #ifdef DEBUG bool vnBased = false; AssertionIndex index = NO_ASSERTION_INDEX; #endif if (optAssertionIsNonNull(op1, assertions DEBUGARG(&vnBased) DEBUGARG(&index))) { #ifdef DEBUG if (verbose) { (vnBased) ? printf("\nVN based non-null prop in " FMT_BB ":\n", compCurBB->bbNum) : printf("\nNon-null prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); gtDispTree(call, nullptr, nullptr, true); } #endif call->gtFlags &= ~GTF_CALL_NULLCHECK; call->gtFlags &= ~GTF_EXCEPT; noway_assert(call->gtFlags & GTF_SIDE_EFFECT); return call; } return nullptr; } /***************************************************************************** * * Given a tree consisting of a call and a set of available assertions, we * try to propagate an assertion and modify the Call tree if we can. Our * current modifications are limited to removing the nullptrCHECK flag from * the call. * We pass in the root of the tree via 'stmt', for local copy prop 'stmt' * will be nullptr. Returns the modified tree, or nullptr if no assertion prop * took place. * */ GenTree* Compiler::optAssertionProp_Call(ASSERT_VALARG_TP assertions, GenTreeCall* call, Statement* stmt) { if (optNonNullAssertionProp_Call(assertions, call)) { return optAssertionProp_Update(call, call, stmt); } else if (!optLocalAssertionProp && (call->gtCallType == CT_HELPER)) { if (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFINTERFACE) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFARRAY) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFCLASS) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFANY) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTINTERFACE) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTARRAY) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTCLASS) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTANY) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTCLASS_SPECIAL)) { GenTree* arg1 = gtArgEntryByArgNum(call, 1)->GetNode(); if (arg1->gtOper != GT_LCL_VAR) { return nullptr; } GenTree* arg2 = gtArgEntryByArgNum(call, 0)->GetNode(); unsigned index = optAssertionIsSubtype(arg1, arg2, assertions); if (index != NO_ASSERTION_INDEX) { #ifdef DEBUG if (verbose) { printf("\nDid VN based subtype prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); gtDispTree(call, nullptr, nullptr, true); } #endif GenTree* list = nullptr; gtExtractSideEffList(call, &list, GTF_SIDE_EFFECT, true); if (list != nullptr) { arg1 = gtNewOperNode(GT_COMMA, call->TypeGet(), list, arg1); fgSetTreeSeq(arg1); } return optAssertionProp_Update(arg1, call, stmt); } } } return nullptr; } /***************************************************************************** * * Given a tree with a bounds check, remove it if it has already been checked in the program flow. */ GenTree* Compiler::optAssertionProp_BndsChk(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { if (optLocalAssertionProp) { return nullptr; } assert(tree->OperIs(GT_BOUNDS_CHECK)); #ifdef FEATURE_ENABLE_NO_RANGE_CHECKS if (JitConfig.JitNoRangeChks()) { #ifdef DEBUG if (verbose) { printf("\nFlagging check redundant due to JitNoRangeChks in " FMT_BB ":\n", compCurBB->bbNum); gtDispTree(tree, nullptr, nullptr, true); } #endif // DEBUG tree->gtFlags |= GTF_CHK_INDEX_INBND; return nullptr; } #endif // FEATURE_ENABLE_NO_RANGE_CHECKS BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } // If it is not a nothrow assertion, skip. AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if (!curAssertion->IsBoundsCheckNoThrow()) { continue; } GenTreeBoundsChk* arrBndsChk = tree->AsBoundsChk(); // Set 'isRedundant' to true if we can determine that 'arrBndsChk' can be // classified as a redundant bounds check using 'curAssertion' bool isRedundant = false; #ifdef DEBUG const char* dbgMsg = "Not Set"; #endif // Do we have a previous range check involving the same 'vnLen' upper bound? if (curAssertion->op1.bnd.vnLen == vnStore->VNConservativeNormalValue(arrBndsChk->GetArrayLength()->gtVNPair)) { ValueNum vnCurIdx = vnStore->VNConservativeNormalValue(arrBndsChk->GetIndex()->gtVNPair); // Do we have the exact same lower bound 'vnIdx'? // a[i] followed by a[i] if (curAssertion->op1.bnd.vnIdx == vnCurIdx) { isRedundant = true; #ifdef DEBUG dbgMsg = "a[i] followed by a[i]"; #endif } // Are we using zero as the index? // It can always be considered as redundant with any previous value // a[*] followed by a[0] else if (vnCurIdx == vnStore->VNZeroForType(arrBndsChk->GetIndex()->TypeGet())) { isRedundant = true; #ifdef DEBUG dbgMsg = "a[*] followed by a[0]"; #endif } // Do we have two constant indexes? else if (vnStore->IsVNConstant(curAssertion->op1.bnd.vnIdx) && vnStore->IsVNConstant(vnCurIdx)) { // Make sure the types match. var_types type1 = vnStore->TypeOfVN(curAssertion->op1.bnd.vnIdx); var_types type2 = vnStore->TypeOfVN(vnCurIdx); if (type1 == type2 && type1 == TYP_INT) { int index1 = vnStore->ConstantValue<int>(curAssertion->op1.bnd.vnIdx); int index2 = vnStore->ConstantValue<int>(vnCurIdx); // the case where index1 == index2 should have been handled above assert(index1 != index2); // It can always be considered as redundant with any previous higher constant value // a[K1] followed by a[K2], with K2 >= 0 and K1 >= K2 if (index2 >= 0 && index1 >= index2) { isRedundant = true; #ifdef DEBUG dbgMsg = "a[K1] followed by a[K2], with K2 >= 0 and K1 >= K2"; #endif } } } // Extend this to remove additional redundant bounds checks: // i.e. a[i+1] followed by a[i] by using the VN(i+1) >= VN(i) // a[i] followed by a[j] when j is known to be >= i // a[i] followed by a[5] when i is known to be >= 5 } if (!isRedundant) { continue; } #ifdef DEBUG if (verbose) { printf("\nVN based redundant (%s) bounds check assertion prop for index #%02u in " FMT_BB ":\n", dbgMsg, assertionIndex, compCurBB->bbNum); gtDispTree(tree, nullptr, nullptr, true); } #endif if (arrBndsChk == stmt->GetRootNode()) { // We have a top-level bounds check node. // This can happen when trees are broken up due to inlining. // optRemoveStandaloneRangeCheck will return the modified tree (side effects or a no-op). GenTree* newTree = optRemoveStandaloneRangeCheck(arrBndsChk, stmt); return optAssertionProp_Update(newTree, arrBndsChk, stmt); } // Defer actually removing the tree until processing reaches its parent comma, since // optRemoveCommaBasedRangeCheck needs to rewrite the whole comma tree. arrBndsChk->gtFlags |= GTF_CHK_INDEX_INBND; return nullptr; } return nullptr; } /***************************************************************************** * * Called when we have a successfully performed an assertion prop. We have * the newTree in hand. This method will replace the existing tree in the * stmt with the newTree. * */ GenTree* Compiler::optAssertionProp_Update(GenTree* newTree, GenTree* tree, Statement* stmt) { assert(newTree != nullptr); assert(tree != nullptr); if (stmt == nullptr) { noway_assert(optLocalAssertionProp); } else { noway_assert(!optLocalAssertionProp); // If newTree == tree then we modified the tree in-place otherwise we have to // locate our parent node and update it so that it points to newTree. if (newTree != tree) { FindLinkData linkData = gtFindLink(stmt, tree); GenTree** useEdge = linkData.result; GenTree* parent = linkData.parent; noway_assert(useEdge != nullptr); if (parent != nullptr) { parent->ReplaceOperand(useEdge, newTree); } else { // If there's no parent, the tree being replaced is the root of the // statement. assert((stmt->GetRootNode() == tree) && (stmt->GetRootNodePointer() == useEdge)); stmt->SetRootNode(newTree); } // We only need to ensure that the gtNext field is set as it is used to traverse // to the next node in the tree. We will re-morph this entire statement in // optAssertionPropMain(). It will reset the gtPrev and gtNext links for all nodes. newTree->gtNext = tree->gtNext; // Old tree should not be referenced anymore. DEBUG_DESTROY_NODE(tree); } } // Record that we propagated the assertion. optAssertionPropagated = true; optAssertionPropagatedCurrentStmt = true; return newTree; } //------------------------------------------------------------------------ // optAssertionProp: try and optimize a tree via assertion propagation // // Arguments: // assertions - set of live assertions // tree - tree to possibly optimize // stmt - statement containing the tree // block - block containing the statement // // Returns: // The modified tree, or nullptr if no assertion prop took place. // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optAssertionProp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt, BasicBlock* block) { switch (tree->gtOper) { case GT_LCL_VAR: return optAssertionProp_LclVar(assertions, tree->AsLclVarCommon(), stmt); case GT_ASG: return optAssertionProp_Asg(assertions, tree->AsOp(), stmt); case GT_RETURN: return optAssertionProp_Return(assertions, tree->AsUnOp(), stmt); case GT_OBJ: case GT_BLK: case GT_IND: case GT_NULLCHECK: case GT_STORE_DYN_BLK: return optAssertionProp_Ind(assertions, tree, stmt); case GT_BOUNDS_CHECK: return optAssertionProp_BndsChk(assertions, tree, stmt); case GT_COMMA: return optAssertionProp_Comma(assertions, tree, stmt); case GT_CAST: return optAssertionProp_Cast(assertions, tree->AsCast(), stmt); case GT_CALL: return optAssertionProp_Call(assertions, tree->AsCall(), stmt); case GT_EQ: case GT_NE: case GT_LT: case GT_LE: case GT_GT: case GT_GE: return optAssertionProp_RelOp(assertions, tree, stmt); case GT_JTRUE: if (block != nullptr) { return optVNConstantPropOnJTrue(block, tree); } return nullptr; default: return nullptr; } } //------------------------------------------------------------------------ // optImpliedAssertions: Given an assertion this method computes the set // of implied assertions that are also true. // // Arguments: // assertionIndex : The id of the assertion. // activeAssertions : The assertions that are already true at this point. // This method will add the discovered implied assertions // to this set. // void Compiler::optImpliedAssertions(AssertionIndex assertionIndex, ASSERT_TP& activeAssertions) { noway_assert(!optLocalAssertionProp); noway_assert(assertionIndex != 0); noway_assert(assertionIndex <= optAssertionCount); AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if (!BitVecOps::IsEmpty(apTraits, activeAssertions)) { const ASSERT_TP mappedAssertions = optGetVnMappedAssertions(curAssertion->op1.vn); if (mappedAssertions == nullptr) { return; } ASSERT_TP chkAssertions = BitVecOps::MakeCopy(apTraits, mappedAssertions); if (curAssertion->op2.kind == O2K_LCLVAR_COPY) { const ASSERT_TP op2Assertions = optGetVnMappedAssertions(curAssertion->op2.vn); if (op2Assertions != nullptr) { BitVecOps::UnionD(apTraits, chkAssertions, op2Assertions); } } BitVecOps::IntersectionD(apTraits, chkAssertions, activeAssertions); if (BitVecOps::IsEmpty(apTraits, chkAssertions)) { return; } // Check each assertion in chkAssertions to see if it can be applied to curAssertion BitVecOps::Iter chkIter(apTraits, chkAssertions); unsigned chkIndex = 0; while (chkIter.NextElem(&chkIndex)) { AssertionIndex chkAssertionIndex = GetAssertionIndex(chkIndex); if (chkAssertionIndex > optAssertionCount) { break; } if (chkAssertionIndex == assertionIndex) { continue; } // Determine which one is a copy assertion and use the other to check for implied assertions. AssertionDsc* iterAssertion = optGetAssertion(chkAssertionIndex); if (curAssertion->IsCopyAssertion()) { optImpliedByCopyAssertion(curAssertion, iterAssertion, activeAssertions); } else if (iterAssertion->IsCopyAssertion()) { optImpliedByCopyAssertion(iterAssertion, curAssertion, activeAssertions); } } } // Is curAssertion a constant assignment of a 32-bit integer? // (i.e GT_LVL_VAR X == GT_CNS_INT) else if ((curAssertion->assertionKind == OAK_EQUAL) && (curAssertion->op1.kind == O1K_LCLVAR) && (curAssertion->op2.kind == O2K_CONST_INT)) { optImpliedByConstAssertion(curAssertion, activeAssertions); } } /***************************************************************************** * * Given a set of active assertions this method computes the set * of non-Null implied assertions that are also true */ void Compiler::optImpliedByTypeOfAssertions(ASSERT_TP& activeAssertions) { if (BitVecOps::IsEmpty(apTraits, activeAssertions)) { return; } // Check each assertion in activeAssertions to see if it can be applied to constAssertion BitVecOps::Iter chkIter(apTraits, activeAssertions); unsigned chkIndex = 0; while (chkIter.NextElem(&chkIndex)) { AssertionIndex chkAssertionIndex = GetAssertionIndex(chkIndex); if (chkAssertionIndex > optAssertionCount) { break; } // chkAssertion must be Type/Subtype is equal assertion AssertionDsc* chkAssertion = optGetAssertion(chkAssertionIndex); if ((chkAssertion->op1.kind != O1K_SUBTYPE && chkAssertion->op1.kind != O1K_EXACT_TYPE) || (chkAssertion->assertionKind != OAK_EQUAL)) { continue; } // Search the assertion table for a non-null assertion on op1 that matches chkAssertion for (AssertionIndex impIndex = 1; impIndex <= optAssertionCount; impIndex++) { AssertionDsc* impAssertion = optGetAssertion(impIndex); // The impAssertion must be different from the chkAssertion if (impIndex == chkAssertionIndex) { continue; } // impAssertion must be a Non Null assertion on lclNum if ((impAssertion->assertionKind != OAK_NOT_EQUAL) || ((impAssertion->op1.kind != O1K_LCLVAR) && (impAssertion->op1.kind != O1K_VALUE_NUMBER)) || (impAssertion->op2.kind != O2K_CONST_INT) || (impAssertion->op1.vn != chkAssertion->op1.vn)) { continue; } // The bit may already be in the result set if (!BitVecOps::IsMember(apTraits, activeAssertions, impIndex - 1)) { BitVecOps::AddElemD(apTraits, activeAssertions, impIndex - 1); #ifdef DEBUG if (verbose) { printf("\nCompiler::optImpliedByTypeOfAssertions: %s Assertion #%02d, implies assertion #%02d", (chkAssertion->op1.kind == O1K_SUBTYPE) ? "Subtype" : "Exact-type", chkAssertionIndex, impIndex); } #endif } // There is at most one non-null assertion that is implied by the current chkIndex assertion break; } } } //------------------------------------------------------------------------ // optGetVnMappedAssertions: Given a value number, get the assertions // we have about the value number. // // Arguments: // vn - The given value number. // // Return Value: // The assertions we have about the value number. // ASSERT_VALRET_TP Compiler::optGetVnMappedAssertions(ValueNum vn) { ASSERT_TP set = BitVecOps::UninitVal(); if (optValueNumToAsserts->Lookup(vn, &set)) { return set; } return BitVecOps::UninitVal(); } /***************************************************************************** * * Given a const assertion this method computes the set of implied assertions * that are also true */ void Compiler::optImpliedByConstAssertion(AssertionDsc* constAssertion, ASSERT_TP& result) { noway_assert(constAssertion->assertionKind == OAK_EQUAL); noway_assert(constAssertion->op1.kind == O1K_LCLVAR); noway_assert(constAssertion->op2.kind == O2K_CONST_INT); ssize_t iconVal = constAssertion->op2.u1.iconVal; const ASSERT_TP chkAssertions = optGetVnMappedAssertions(constAssertion->op1.vn); if (chkAssertions == nullptr || BitVecOps::IsEmpty(apTraits, chkAssertions)) { return; } // Check each assertion in chkAssertions to see if it can be applied to constAssertion BitVecOps::Iter chkIter(apTraits, chkAssertions); unsigned chkIndex = 0; while (chkIter.NextElem(&chkIndex)) { AssertionIndex chkAssertionIndex = GetAssertionIndex(chkIndex); if (chkAssertionIndex > optAssertionCount) { break; } // The impAssertion must be different from the const assertion. AssertionDsc* impAssertion = optGetAssertion(chkAssertionIndex); if (impAssertion == constAssertion) { continue; } // The impAssertion must be an assertion about the same local var. if (impAssertion->op1.vn != constAssertion->op1.vn) { continue; } bool usable = false; switch (impAssertion->op2.kind) { case O2K_SUBRANGE: // Is the const assertion's constant, within implied assertion's bounds? usable = impAssertion->op2.u2.Contains(iconVal); break; case O2K_CONST_INT: // Is the const assertion's constant equal/not equal to the implied assertion? usable = ((impAssertion->assertionKind == OAK_EQUAL) && (impAssertion->op2.u1.iconVal == iconVal)) || ((impAssertion->assertionKind == OAK_NOT_EQUAL) && (impAssertion->op2.u1.iconVal != iconVal)); break; default: // leave 'usable' = false; break; } if (usable) { BitVecOps::AddElemD(apTraits, result, chkIndex); #ifdef DEBUG if (verbose) { AssertionDsc* firstAssertion = optGetAssertion(1); printf("Compiler::optImpliedByConstAssertion: const assertion #%02d implies assertion #%02d\n", (constAssertion - firstAssertion) + 1, (impAssertion - firstAssertion) + 1); } #endif } } } /***************************************************************************** * * Given a copy assertion and a dependent assertion this method computes the * set of implied assertions that are also true. * For copy assertions, exact SSA num and LCL nums should match, because * we don't have kill sets and we depend on their value num for dataflow. */ void Compiler::optImpliedByCopyAssertion(AssertionDsc* copyAssertion, AssertionDsc* depAssertion, ASSERT_TP& result) { noway_assert(copyAssertion->IsCopyAssertion()); // Get the copyAssert's lcl/ssa nums. unsigned copyAssertLclNum = BAD_VAR_NUM; unsigned copyAssertSsaNum = SsaConfig::RESERVED_SSA_NUM; // Check if copyAssertion's op1 or op2 matches the depAssertion's op1. if (depAssertion->op1.lcl.lclNum == copyAssertion->op1.lcl.lclNum) { copyAssertLclNum = copyAssertion->op2.lcl.lclNum; copyAssertSsaNum = copyAssertion->op2.lcl.ssaNum; } else if (depAssertion->op1.lcl.lclNum == copyAssertion->op2.lcl.lclNum) { copyAssertLclNum = copyAssertion->op1.lcl.lclNum; copyAssertSsaNum = copyAssertion->op1.lcl.ssaNum; } // Check if copyAssertion's op1 or op2 matches the depAssertion's op2. else if (depAssertion->op2.kind == O2K_LCLVAR_COPY) { if (depAssertion->op2.lcl.lclNum == copyAssertion->op1.lcl.lclNum) { copyAssertLclNum = copyAssertion->op2.lcl.lclNum; copyAssertSsaNum = copyAssertion->op2.lcl.ssaNum; } else if (depAssertion->op2.lcl.lclNum == copyAssertion->op2.lcl.lclNum) { copyAssertLclNum = copyAssertion->op1.lcl.lclNum; copyAssertSsaNum = copyAssertion->op1.lcl.ssaNum; } } if (copyAssertLclNum == BAD_VAR_NUM || copyAssertSsaNum == SsaConfig::RESERVED_SSA_NUM) { return; } // Get the depAssert's lcl/ssa nums. unsigned depAssertLclNum = BAD_VAR_NUM; unsigned depAssertSsaNum = SsaConfig::RESERVED_SSA_NUM; if ((depAssertion->op1.kind == O1K_LCLVAR) && (depAssertion->op2.kind == O2K_LCLVAR_COPY)) { if ((depAssertion->op1.lcl.lclNum == copyAssertion->op1.lcl.lclNum) || (depAssertion->op1.lcl.lclNum == copyAssertion->op2.lcl.lclNum)) { depAssertLclNum = depAssertion->op2.lcl.lclNum; depAssertSsaNum = depAssertion->op2.lcl.ssaNum; } else if ((depAssertion->op2.lcl.lclNum == copyAssertion->op1.lcl.lclNum) || (depAssertion->op2.lcl.lclNum == copyAssertion->op2.lcl.lclNum)) { depAssertLclNum = depAssertion->op1.lcl.lclNum; depAssertSsaNum = depAssertion->op1.lcl.ssaNum; } } if (depAssertLclNum == BAD_VAR_NUM || depAssertSsaNum == SsaConfig::RESERVED_SSA_NUM) { return; } // Is depAssertion a constant assignment of a 32-bit integer? // (i.e GT_LVL_VAR X == GT_CNS_INT) bool depIsConstAssertion = ((depAssertion->assertionKind == OAK_EQUAL) && (depAssertion->op1.kind == O1K_LCLVAR) && (depAssertion->op2.kind == O2K_CONST_INT)); // Search the assertion table for an assertion on op1 that matches depAssertion // The matching assertion is the implied assertion. for (AssertionIndex impIndex = 1; impIndex <= optAssertionCount; impIndex++) { AssertionDsc* impAssertion = optGetAssertion(impIndex); // The impAssertion must be different from the copy and dependent assertions if (impAssertion == copyAssertion || impAssertion == depAssertion) { continue; } if (!AssertionDsc::SameKind(depAssertion, impAssertion)) { continue; } bool op1MatchesCopy = (copyAssertLclNum == impAssertion->op1.lcl.lclNum) && (copyAssertSsaNum == impAssertion->op1.lcl.ssaNum); bool usable = false; switch (impAssertion->op2.kind) { case O2K_SUBRANGE: usable = op1MatchesCopy && impAssertion->op2.u2.Contains(depAssertion->op2.u2); break; case O2K_CONST_LONG: usable = op1MatchesCopy && (impAssertion->op2.lconVal == depAssertion->op2.lconVal); break; case O2K_CONST_DOUBLE: // Exact memory match because of positive and negative zero usable = op1MatchesCopy && (memcmp(&impAssertion->op2.dconVal, &depAssertion->op2.dconVal, sizeof(double)) == 0); break; case O2K_IND_CNS_INT: // This is the ngen case where we have an indirection of an address. noway_assert((impAssertion->op1.kind == O1K_EXACT_TYPE) || (impAssertion->op1.kind == O1K_SUBTYPE)); FALLTHROUGH; case O2K_CONST_INT: usable = op1MatchesCopy && (impAssertion->op2.u1.iconVal == depAssertion->op2.u1.iconVal); break; case O2K_LCLVAR_COPY: // Check if op1 of impAssertion matches copyAssertion and also op2 of impAssertion matches depAssertion. if (op1MatchesCopy && (depAssertLclNum == impAssertion->op2.lcl.lclNum && depAssertSsaNum == impAssertion->op2.lcl.ssaNum)) { usable = true; } else { // Otherwise, op2 of impAssertion should match copyAssertion and also op1 of impAssertion matches // depAssertion. usable = ((copyAssertLclNum == impAssertion->op2.lcl.lclNum && copyAssertSsaNum == impAssertion->op2.lcl.ssaNum) && (depAssertLclNum == impAssertion->op1.lcl.lclNum && depAssertSsaNum == impAssertion->op1.lcl.ssaNum)); } break; default: // leave 'usable' = false; break; } if (usable) { BitVecOps::AddElemD(apTraits, result, impIndex - 1); #ifdef DEBUG if (verbose) { AssertionDsc* firstAssertion = optGetAssertion(1); printf("\nCompiler::optImpliedByCopyAssertion: copyAssertion #%02d and depAssertion #%02d, implies " "assertion #%02d", (copyAssertion - firstAssertion) + 1, (depAssertion - firstAssertion) + 1, (impAssertion - firstAssertion) + 1); } #endif // If the depAssertion is a const assertion then any other assertions that it implies could also imply a // subrange assertion. if (depIsConstAssertion) { optImpliedByConstAssertion(impAssertion, result); } } } } #include "dataflow.h" /***************************************************************************** * * Dataflow visitor like callback so that all dataflow is in a single place * */ class AssertionPropFlowCallback { private: ASSERT_TP preMergeOut; ASSERT_TP preMergeJumpDestOut; ASSERT_TP* mJumpDestOut; ASSERT_TP* mJumpDestGen; BitVecTraits* apTraits; public: AssertionPropFlowCallback(Compiler* pCompiler, ASSERT_TP* jumpDestOut, ASSERT_TP* jumpDestGen) : preMergeOut(BitVecOps::UninitVal()) , preMergeJumpDestOut(BitVecOps::UninitVal()) , mJumpDestOut(jumpDestOut) , mJumpDestGen(jumpDestGen) , apTraits(pCompiler->apTraits) { } // At the start of the merge function of the dataflow equations, initialize premerge state (to detect change.) void StartMerge(BasicBlock* block) { if (VerboseDataflow()) { JITDUMP("StartMerge: " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("in -> ", block->bbAssertionIn, "\n"); } BitVecOps::Assign(apTraits, preMergeOut, block->bbAssertionOut); BitVecOps::Assign(apTraits, preMergeJumpDestOut, mJumpDestOut[block->bbNum]); } // During merge, perform the actual merging of the predecessor's (since this is a forward analysis) dataflow flags. void Merge(BasicBlock* block, BasicBlock* predBlock, unsigned dupCount) { ASSERT_TP pAssertionOut; if (predBlock->bbJumpKind == BBJ_COND && (predBlock->bbJumpDest == block)) { pAssertionOut = mJumpDestOut[predBlock->bbNum]; if (dupCount > 1) { // Scenario where next block and conditional block, both point to the same block. // In such case, intersect the assertions present on both the out edges of predBlock. assert(predBlock->bbNext == block); BitVecOps::IntersectionD(apTraits, pAssertionOut, predBlock->bbAssertionOut); if (VerboseDataflow()) { JITDUMP("Merge : Duplicate flow, " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("in -> ", block->bbAssertionIn, "; "); JITDUMP("pred " FMT_BB " ", predBlock->bbNum); Compiler::optDumpAssertionIndices("out1 -> ", mJumpDestOut[predBlock->bbNum], "; "); Compiler::optDumpAssertionIndices("out2 -> ", predBlock->bbAssertionOut, "\n"); } } } else { pAssertionOut = predBlock->bbAssertionOut; } if (VerboseDataflow()) { JITDUMP("Merge : " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("in -> ", block->bbAssertionIn, "; "); JITDUMP("pred " FMT_BB " ", predBlock->bbNum); Compiler::optDumpAssertionIndices("out -> ", pAssertionOut, "\n"); } BitVecOps::IntersectionD(apTraits, block->bbAssertionIn, pAssertionOut); } //------------------------------------------------------------------------ // MergeHandler: Merge assertions into the first exception handler/filter block. // // Arguments: // block - the block that is the start of a handler or filter; // firstTryBlock - the first block of the try for "block" handler; // lastTryBlock - the last block of the try for "block" handler;. // // Notes: // We can jump to the handler from any instruction in the try region. // It means we can propagate only assertions that are valid for the whole try region. void MergeHandler(BasicBlock* block, BasicBlock* firstTryBlock, BasicBlock* lastTryBlock) { if (VerboseDataflow()) { JITDUMP("Merge : " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("in -> ", block->bbAssertionIn, "; "); JITDUMP("firstTryBlock " FMT_BB " ", firstTryBlock->bbNum); Compiler::optDumpAssertionIndices("in -> ", firstTryBlock->bbAssertionIn, "; "); JITDUMP("lastTryBlock " FMT_BB " ", lastTryBlock->bbNum); Compiler::optDumpAssertionIndices("out -> ", lastTryBlock->bbAssertionOut, "\n"); } BitVecOps::IntersectionD(apTraits, block->bbAssertionIn, firstTryBlock->bbAssertionIn); BitVecOps::IntersectionD(apTraits, block->bbAssertionIn, lastTryBlock->bbAssertionOut); } // At the end of the merge store results of the dataflow equations, in a postmerge state. bool EndMerge(BasicBlock* block) { if (VerboseDataflow()) { JITDUMP("EndMerge : " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("in -> ", block->bbAssertionIn, "\n\n"); } BitVecOps::DataFlowD(apTraits, block->bbAssertionOut, block->bbAssertionGen, block->bbAssertionIn); BitVecOps::DataFlowD(apTraits, mJumpDestOut[block->bbNum], mJumpDestGen[block->bbNum], block->bbAssertionIn); bool changed = (!BitVecOps::Equal(apTraits, preMergeOut, block->bbAssertionOut) || !BitVecOps::Equal(apTraits, preMergeJumpDestOut, mJumpDestOut[block->bbNum])); if (VerboseDataflow()) { if (changed) { JITDUMP("Changed : " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("before out -> ", preMergeOut, "; "); Compiler::optDumpAssertionIndices("after out -> ", block->bbAssertionOut, ";\n "); Compiler::optDumpAssertionIndices("jumpDest before out -> ", preMergeJumpDestOut, "; "); Compiler::optDumpAssertionIndices("jumpDest after out -> ", mJumpDestOut[block->bbNum], ";\n\n"); } else { JITDUMP("Unchanged : " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("out -> ", block->bbAssertionOut, "; "); Compiler::optDumpAssertionIndices("jumpDest out -> ", mJumpDestOut[block->bbNum], "\n\n"); } } return changed; } // Can be enabled to get detailed debug output about dataflow for assertions. bool VerboseDataflow() { #if 0 return VERBOSE; #endif return false; } }; /***************************************************************************** * * Compute the assertions generated by each block. */ ASSERT_TP* Compiler::optComputeAssertionGen() { ASSERT_TP* jumpDestGen = fgAllocateTypeForEachBlk<ASSERT_TP>(); for (BasicBlock* const block : Blocks()) { ASSERT_TP valueGen = BitVecOps::MakeEmpty(apTraits); GenTree* jtrue = nullptr; // Walk the statement trees in this basic block. for (Statement* const stmt : block->Statements()) { for (GenTree* const tree : stmt->TreeList()) { if (tree->gtOper == GT_JTRUE) { // A GT_TRUE is always the last node in a tree, so we can break here assert((tree->gtNext == nullptr) && (stmt->GetNextStmt() == nullptr)); jtrue = tree; break; } if (tree->GeneratesAssertion()) { AssertionInfo info = tree->GetAssertionInfo(); optImpliedAssertions(info.GetAssertionIndex(), valueGen); BitVecOps::AddElemD(apTraits, valueGen, info.GetAssertionIndex() - 1); } } } if (jtrue != nullptr) { // Copy whatever we have accumulated into jumpDest edge's valueGen. ASSERT_TP jumpDestValueGen = BitVecOps::MakeCopy(apTraits, valueGen); if (jtrue->GeneratesAssertion()) { AssertionInfo info = jtrue->GetAssertionInfo(); AssertionIndex valueAssertionIndex; AssertionIndex jumpDestAssertionIndex; if (info.IsNextEdgeAssertion()) { valueAssertionIndex = info.GetAssertionIndex(); jumpDestAssertionIndex = optFindComplementary(info.GetAssertionIndex()); } else // is jump edge assertion { jumpDestAssertionIndex = info.GetAssertionIndex(); valueAssertionIndex = optFindComplementary(jumpDestAssertionIndex); } if (valueAssertionIndex != NO_ASSERTION_INDEX) { // Update valueGen if we have an assertion for the bbNext edge optImpliedAssertions(valueAssertionIndex, valueGen); BitVecOps::AddElemD(apTraits, valueGen, valueAssertionIndex - 1); } if (jumpDestAssertionIndex != NO_ASSERTION_INDEX) { // Update jumpDestValueGen if we have an assertion for the bbJumpDest edge optImpliedAssertions(jumpDestAssertionIndex, jumpDestValueGen); BitVecOps::AddElemD(apTraits, jumpDestValueGen, jumpDestAssertionIndex - 1); } } jumpDestGen[block->bbNum] = jumpDestValueGen; } else { jumpDestGen[block->bbNum] = BitVecOps::MakeEmpty(apTraits); } block->bbAssertionGen = valueGen; #ifdef DEBUG if (verbose) { if (block == fgFirstBB) { printf("\n"); } printf(FMT_BB " valueGen = ", block->bbNum); optPrintAssertionIndices(block->bbAssertionGen); if (block->bbJumpKind == BBJ_COND) { printf(" => " FMT_BB " valueGen = ", block->bbJumpDest->bbNum); optPrintAssertionIndices(jumpDestGen[block->bbNum]); } printf("\n"); if (block == fgLastBB) { printf("\n"); } } #endif } return jumpDestGen; } /***************************************************************************** * * Initialize the assertion data flow flags that will be propagated. */ ASSERT_TP* Compiler::optInitAssertionDataflowFlags() { ASSERT_TP* jumpDestOut = fgAllocateTypeForEachBlk<ASSERT_TP>(); // The local assertion gen phase may have created unreachable blocks. // They will never be visited in the dataflow propagation phase, so they need to // be initialized correctly. This means that instead of setting their sets to // apFull (i.e. all possible bits set), we need to set the bits only for valid // assertions (note that at this point we are not creating any new assertions). // Also note that assertion indices start from 1. ASSERT_TP apValidFull = BitVecOps::MakeEmpty(apTraits); for (int i = 1; i <= optAssertionCount; i++) { BitVecOps::AddElemD(apTraits, apValidFull, i - 1); } // Initially estimate the OUT sets to everything except killed expressions // Also set the IN sets to 1, so that we can perform the intersection. for (BasicBlock* const block : Blocks()) { block->bbAssertionIn = BitVecOps::MakeCopy(apTraits, apValidFull); block->bbAssertionGen = BitVecOps::MakeEmpty(apTraits); block->bbAssertionOut = BitVecOps::MakeCopy(apTraits, apValidFull); jumpDestOut[block->bbNum] = BitVecOps::MakeCopy(apTraits, apValidFull); } // Compute the data flow values for all tracked expressions // IN and OUT never change for the initial basic block B1 BitVecOps::ClearD(apTraits, fgFirstBB->bbAssertionIn); return jumpDestOut; } // Callback data for the VN based constant prop visitor. struct VNAssertionPropVisitorInfo { Compiler* pThis; Statement* stmt; BasicBlock* block; VNAssertionPropVisitorInfo(Compiler* pThis, BasicBlock* block, Statement* stmt) : pThis(pThis), stmt(stmt), block(block) { } }; //------------------------------------------------------------------------------ // optExtractSideEffListFromConst // Extracts side effects from a tree so it can be replaced with a comma // separated list of side effects + a const tree. // // Note: // The caller expects that the root of the tree has no side effects and it // won't be extracted. Otherwise the resulting comma tree would be bigger // than the tree before optimization. // // Arguments: // tree - The tree node with constant value to extrace side-effects from. // // Return Value: // 1. Returns the extracted side-effects from "tree" // 2. When no side-effects are present, returns null. // // GenTree* Compiler::optExtractSideEffListFromConst(GenTree* tree) { assert(vnStore->IsVNConstant(vnStore->VNConservativeNormalValue(tree->gtVNPair)) || vnStore->IsVNVectorZero(vnStore->VNConservativeNormalValue(tree->gtVNPair))); GenTree* sideEffList = nullptr; // If we have side effects, extract them. if ((tree->gtFlags & GTF_SIDE_EFFECT) != 0) { // Do a sanity check to ensure persistent side effects aren't discarded and // tell gtExtractSideEffList to ignore the root of the tree. // We are relying here on an invariant that VN will only fold non-throwing expressions. const bool ignoreExceptions = true; const bool ignoreCctors = false; // We have to check "AsCall()->HasSideEffects()" here separately because "gtNodeHasSideEffects" // also checks for side effects that arguments introduce (incosistently so, it otherwise only // checks for the side effects the node itself has). TODO-Cleanup: change it to not do that? assert(!gtNodeHasSideEffects(tree, GTF_PERSISTENT_SIDE_EFFECTS) || (tree->IsCall() && !tree->AsCall()->HasSideEffects(this, ignoreExceptions, ignoreCctors))); // Exception side effects may be ignored because the root is known to be a constant // (e.g. VN may evaluate a DIV/MOD node to a constant and the node may still // have GTF_EXCEPT set, even if it does not actually throw any exceptions). bool ignoreRoot = true; gtExtractSideEffList(tree, &sideEffList, GTF_SIDE_EFFECT, ignoreRoot); JITDUMP("Extracted side effects from a constant tree [%06u]:\n", tree->gtTreeID); DISPTREE(sideEffList); } return sideEffList; } //------------------------------------------------------------------------------ // optVNConstantPropOnJTrue // Constant propagate on the JTrue node by extracting side effects and moving // them into their own statements. The relop node is then modified to yield // true or false, so the branch can be folded. // // Arguments: // block - The block that contains the JTrue. // test - The JTrue node whose relop evaluates to 0 or non-zero value. // // Return Value: // The jmpTrue tree node that has relop of the form "0 =/!= 0". // If "tree" evaluates to "true" relop is "0 == 0". Else relop is "0 != 0". // // Description: // Special treatment for JTRUE nodes' constant propagation. This is because // for JTRUE(1) or JTRUE(0), if there are side effects they need to be put // in separate statements. This is to prevent relop's constant // propagation from doing a simple minded conversion from // (1) STMT(JTRUE(RELOP(COMMA(sideEffect, OP1), OP2)), S.T. op1 =/!= op2 to // (2) STMT(JTRUE(COMMA(sideEffect, 1/0)). // // fgFoldConditional doesn't fold (2), a side-effecting JTRUE's op1. So, let us, // here, convert (1) as two statements: STMT(sideEffect), STMT(JTRUE(1/0)), // so that the JTRUE will get folded by fgFoldConditional. // // Note: fgFoldConditional is called from other places as well, which may be // sensitive to adding new statements. Hence the change is not made directly // into fgFoldConditional. // GenTree* Compiler::optVNConstantPropOnJTrue(BasicBlock* block, GenTree* test) { GenTree* relop = test->gtGetOp1(); // VN based assertion non-null on this relop has been performed. if (!relop->OperIsCompare()) { return nullptr; } // // Make sure GTF_RELOP_JMP_USED flag is set so that we can later skip constant // prop'ing a JTRUE's relop child node for a second time in the pre-order // tree walk. // assert((relop->gtFlags & GTF_RELOP_JMP_USED) != 0); // We want to use the Normal ValueNumber when checking for constants. ValueNum vnCns = vnStore->VNConservativeNormalValue(relop->gtVNPair); ValueNum vnLib = vnStore->VNLiberalNormalValue(relop->gtVNPair); if (!vnStore->IsVNConstant(vnCns)) { return nullptr; } // Prepare the tree for replacement so any side effects can be extracted. GenTree* sideEffList = optExtractSideEffListFromConst(relop); // Transform the relop's operands to be both zeroes. ValueNum vnZero = vnStore->VNZeroForType(TYP_INT); relop->AsOp()->gtOp1 = gtNewIconNode(0); relop->AsOp()->gtOp1->gtVNPair = ValueNumPair(vnZero, vnZero); relop->AsOp()->gtOp2 = gtNewIconNode(0); relop->AsOp()->gtOp2->gtVNPair = ValueNumPair(vnZero, vnZero); // Update the oper and restore the value numbers. bool evalsToTrue = (vnStore->CoercedConstantValue<INT64>(vnCns) != 0); relop->SetOper(evalsToTrue ? GT_EQ : GT_NE); relop->gtVNPair = ValueNumPair(vnLib, vnCns); // Insert side effects back after they were removed from the JTrue stmt. // It is important not to allow duplicates exist in the IR, that why we delete // these side effects from the JTrue stmt before insert them back here. while (sideEffList != nullptr) { Statement* newStmt; if (sideEffList->OperGet() == GT_COMMA) { newStmt = fgNewStmtNearEnd(block, sideEffList->gtGetOp1()); sideEffList = sideEffList->gtGetOp2(); } else { newStmt = fgNewStmtNearEnd(block, sideEffList); sideEffList = nullptr; } // fgMorphBlockStmt could potentially affect stmts after the current one, // for example when it decides to fgRemoveRestOfBlock. fgMorphBlockStmt(block, newStmt DEBUGARG(__FUNCTION__)); } return test; } //------------------------------------------------------------------------------ // optVNConstantPropCurStmt // Performs constant prop on the current statement's tree nodes. // // Assumption: // This function is called as part of a pre-order tree walk. // // Arguments: // tree - The currently visited tree node. // stmt - The statement node in which the "tree" is present. // block - The block that contains the statement that contains the tree. // // Return Value: // Returns the standard visitor walk result. // // Description: // Checks if a node is an R-value and evaluates to a constant. If the node // evaluates to constant, then the tree is replaced by its side effects and // the constant node. // Compiler::fgWalkResult Compiler::optVNConstantPropCurStmt(BasicBlock* block, Statement* stmt, GenTree* tree) { // Don't perform const prop on expressions marked with GTF_DONT_CSE if (!tree->CanCSE()) { return WALK_CONTINUE; } // Don't propagate floating-point constants into a TYP_STRUCT LclVar // This can occur for HFA return values (see hfa_sf3E_r.exe) if (tree->TypeGet() == TYP_STRUCT) { return WALK_CONTINUE; } switch (tree->OperGet()) { // Make sure we have an R-value. case GT_ADD: case GT_SUB: case GT_DIV: case GT_MOD: case GT_UDIV: case GT_UMOD: case GT_EQ: case GT_NE: case GT_LT: case GT_LE: case GT_GE: case GT_GT: case GT_OR: case GT_XOR: case GT_AND: case GT_LSH: case GT_RSH: case GT_RSZ: case GT_NEG: case GT_CAST: case GT_INTRINSIC: break; case GT_JTRUE: break; case GT_MUL: // Don't transform long multiplies. if (tree->gtFlags & GTF_MUL_64RSLT) { return WALK_SKIP_SUBTREES; } break; case GT_LCL_VAR: case GT_LCL_FLD: // Make sure the local variable is an R-value. if ((tree->gtFlags & (GTF_VAR_USEASG | GTF_VAR_DEF | GTF_DONT_CSE)) != GTF_EMPTY) { return WALK_CONTINUE; } // Let's not conflict with CSE (to save the movw/movt). if (lclNumIsCSE(tree->AsLclVarCommon()->GetLclNum())) { return WALK_CONTINUE; } break; case GT_CALL: if (!tree->AsCall()->IsPure(this)) { return WALK_CONTINUE; } break; default: // Unknown node, continue to walk. return WALK_CONTINUE; } // Perform the constant propagation GenTree* newTree = optVNConstantPropOnTree(block, tree); if (newTree == nullptr) { // Not propagated, keep going. return WALK_CONTINUE; } // Successful propagation, mark as assertion propagated and skip // sub-tree (with side-effects) visits. // TODO #18291: at that moment stmt could be already removed from the stmt list. optAssertionProp_Update(newTree, tree, stmt); JITDUMP("After constant propagation on [%06u]:\n", tree->gtTreeID); DBEXEC(VERBOSE, gtDispStmt(stmt)); return WALK_SKIP_SUBTREES; } //------------------------------------------------------------------------------ // optVnNonNullPropCurStmt // Performs VN based non-null propagation on the tree node. // // Assumption: // This function is called as part of a pre-order tree walk. // // Arguments: // block - The block that contains the statement that contains the tree. // stmt - The statement node in which the "tree" is present. // tree - The currently visited tree node. // // Return Value: // None. // // Description: // Performs value number based non-null propagation on GT_CALL and // indirections. This is different from flow based assertions and helps // unify VN based constant prop and non-null prop in a single pre-order walk. // void Compiler::optVnNonNullPropCurStmt(BasicBlock* block, Statement* stmt, GenTree* tree) { ASSERT_TP empty = BitVecOps::UninitVal(); GenTree* newTree = nullptr; if (tree->OperGet() == GT_CALL) { newTree = optNonNullAssertionProp_Call(empty, tree->AsCall()); } else if (tree->OperIsIndir()) { newTree = optAssertionProp_Ind(empty, tree, stmt); } if (newTree) { assert(newTree == tree); optAssertionProp_Update(newTree, tree, stmt); } } //------------------------------------------------------------------------------ // optVNAssertionPropCurStmtVisitor // Unified Value Numbering based assertion propagation visitor. // // Assumption: // This function is called as part of a pre-order tree walk. // // Return Value: // WALK_RESULTs. // // Description: // An unified value numbering based assertion prop visitor that // performs non-null and constant assertion propagation based on // value numbers. // /* static */ Compiler::fgWalkResult Compiler::optVNAssertionPropCurStmtVisitor(GenTree** ppTree, fgWalkData* data) { VNAssertionPropVisitorInfo* pData = (VNAssertionPropVisitorInfo*)data->pCallbackData; Compiler* pThis = pData->pThis; pThis->optVnNonNullPropCurStmt(pData->block, pData->stmt, *ppTree); return pThis->optVNConstantPropCurStmt(pData->block, pData->stmt, *ppTree); } /***************************************************************************** * * Perform VN based i.e., data flow based assertion prop first because * even if we don't gen new control flow assertions, we still propagate * these first. * * Returns the skipped next stmt if the current statement or next few * statements got removed, else just returns the incoming stmt. */ Statement* Compiler::optVNAssertionPropCurStmt(BasicBlock* block, Statement* stmt) { // TODO-Review: EH successor/predecessor iteration seems broken. // See: SELF_HOST_TESTS_ARM\jit\Directed\ExcepFilters\fault\fault.exe if (block->bbCatchTyp == BBCT_FAULT) { return stmt; } // Preserve the prev link before the propagation and morph. Statement* prev = (stmt == block->firstStmt()) ? nullptr : stmt->GetPrevStmt(); // Perform VN based assertion prop first, in case we don't find // anything in assertion gen. optAssertionPropagatedCurrentStmt = false; VNAssertionPropVisitorInfo data(this, block, stmt); fgWalkTreePre(stmt->GetRootNodePointer(), Compiler::optVNAssertionPropCurStmtVisitor, &data); if (optAssertionPropagatedCurrentStmt) { fgMorphBlockStmt(block, stmt DEBUGARG("optVNAssertionPropCurStmt")); } // Check if propagation removed statements starting from current stmt. // If so, advance to the next good statement. Statement* nextStmt = (prev == nullptr) ? block->firstStmt() : prev->GetNextStmt(); return nextStmt; } /***************************************************************************** * * The entry point for assertion propagation */ void Compiler::optAssertionPropMain() { if (fgSsaPassesCompleted == 0) { return; } #ifdef DEBUG if (verbose) { printf("*************** In optAssertionPropMain()\n"); printf("Blocks/Trees at start of phase\n"); fgDispBasicBlocks(true); } #endif optAssertionInit(false); noway_assert(optAssertionCount == 0); // First discover all value assignments and record them in the table. for (BasicBlock* const block : Blocks()) { compCurBB = block; fgRemoveRestOfBlock = false; Statement* stmt = block->firstStmt(); while (stmt != nullptr) { // We need to remove the rest of the block. if (fgRemoveRestOfBlock) { fgRemoveStmt(block, stmt); stmt = stmt->GetNextStmt(); continue; } else { // Perform VN based assertion prop before assertion gen. Statement* nextStmt = optVNAssertionPropCurStmt(block, stmt); // Propagation resulted in removal of the remaining stmts, perform it. if (fgRemoveRestOfBlock) { stmt = stmt->GetNextStmt(); continue; } // Propagation removed the current stmt or next few stmts, so skip them. if (stmt != nextStmt) { stmt = nextStmt; continue; } } // Perform assertion gen for control flow based assertions. for (GenTree* const tree : stmt->TreeList()) { optAssertionGen(tree); } // Advance the iterator stmt = stmt->GetNextStmt(); } } if (optAssertionCount == 0) { // Zero out the bbAssertionIn values, as these can be referenced in RangeCheck::MergeAssertion // and this is sharedstate with the CSE phase: bbCseIn // for (BasicBlock* const block : Blocks()) { block->bbAssertionIn = BitVecOps::MakeEmpty(apTraits); } return; } #ifdef DEBUG fgDebugCheckLinks(); #endif // Allocate the bits for the predicate sensitive dataflow analysis bbJtrueAssertionOut = optInitAssertionDataflowFlags(); ASSERT_TP* jumpDestGen = optComputeAssertionGen(); // Modified dataflow algorithm for available expressions. DataFlow flow(this); AssertionPropFlowCallback ap(this, bbJtrueAssertionOut, jumpDestGen); if (ap.VerboseDataflow()) { JITDUMP("AssertionPropFlowCallback:\n\n") } flow.ForwardAnalysis(ap); for (BasicBlock* const block : Blocks()) { // Compute any implied non-Null assertions for block->bbAssertionIn optImpliedByTypeOfAssertions(block->bbAssertionIn); } #ifdef DEBUG if (verbose) { for (BasicBlock* const block : Blocks()) { printf(FMT_BB ":\n", block->bbNum); optDumpAssertionIndices(" in = ", block->bbAssertionIn, "\n"); optDumpAssertionIndices(" out = ", block->bbAssertionOut, "\n"); if (block->bbJumpKind == BBJ_COND) { printf(" " FMT_BB " = ", block->bbJumpDest->bbNum); optDumpAssertionIndices(bbJtrueAssertionOut[block->bbNum], "\n"); } } printf("\n"); } #endif // DEBUG ASSERT_TP assertions = BitVecOps::MakeEmpty(apTraits); // Perform assertion propagation (and constant folding) for (BasicBlock* const block : Blocks()) { BitVecOps::Assign(apTraits, assertions, block->bbAssertionIn); // TODO-Review: EH successor/predecessor iteration seems broken. // SELF_HOST_TESTS_ARM\jit\Directed\ExcepFilters\fault\fault.exe if (block->bbCatchTyp == BBCT_FAULT) { continue; } // Make the current basic block address available globally. compCurBB = block; fgRemoveRestOfBlock = false; // Walk the statement trees in this basic block Statement* stmt = block->FirstNonPhiDef(); while (stmt != nullptr) { // Propagation tells us to remove the rest of the block. Remove it. if (fgRemoveRestOfBlock) { fgRemoveStmt(block, stmt); stmt = stmt->GetNextStmt(); continue; } // Preserve the prev link before the propagation and morph, to check if propagation // removes the current stmt. Statement* prevStmt = (stmt == block->firstStmt()) ? nullptr : stmt->GetPrevStmt(); optAssertionPropagatedCurrentStmt = false; // set to true if a assertion propagation took place // and thus we must morph, set order, re-link for (GenTree* tree = stmt->GetTreeList(); tree != nullptr; tree = tree->gtNext) { optDumpAssertionIndices("Propagating ", assertions, " "); JITDUMP("for " FMT_BB ", stmt " FMT_STMT ", tree [%06d]", block->bbNum, stmt->GetID(), dspTreeID(tree)); JITDUMP(", tree -> "); JITDUMPEXEC(optPrintAssertionIndex(tree->GetAssertionInfo().GetAssertionIndex())); JITDUMP("\n"); GenTree* newTree = optAssertionProp(assertions, tree, stmt, block); if (newTree) { assert(optAssertionPropagatedCurrentStmt == true); tree = newTree; } // If this tree makes an assertion - make it available. if (tree->GeneratesAssertion()) { AssertionInfo info = tree->GetAssertionInfo(); optImpliedAssertions(info.GetAssertionIndex(), assertions); BitVecOps::AddElemD(apTraits, assertions, info.GetAssertionIndex() - 1); } } if (optAssertionPropagatedCurrentStmt) { #ifdef DEBUG if (verbose) { printf("Re-morphing this stmt:\n"); gtDispStmt(stmt); printf("\n"); } #endif // Re-morph the statement. fgMorphBlockStmt(block, stmt DEBUGARG("optAssertionPropMain")); } // Check if propagation removed statements starting from current stmt. // If so, advance to the next good statement. Statement* nextStmt = (prevStmt == nullptr) ? block->firstStmt() : prevStmt->GetNextStmt(); stmt = (stmt == nextStmt) ? stmt->GetNextStmt() : nextStmt; } optAssertionPropagatedCurrentStmt = false; // clear it back as we are done with stmts. } #ifdef DEBUG fgDebugCheckBBlist(); fgDebugCheckLinks(); #endif }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX AssertionProp XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif //------------------------------------------------------------------------ // Contains: Whether the range contains a given integral value, inclusive. // // Arguments: // value - the integral value in question // // Return Value: // "true" if the value is within the range's bounds, "false" otherwise. // bool IntegralRange::Contains(int64_t value) const { int64_t lowerBound = SymbolicToRealValue(m_lowerBound); int64_t upperBound = SymbolicToRealValue(m_upperBound); return (lowerBound <= value) && (value <= upperBound); } //------------------------------------------------------------------------ // SymbolicToRealValue: Convert a symbolic value to a 64-bit signed integer. // // Arguments: // value - the symbolic value in question // // Return Value: // Integer correspoding to the symbolic value. // /* static */ int64_t IntegralRange::SymbolicToRealValue(SymbolicIntegerValue value) { static const int64_t SymbolicToRealMap[]{INT64_MIN, INT32_MIN, INT16_MIN, INT8_MIN, 0, 1, INT8_MAX, UINT8_MAX, INT16_MAX, UINT16_MAX, INT32_MAX, UINT32_MAX, INT64_MAX}; assert(sizeof(SymbolicIntegerValue) == sizeof(int32_t)); assert(SymbolicToRealMap[static_cast<int32_t>(SymbolicIntegerValue::LongMin)] == INT64_MIN); assert(SymbolicToRealMap[static_cast<int32_t>(SymbolicIntegerValue::Zero)] == 0); assert(SymbolicToRealMap[static_cast<int32_t>(SymbolicIntegerValue::LongMax)] == INT64_MAX); return SymbolicToRealMap[static_cast<int32_t>(value)]; } //------------------------------------------------------------------------ // LowerBoundForType: Get the symbolic lower bound for a type. // // Arguments: // type - the integral type in question // // Return Value: // Symbolic value representing the smallest possible value "type" can represent. // /* static */ SymbolicIntegerValue IntegralRange::LowerBoundForType(var_types type) { switch (type) { case TYP_BOOL: case TYP_UBYTE: case TYP_USHORT: return SymbolicIntegerValue::Zero; case TYP_BYTE: return SymbolicIntegerValue::ByteMin; case TYP_SHORT: return SymbolicIntegerValue::ShortMin; case TYP_INT: return SymbolicIntegerValue::IntMin; case TYP_LONG: return SymbolicIntegerValue::LongMin; default: unreached(); } } //------------------------------------------------------------------------ // UpperBoundForType: Get the symbolic upper bound for a type. // // Arguments: // type - the integral type in question // // Return Value: // Symbolic value representing the largest possible value "type" can represent. // /* static */ SymbolicIntegerValue IntegralRange::UpperBoundForType(var_types type) { switch (type) { case TYP_BYTE: return SymbolicIntegerValue::ByteMax; case TYP_BOOL: case TYP_UBYTE: return SymbolicIntegerValue::UByteMax; case TYP_SHORT: return SymbolicIntegerValue::ShortMax; case TYP_USHORT: return SymbolicIntegerValue::UShortMax; case TYP_INT: return SymbolicIntegerValue::IntMax; case TYP_UINT: return SymbolicIntegerValue::UIntMax; case TYP_LONG: return SymbolicIntegerValue::LongMax; default: unreached(); } } //------------------------------------------------------------------------ // ForNode: Compute the integral range for a node. // // Arguments: // node - the node, of an integral type, in question // compiler - the Compiler, used to retrieve additional info // // Return Value: // The integral range this node produces. // /* static */ IntegralRange IntegralRange::ForNode(GenTree* node, Compiler* compiler) { assert(varTypeIsIntegral(node)); var_types rangeType = node->TypeGet(); switch (node->OperGet()) { case GT_EQ: case GT_NE: case GT_LT: case GT_LE: case GT_GE: case GT_GT: return {SymbolicIntegerValue::Zero, SymbolicIntegerValue::One}; case GT_ARR_LENGTH: return {SymbolicIntegerValue::Zero, SymbolicIntegerValue::IntMax}; case GT_CALL: if (node->AsCall()->NormalizesSmallTypesOnReturn()) { rangeType = static_cast<var_types>(node->AsCall()->gtReturnType); } break; case GT_LCL_VAR: if (compiler->lvaGetDesc(node->AsLclVar())->lvNormalizeOnStore()) { rangeType = compiler->lvaGetDesc(node->AsLclVar())->TypeGet(); } break; case GT_CAST: return ForCastOutput(node->AsCast()); #if defined(FEATURE_HW_INTRINSICS) case GT_HWINTRINSIC: switch (node->AsHWIntrinsic()->GetHWIntrinsicId()) { #if defined(TARGET_XARCH) case NI_BMI1_TrailingZeroCount: case NI_BMI1_X64_TrailingZeroCount: case NI_LZCNT_LeadingZeroCount: case NI_LZCNT_X64_LeadingZeroCount: case NI_POPCNT_PopCount: case NI_POPCNT_X64_PopCount: #elif defined(TARGET_ARM64) case NI_AdvSimd_PopCount: case NI_AdvSimd_LeadingZeroCount: case NI_AdvSimd_LeadingSignCount: case NI_ArmBase_LeadingZeroCount: case NI_ArmBase_Arm64_LeadingZeroCount: case NI_ArmBase_Arm64_LeadingSignCount: #else #error Unsupported platform #endif // TODO-Casts: specify more precise ranges once "IntegralRange" supports them. return {SymbolicIntegerValue::Zero, SymbolicIntegerValue::ByteMax}; default: break; } break; #endif // defined(FEATURE_HW_INTRINSICS) default: break; } return ForType(rangeType); } //------------------------------------------------------------------------ // ForCastInput: Get the non-overflowing input range for a cast. // // This routine computes the input range for a cast from // an integer to an integer for which it will not overflow. // See also the specification comment for IntegralRange. // // Arguments: // cast - the cast node for which the range will be computed // // Return Value: // The range this cast consumes without overflowing - see description. // /* static */ IntegralRange IntegralRange::ForCastInput(GenTreeCast* cast) { var_types fromType = genActualType(cast->CastOp()); var_types toType = cast->CastToType(); bool fromUnsigned = cast->IsUnsigned(); assert((fromType == TYP_INT) || (fromType == TYP_LONG) || varTypeIsGC(fromType)); assert(varTypeIsIntegral(toType)); // Cast from a GC type is the same as a cast from TYP_I_IMPL for our purposes. if (varTypeIsGC(fromType)) { fromType = TYP_I_IMPL; } if (!cast->gtOverflow()) { // CAST(small type <- uint/int/ulong/long) - [TO_TYPE_MIN..TO_TYPE_MAX] if (varTypeIsSmall(toType)) { return {LowerBoundForType(toType), UpperBoundForType(toType)}; } // We choose to say here that representation-changing casts never overflow. // It does not really matter what we do here because representation-changing // non-overflowing casts cannot be deleted from the IR in any case. // CAST(uint/int <- uint/int) - [INT_MIN..INT_MAX] // CAST(uint/int <- ulong/long) - [LONG_MIN..LONG_MAX] // CAST(ulong/long <- uint/int) - [INT_MIN..INT_MAX] // CAST(ulong/long <- ulong/long) - [LONG_MIN..LONG_MAX] return ForType(fromType); } SymbolicIntegerValue lowerBound; SymbolicIntegerValue upperBound; // CAST_OVF(small type <- int/long) - [TO_TYPE_MIN..TO_TYPE_MAX] // CAST_OVF(small type <- uint/ulong) - [0..TO_TYPE_MAX] if (varTypeIsSmall(toType)) { lowerBound = fromUnsigned ? SymbolicIntegerValue::Zero : LowerBoundForType(toType); upperBound = UpperBoundForType(toType); } else { switch (toType) { // CAST_OVF(uint <- uint) - [INT_MIN..INT_MAX] // CAST_OVF(uint <- int) - [0..INT_MAX] // CAST_OVF(uint <- ulong/long) - [0..UINT_MAX] case TYP_UINT: if (fromType == TYP_LONG) { lowerBound = SymbolicIntegerValue::Zero; upperBound = SymbolicIntegerValue::UIntMax; } else { lowerBound = fromUnsigned ? SymbolicIntegerValue::IntMin : SymbolicIntegerValue::Zero; upperBound = SymbolicIntegerValue::IntMax; } break; // CAST_OVF(int <- uint/ulong) - [0..INT_MAX] // CAST_OVF(int <- int/long) - [INT_MIN..INT_MAX] case TYP_INT: lowerBound = fromUnsigned ? SymbolicIntegerValue::Zero : SymbolicIntegerValue::IntMin; upperBound = SymbolicIntegerValue::IntMax; break; // CAST_OVF(ulong <- uint) - [INT_MIN..INT_MAX] // CAST_OVF(ulong <- int) - [0..INT_MAX] // CAST_OVF(ulong <- ulong) - [LONG_MIN..LONG_MAX] // CAST_OVF(ulong <- long) - [0..LONG_MAX] case TYP_ULONG: lowerBound = fromUnsigned ? LowerBoundForType(fromType) : SymbolicIntegerValue::Zero; upperBound = UpperBoundForType(fromType); break; // CAST_OVF(long <- uint/int) - [INT_MIN..INT_MAX] // CAST_OVF(long <- ulong) - [0..LONG_MAX] // CAST_OVF(long <- long) - [LONG_MIN..LONG_MAX] case TYP_LONG: if (fromUnsigned && (fromType == TYP_LONG)) { lowerBound = SymbolicIntegerValue::Zero; } else { lowerBound = LowerBoundForType(fromType); } upperBound = UpperBoundForType(fromType); break; default: unreached(); } } return {lowerBound, upperBound}; } //------------------------------------------------------------------------ // ForCastOutput: Get the output range for a cast. // // This method is the "output" counterpart to ForCastInput, it returns // a range produced by a cast (by definition, non-overflowing one). // The output range is the same for representation-preserving casts, but // can be different for others. One example is CAST_OVF(uint <- long). // The input range is [0..UINT_MAX], while the output is [INT_MIN..INT_MAX]. // Unlike ForCastInput, this method supports casts from floating point types. // // Arguments: // cast - the cast node for which the range will be computed // // Return Value: // The range this cast produces - see description. // /* static */ IntegralRange IntegralRange::ForCastOutput(GenTreeCast* cast) { var_types fromType = genActualType(cast->CastOp()); var_types toType = cast->CastToType(); bool fromUnsigned = cast->IsUnsigned(); assert((fromType == TYP_INT) || (fromType == TYP_LONG) || varTypeIsFloating(fromType) || varTypeIsGC(fromType)); assert(varTypeIsIntegral(toType)); // CAST/CAST_OVF(small type <- float/double) - [TO_TYPE_MIN..TO_TYPE_MAX] // CAST/CAST_OVF(uint/int <- float/double) - [INT_MIN..INT_MAX] // CAST/CAST_OVF(ulong/long <- float/double) - [LONG_MIN..LONG_MAX] if (varTypeIsFloating(fromType)) { if (!varTypeIsSmall(toType)) { toType = genActualType(toType); } return IntegralRange::ForType(toType); } // Cast from a GC type is the same as a cast from TYP_I_IMPL for our purposes. if (varTypeIsGC(fromType)) { fromType = TYP_I_IMPL; } if (varTypeIsSmall(toType) || (genActualType(toType) == fromType)) { return ForCastInput(cast); } // CAST(uint/int <- ulong/long) - [INT_MIN..INT_MAX] // CAST(ulong/long <- uint) - [0..UINT_MAX] // CAST(ulong/long <- int) - [INT_MIN..INT_MAX] if (!cast->gtOverflow()) { if ((fromType == TYP_INT) && fromUnsigned) { return {SymbolicIntegerValue::Zero, SymbolicIntegerValue::UIntMax}; } return {SymbolicIntegerValue::IntMin, SymbolicIntegerValue::IntMax}; } SymbolicIntegerValue lowerBound; SymbolicIntegerValue upperBound; switch (toType) { // CAST_OVF(uint <- ulong) - [INT_MIN..INT_MAX] // CAST_OVF(uint <- long) - [INT_MIN..INT_MAX] case TYP_UINT: lowerBound = SymbolicIntegerValue::IntMin; upperBound = SymbolicIntegerValue::IntMax; break; // CAST_OVF(int <- ulong) - [0..INT_MAX] // CAST_OVF(int <- long) - [INT_MIN..INT_MAX] case TYP_INT: lowerBound = fromUnsigned ? SymbolicIntegerValue::Zero : SymbolicIntegerValue::IntMin; upperBound = SymbolicIntegerValue::IntMax; break; // CAST_OVF(ulong <- uint) - [0..UINT_MAX] // CAST_OVF(ulong <- int) - [0..INT_MAX] case TYP_ULONG: lowerBound = SymbolicIntegerValue::Zero; upperBound = fromUnsigned ? SymbolicIntegerValue::UIntMax : SymbolicIntegerValue::IntMax; break; // CAST_OVF(long <- uint) - [0..UINT_MAX] // CAST_OVF(long <- int) - [INT_MIN..INT_MAX] case TYP_LONG: lowerBound = fromUnsigned ? SymbolicIntegerValue::Zero : SymbolicIntegerValue::IntMin; upperBound = fromUnsigned ? SymbolicIntegerValue::UIntMax : SymbolicIntegerValue::IntMax; break; default: unreached(); } return {lowerBound, upperBound}; } #ifdef DEBUG /* static */ void IntegralRange::Print(IntegralRange range) { printf("[%lld", SymbolicToRealValue(range.m_lowerBound)); printf(".."); printf("%lld]", SymbolicToRealValue(range.m_upperBound)); } #endif // DEBUG /***************************************************************************** * * Helper passed to Compiler::fgWalkTreePre() to find the Asgn node for optAddCopies() */ /* static */ Compiler::fgWalkResult Compiler::optAddCopiesCallback(GenTree** pTree, fgWalkData* data) { GenTree* tree = *pTree; if (tree->OperIs(GT_ASG)) { GenTree* op1 = tree->AsOp()->gtOp1; Compiler* comp = data->compiler; if ((op1->gtOper == GT_LCL_VAR) && (op1->AsLclVarCommon()->GetLclNum() == comp->optAddCopyLclNum)) { comp->optAddCopyAsgnNode = tree; return WALK_ABORT; } } return WALK_CONTINUE; } /***************************************************************************** * * Add new copies before Assertion Prop. */ void Compiler::optAddCopies() { unsigned lclNum; LclVarDsc* varDsc; #ifdef DEBUG if (verbose) { printf("\n*************** In optAddCopies()\n\n"); } if (verboseTrees) { printf("Blocks/Trees at start of phase\n"); fgDispBasicBlocks(true); } #endif // Don't add any copies if we have reached the tracking limit. if (lvaHaveManyLocals()) { return; } for (lclNum = 0, varDsc = lvaTable; lclNum < lvaCount; lclNum++, varDsc++) { var_types typ = varDsc->TypeGet(); // We only add copies for non temp local variables // that have a single def and that can possibly be enregistered if (varDsc->lvIsTemp || !varDsc->lvSingleDef || !varTypeIsEnregisterable(typ)) { continue; } /* For lvNormalizeOnLoad(), we need to add a cast to the copy-assignment like "copyLclNum = int(varDsc)" and optAssertionGen() only tracks simple assignments. The same goes for lvNormalizedOnStore as the cast is generated in fgMorphSmpOpAsg. This boils down to not having a copy until optAssertionGen handles this*/ if (varDsc->lvNormalizeOnLoad() || varDsc->lvNormalizeOnStore()) { continue; } if (varTypeIsSmall(varDsc->TypeGet()) || typ == TYP_BOOL) { continue; } // If locals must be initialized to zero, that initialization counts as a second definition. // VB in particular allows usage of variables not explicitly initialized. // Note that this effectively disables this optimization for all local variables // as C# sets InitLocals all the time starting in Whidbey. if (!varDsc->lvIsParam && info.compInitMem) { continue; } // On x86 we may want to add a copy for an incoming double parameter // because we can ensure that the copy we make is double aligned // where as we can never ensure the alignment of an incoming double parameter // // On all other platforms we will never need to make a copy // for an incoming double parameter bool isFloatParam = false; #ifdef TARGET_X86 isFloatParam = varDsc->lvIsParam && varTypeIsFloating(typ); #endif if (!isFloatParam && !varDsc->lvVolatileHint) { continue; } // We don't want to add a copy for a variable that is part of a struct if (varDsc->lvIsStructField) { continue; } // We require that the weighted ref count be significant. if (varDsc->lvRefCntWtd() <= (BB_LOOP_WEIGHT_SCALE * BB_UNITY_WEIGHT / 2)) { continue; } // For parameters, we only want to add a copy for the heavier-than-average // uses instead of adding a copy to cover every single use. // 'paramImportantUseDom' is the set of blocks that dominate the // heavier-than-average uses of a parameter. // Initial value is all blocks. BlockSet paramImportantUseDom(BlockSetOps::MakeFull(this)); // This will be threshold for determining heavier-than-average uses weight_t paramAvgWtdRefDiv2 = (varDsc->lvRefCntWtd() + varDsc->lvRefCnt() / 2) / (varDsc->lvRefCnt() * 2); bool paramFoundImportantUse = false; #ifdef DEBUG if (verbose) { printf("Trying to add a copy for V%02u %s, avg_wtd = %s\n", lclNum, varDsc->lvIsParam ? "an arg" : "a local", refCntWtd2str(paramAvgWtdRefDiv2)); } #endif // // We must have a ref in a block that is dominated only by the entry block // if (BlockSetOps::MayBeUninit(varDsc->lvRefBlks)) { // No references continue; } bool isDominatedByFirstBB = false; BlockSetOps::Iter iter(this, varDsc->lvRefBlks); unsigned bbNum = 0; while (iter.NextElem(&bbNum)) { /* Find the block 'bbNum' */ BasicBlock* block = fgFirstBB; while (block && (block->bbNum != bbNum)) { block = block->bbNext; } noway_assert(block && (block->bbNum == bbNum)); bool importantUseInBlock = (varDsc->lvIsParam) && (block->getBBWeight(this) > paramAvgWtdRefDiv2); bool isPreHeaderBlock = ((block->bbFlags & BBF_LOOP_PREHEADER) != 0); BlockSet blockDom(BlockSetOps::UninitVal()); BlockSet blockDomSub0(BlockSetOps::UninitVal()); if (block->bbIDom == nullptr && isPreHeaderBlock) { // Loop Preheader blocks that we insert will have a bbDom set that is nullptr // but we can instead use the bNext successor block's dominator information noway_assert(block->bbNext != nullptr); BlockSetOps::AssignNoCopy(this, blockDom, fgGetDominatorSet(block->bbNext)); } else { BlockSetOps::AssignNoCopy(this, blockDom, fgGetDominatorSet(block)); } if (!BlockSetOps::IsEmpty(this, blockDom)) { BlockSetOps::Assign(this, blockDomSub0, blockDom); if (isPreHeaderBlock) { // We must clear bbNext block number from the dominator set BlockSetOps::RemoveElemD(this, blockDomSub0, block->bbNext->bbNum); } /* Is this block dominated by fgFirstBB? */ if (BlockSetOps::IsMember(this, blockDomSub0, fgFirstBB->bbNum)) { isDominatedByFirstBB = true; } } #ifdef DEBUG if (verbose) { printf(" Referenced in " FMT_BB ", bbWeight is %s", bbNum, refCntWtd2str(block->getBBWeight(this))); if (isDominatedByFirstBB) { printf(", which is dominated by BB01"); } if (importantUseInBlock) { printf(", ImportantUse"); } printf("\n"); } #endif /* If this is a heavier-than-average block, then track which blocks dominate this use of the parameter. */ if (importantUseInBlock) { paramFoundImportantUse = true; BlockSetOps::IntersectionD(this, paramImportantUseDom, blockDomSub0); // Clear blocks that do not dominate } } // We should have found at least one heavier-than-averageDiv2 block. if (varDsc->lvIsParam) { if (!paramFoundImportantUse) { continue; } } // For us to add a new copy: // we require that we have a floating point parameter // or a lvVolatile variable that is always reached from the first BB // and we have at least one block available in paramImportantUseDom // bool doCopy = (isFloatParam || (isDominatedByFirstBB && varDsc->lvVolatileHint)) && !BlockSetOps::IsEmpty(this, paramImportantUseDom); // Under stress mode we expand the number of candidates // to include parameters of any type // or any variable that is always reached from the first BB // if (compStressCompile(STRESS_GENERIC_VARN, 30)) { // Ensure that we preserve the invariants required by the subsequent code. if (varDsc->lvIsParam || isDominatedByFirstBB) { doCopy = true; } } if (!doCopy) { continue; } Statement* stmt; unsigned copyLclNum = lvaGrabTemp(false DEBUGARG("optAddCopies")); // Because lvaGrabTemp may have reallocated the lvaTable, ensure varDsc is still in sync. varDsc = lvaGetDesc(lclNum); // Set lvType on the new Temp Lcl Var lvaGetDesc(copyLclNum)->lvType = typ; #ifdef DEBUG if (verbose) { printf("\n Finding the best place to insert the assignment V%02i=V%02i\n", copyLclNum, lclNum); } #endif if (varDsc->lvIsParam) { noway_assert(varDsc->lvDefStmt == nullptr || varDsc->lvIsStructField); // Create a new copy assignment tree GenTree* copyAsgn = gtNewTempAssign(copyLclNum, gtNewLclvNode(lclNum, typ)); /* Find the best block to insert the new assignment */ /* We will choose the lowest weighted block, and within */ /* those block, the highest numbered block which */ /* dominates all the uses of the local variable */ /* Our default is to use the first block */ BasicBlock* bestBlock = fgFirstBB; weight_t bestWeight = bestBlock->getBBWeight(this); BasicBlock* block = bestBlock; #ifdef DEBUG if (verbose) { printf(" Starting at " FMT_BB ", bbWeight is %s", block->bbNum, refCntWtd2str(block->getBBWeight(this))); printf(", bestWeight is %s\n", refCntWtd2str(bestWeight)); } #endif /* We have already calculated paramImportantUseDom above. */ BlockSetOps::Iter iter(this, paramImportantUseDom); unsigned bbNum = 0; while (iter.NextElem(&bbNum)) { /* Advance block to point to 'bbNum' */ /* This assumes that the iterator returns block number is increasing lexical order. */ while (block && (block->bbNum != bbNum)) { block = block->bbNext; } noway_assert(block && (block->bbNum == bbNum)); #ifdef DEBUG if (verbose) { printf(" Considering " FMT_BB ", bbWeight is %s", block->bbNum, refCntWtd2str(block->getBBWeight(this))); printf(", bestWeight is %s\n", refCntWtd2str(bestWeight)); } #endif // Does this block have a smaller bbWeight value? if (block->getBBWeight(this) > bestWeight) { #ifdef DEBUG if (verbose) { printf("bbWeight too high\n"); } #endif continue; } // Don't use blocks that are exception handlers because // inserting a new first statement will interface with // the CATCHARG if (handlerGetsXcptnObj(block->bbCatchTyp)) { #ifdef DEBUG if (verbose) { printf("Catch block\n"); } #endif continue; } // Don't use the BBJ_ALWAYS block marked with BBF_KEEP_BBJ_ALWAYS. These // are used by EH code. The JIT can not generate code for such a block. if (block->bbFlags & BBF_KEEP_BBJ_ALWAYS) { #if defined(FEATURE_EH_FUNCLETS) // With funclets, this is only used for BBJ_CALLFINALLY/BBJ_ALWAYS pairs. For x86, it is also used // as the "final step" block for leaving finallys. assert(block->isBBCallAlwaysPairTail()); #endif // FEATURE_EH_FUNCLETS #ifdef DEBUG if (verbose) { printf("Internal EH BBJ_ALWAYS block\n"); } #endif continue; } // This block will be the new candidate for the insert point // for the new assignment CLANG_FORMAT_COMMENT_ANCHOR; #ifdef DEBUG if (verbose) { printf("new bestBlock\n"); } #endif bestBlock = block; bestWeight = block->getBBWeight(this); } // If there is a use of the variable in this block // then we insert the assignment at the beginning // otherwise we insert the statement at the end CLANG_FORMAT_COMMENT_ANCHOR; #ifdef DEBUG if (verbose) { printf(" Insert copy at the %s of " FMT_BB "\n", (BlockSetOps::IsEmpty(this, paramImportantUseDom) || BlockSetOps::IsMember(this, varDsc->lvRefBlks, bestBlock->bbNum)) ? "start" : "end", bestBlock->bbNum); } #endif if (BlockSetOps::IsEmpty(this, paramImportantUseDom) || BlockSetOps::IsMember(this, varDsc->lvRefBlks, bestBlock->bbNum)) { stmt = fgNewStmtAtBeg(bestBlock, copyAsgn); } else { stmt = fgNewStmtNearEnd(bestBlock, copyAsgn); } } else { noway_assert(varDsc->lvDefStmt != nullptr); /* Locate the assignment to varDsc in the lvDefStmt */ stmt = varDsc->lvDefStmt; optAddCopyLclNum = lclNum; // in optAddCopyAsgnNode = nullptr; // out fgWalkTreePre(stmt->GetRootNodePointer(), Compiler::optAddCopiesCallback, (void*)this, false); noway_assert(optAddCopyAsgnNode); GenTree* tree = optAddCopyAsgnNode; GenTree* op1 = tree->AsOp()->gtOp1; noway_assert(tree && op1 && tree->OperIs(GT_ASG) && (op1->gtOper == GT_LCL_VAR) && (op1->AsLclVarCommon()->GetLclNum() == lclNum)); /* Assign the old expression into the new temp */ GenTree* newAsgn = gtNewTempAssign(copyLclNum, tree->AsOp()->gtOp2); /* Copy the new temp to op1 */ GenTree* copyAsgn = gtNewAssignNode(op1, gtNewLclvNode(copyLclNum, typ)); /* Change the tree to a GT_COMMA with the two assignments as child nodes */ tree->gtBashToNOP(); tree->ChangeOper(GT_COMMA); tree->AsOp()->gtOp1 = newAsgn; tree->AsOp()->gtOp2 = copyAsgn; tree->gtFlags |= (newAsgn->gtFlags & GTF_ALL_EFFECT); tree->gtFlags |= (copyAsgn->gtFlags & GTF_ALL_EFFECT); } #ifdef DEBUG if (verbose) { printf("\nIntroducing a new copy for V%02u\n", lclNum); gtDispTree(stmt->GetRootNode()); printf("\n"); } #endif } } //------------------------------------------------------------------------------ // GetAssertionDep: Retrieve the assertions on this local variable // // Arguments: // lclNum - The local var id. // // Return Value: // The dependent assertions (assertions using the value of the local var) // of the local var. // ASSERT_TP& Compiler::GetAssertionDep(unsigned lclNum) { JitExpandArray<ASSERT_TP>& dep = *optAssertionDep; if (dep[lclNum] == nullptr) { dep[lclNum] = BitVecOps::MakeEmpty(apTraits); } return dep[lclNum]; } /***************************************************************************** * * Initialize the assertion prop bitset traits and the default bitsets. */ void Compiler::optAssertionTraitsInit(AssertionIndex assertionCount) { apTraits = new (this, CMK_AssertionProp) BitVecTraits(assertionCount, this); apFull = BitVecOps::MakeFull(apTraits); } /***************************************************************************** * * Initialize the assertion prop tracking logic. */ void Compiler::optAssertionInit(bool isLocalProp) { // Use a function countFunc to determine a proper maximum assertion count for the // method being compiled. The function is linear to the IL size for small and // moderate methods. For large methods, considering throughput impact, we track no // more than 64 assertions. // Note this tracks at most only 256 assertions. static const AssertionIndex countFunc[] = {64, 128, 256, 64}; static const unsigned lowerBound = 0; static const unsigned upperBound = ArrLen(countFunc) - 1; const unsigned codeSize = info.compILCodeSize / 512; optMaxAssertionCount = countFunc[isLocalProp ? lowerBound : min(upperBound, codeSize)]; optLocalAssertionProp = isLocalProp; optAssertionTabPrivate = new (this, CMK_AssertionProp) AssertionDsc[optMaxAssertionCount]; optComplementaryAssertionMap = new (this, CMK_AssertionProp) AssertionIndex[optMaxAssertionCount + 1](); // zero-inited (NO_ASSERTION_INDEX) assert(NO_ASSERTION_INDEX == 0); if (!isLocalProp) { optValueNumToAsserts = new (getAllocator(CMK_AssertionProp)) ValueNumToAssertsMap(getAllocator(CMK_AssertionProp)); } if (optAssertionDep == nullptr) { optAssertionDep = new (this, CMK_AssertionProp) JitExpandArray<ASSERT_TP>(getAllocator(CMK_AssertionProp), max(1, lvaCount)); } optAssertionTraitsInit(optMaxAssertionCount); optAssertionCount = 0; optAssertionPropagated = false; bbJtrueAssertionOut = nullptr; } #ifdef DEBUG void Compiler::optPrintAssertion(AssertionDsc* curAssertion, AssertionIndex assertionIndex /* = 0 */) { if (curAssertion->op1.kind == O1K_EXACT_TYPE) { printf("Type "); } else if (curAssertion->op1.kind == O1K_ARR_BND) { printf("ArrBnds "); } else if (curAssertion->op1.kind == O1K_SUBTYPE) { printf("Subtype "); } else if (curAssertion->op2.kind == O2K_LCLVAR_COPY) { printf("Copy "); } else if ((curAssertion->op2.kind == O2K_CONST_INT) || (curAssertion->op2.kind == O2K_CONST_LONG) || (curAssertion->op2.kind == O2K_CONST_DOUBLE) || (curAssertion->op2.kind == O2K_ZEROOBJ)) { printf("Constant "); } else if (curAssertion->op2.kind == O2K_SUBRANGE) { printf("Subrange "); } else { printf("?assertion classification? "); } printf("Assertion: "); if (!optLocalAssertionProp) { printf("(" FMT_VN "," FMT_VN ") ", curAssertion->op1.vn, curAssertion->op2.vn); } if ((curAssertion->op1.kind == O1K_LCLVAR) || (curAssertion->op1.kind == O1K_EXACT_TYPE) || (curAssertion->op1.kind == O1K_SUBTYPE)) { printf("V%02u", curAssertion->op1.lcl.lclNum); if (curAssertion->op1.lcl.ssaNum != SsaConfig::RESERVED_SSA_NUM) { printf(".%02u", curAssertion->op1.lcl.ssaNum); } } else if (curAssertion->op1.kind == O1K_ARR_BND) { printf("[idx:"); vnStore->vnDump(this, curAssertion->op1.bnd.vnIdx); printf(";len:"); vnStore->vnDump(this, curAssertion->op1.bnd.vnLen); printf("]"); } else if (curAssertion->op1.kind == O1K_BOUND_OPER_BND) { printf("Oper_Bnd"); vnStore->vnDump(this, curAssertion->op1.vn); } else if (curAssertion->op1.kind == O1K_BOUND_LOOP_BND) { printf("Loop_Bnd"); vnStore->vnDump(this, curAssertion->op1.vn); } else if (curAssertion->op1.kind == O1K_CONSTANT_LOOP_BND) { printf("Const_Loop_Bnd"); vnStore->vnDump(this, curAssertion->op1.vn); } else if (curAssertion->op1.kind == O1K_CONSTANT_LOOP_BND_UN) { printf("Const_Loop_Bnd_Un"); vnStore->vnDump(this, curAssertion->op1.vn); } else if (curAssertion->op1.kind == O1K_VALUE_NUMBER) { printf("Value_Number"); vnStore->vnDump(this, curAssertion->op1.vn); } else { printf("?op1.kind?"); } if (curAssertion->assertionKind == OAK_SUBRANGE) { printf(" in "); } else if (curAssertion->assertionKind == OAK_EQUAL) { if (curAssertion->op1.kind == O1K_LCLVAR) { printf(" == "); } else { printf(" is "); } } else if (curAssertion->assertionKind == OAK_NO_THROW) { printf(" in range "); } else if (curAssertion->assertionKind == OAK_NOT_EQUAL) { if (curAssertion->op1.kind == O1K_LCLVAR) { printf(" != "); } else { printf(" is not "); } } else { printf(" ?assertionKind? "); } if (curAssertion->op1.kind != O1K_ARR_BND) { switch (curAssertion->op2.kind) { case O2K_LCLVAR_COPY: printf("V%02u", curAssertion->op2.lcl.lclNum); if (curAssertion->op1.lcl.ssaNum != SsaConfig::RESERVED_SSA_NUM) { printf(".%02u", curAssertion->op1.lcl.ssaNum); } if (curAssertion->op2.zeroOffsetFieldSeq != nullptr) { printf(" Zero"); gtDispFieldSeq(curAssertion->op2.zeroOffsetFieldSeq); } break; case O2K_CONST_INT: case O2K_IND_CNS_INT: if (curAssertion->op1.kind == O1K_EXACT_TYPE) { printf("Exact Type MT(%08X)", dspPtr(curAssertion->op2.u1.iconVal)); assert(curAssertion->op2.u1.iconFlags != GTF_EMPTY); } else if (curAssertion->op1.kind == O1K_SUBTYPE) { printf("MT(%08X)", dspPtr(curAssertion->op2.u1.iconVal)); assert(curAssertion->op2.u1.iconFlags != GTF_EMPTY); } else if ((curAssertion->op1.kind == O1K_BOUND_OPER_BND) || (curAssertion->op1.kind == O1K_BOUND_LOOP_BND) || (curAssertion->op1.kind == O1K_CONSTANT_LOOP_BND) || (curAssertion->op1.kind == O1K_CONSTANT_LOOP_BND_UN)) { assert(!optLocalAssertionProp); vnStore->vnDump(this, curAssertion->op2.vn); } else { var_types op1Type; if (curAssertion->op1.kind == O1K_VALUE_NUMBER) { op1Type = vnStore->TypeOfVN(curAssertion->op1.vn); } else { unsigned lclNum = curAssertion->op1.lcl.lclNum; op1Type = lvaGetDesc(lclNum)->lvType; } if (op1Type == TYP_REF) { assert(curAssertion->op2.u1.iconVal == 0); printf("null"); } else { if ((curAssertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK) != 0) { printf("[%08p]", dspPtr(curAssertion->op2.u1.iconVal)); } else { printf("%d", curAssertion->op2.u1.iconVal); } } } break; case O2K_CONST_LONG: printf("0x%016llx", curAssertion->op2.lconVal); break; case O2K_CONST_DOUBLE: if (*((__int64*)&curAssertion->op2.dconVal) == (__int64)I64(0x8000000000000000)) { printf("-0.00000"); } else { printf("%#lg", curAssertion->op2.dconVal); } break; case O2K_ZEROOBJ: printf("ZeroObj"); break; case O2K_SUBRANGE: IntegralRange::Print(curAssertion->op2.u2); break; default: printf("?op2.kind?"); break; } } if (assertionIndex > 0) { printf(", index = "); optPrintAssertionIndex(assertionIndex); } printf("\n"); } void Compiler::optPrintAssertionIndex(AssertionIndex index) { if (index == NO_ASSERTION_INDEX) { printf("#NA"); return; } printf("#%02u", index); } void Compiler::optPrintAssertionIndices(ASSERT_TP assertions) { if (BitVecOps::IsEmpty(apTraits, assertions)) { optPrintAssertionIndex(NO_ASSERTION_INDEX); return; } BitVecOps::Iter iter(apTraits, assertions); unsigned bitIndex = 0; if (iter.NextElem(&bitIndex)) { optPrintAssertionIndex(static_cast<AssertionIndex>(bitIndex + 1)); while (iter.NextElem(&bitIndex)) { printf(" "); optPrintAssertionIndex(static_cast<AssertionIndex>(bitIndex + 1)); } } } #endif // DEBUG /* static */ void Compiler::optDumpAssertionIndices(const char* header, ASSERT_TP assertions, const char* footer /* = nullptr */) { #ifdef DEBUG Compiler* compiler = JitTls::GetCompiler(); if (compiler->verbose) { printf(header); compiler->optPrintAssertionIndices(assertions); if (footer != nullptr) { printf(footer); } } #endif // DEBUG } /* static */ void Compiler::optDumpAssertionIndices(ASSERT_TP assertions, const char* footer /* = nullptr */) { optDumpAssertionIndices("", assertions, footer); } /****************************************************************************** * * Helper to retrieve the "assertIndex" assertion. Note that assertIndex 0 * is NO_ASSERTION_INDEX and "optAssertionCount" is the last valid index. * */ Compiler::AssertionDsc* Compiler::optGetAssertion(AssertionIndex assertIndex) { assert(NO_ASSERTION_INDEX == 0); assert(assertIndex != NO_ASSERTION_INDEX); assert(assertIndex <= optAssertionCount); AssertionDsc* assertion = &optAssertionTabPrivate[assertIndex - 1]; #ifdef DEBUG optDebugCheckAssertion(assertion); #endif return assertion; } //------------------------------------------------------------------------ // optCreateAssertion: Create an (op1 assertionKind op2) assertion. // // Arguments: // op1 - the first assertion operand // op2 - the second assertion operand // assertionKind - the assertion kind // helperCallArgs - when true this indicates that the assertion operands // are the arguments of a type cast helper call such as // CORINFO_HELP_ISINSTANCEOFCLASS // Return Value: // The new assertion index or NO_ASSERTION_INDEX if a new assertion // was not created. // // Notes: // Assertion creation may fail either because the provided assertion // operands aren't supported or because the assertion table is full. // AssertionIndex Compiler::optCreateAssertion(GenTree* op1, GenTree* op2, optAssertionKind assertionKind, bool helperCallArgs) { assert(op1 != nullptr); assert(!helperCallArgs || (op2 != nullptr)); AssertionDsc assertion = {OAK_INVALID}; assert(assertion.assertionKind == OAK_INVALID); if (op1->OperIs(GT_BOUNDS_CHECK)) { if (assertionKind == OAK_NO_THROW) { GenTreeBoundsChk* arrBndsChk = op1->AsBoundsChk(); assertion.assertionKind = assertionKind; assertion.op1.kind = O1K_ARR_BND; assertion.op1.bnd.vnIdx = vnStore->VNConservativeNormalValue(arrBndsChk->GetIndex()->gtVNPair); assertion.op1.bnd.vnLen = vnStore->VNConservativeNormalValue(arrBndsChk->GetArrayLength()->gtVNPair); goto DONE_ASSERTION; } } // // Are we trying to make a non-null assertion? // if (op2 == nullptr) { // // Must be an OAK_NOT_EQUAL assertion // noway_assert(assertionKind == OAK_NOT_EQUAL); // // Set op1 to the instance pointer of the indirection // ssize_t offset = 0; while ((op1->gtOper == GT_ADD) && (op1->gtType == TYP_BYREF)) { if (op1->gtGetOp2()->IsCnsIntOrI()) { offset += op1->gtGetOp2()->AsIntCon()->gtIconVal; op1 = op1->gtGetOp1(); } else if (op1->gtGetOp1()->IsCnsIntOrI()) { offset += op1->gtGetOp1()->AsIntCon()->gtIconVal; op1 = op1->gtGetOp2(); } else { break; } } if (fgIsBigOffset(offset) || op1->gtOper != GT_LCL_VAR) { goto DONE_ASSERTION; // Don't make an assertion } unsigned lclNum = op1->AsLclVarCommon()->GetLclNum(); LclVarDsc* lclVar = lvaGetDesc(lclNum); ValueNum vn; // // We only perform null-checks on GC refs // so only make non-null assertions about GC refs or byrefs if we can't determine // the corresponding ref. // if (lclVar->TypeGet() != TYP_REF) { if (optLocalAssertionProp || (lclVar->TypeGet() != TYP_BYREF)) { goto DONE_ASSERTION; // Don't make an assertion } vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); VNFuncApp funcAttr; // Try to get value number corresponding to the GC ref of the indirection while (vnStore->GetVNFunc(vn, &funcAttr) && (funcAttr.m_func == (VNFunc)GT_ADD) && (vnStore->TypeOfVN(vn) == TYP_BYREF)) { if (vnStore->IsVNConstant(funcAttr.m_args[1]) && varTypeIsIntegral(vnStore->TypeOfVN(funcAttr.m_args[1]))) { offset += vnStore->CoercedConstantValue<ssize_t>(funcAttr.m_args[1]); vn = funcAttr.m_args[0]; } else if (vnStore->IsVNConstant(funcAttr.m_args[0]) && varTypeIsIntegral(vnStore->TypeOfVN(funcAttr.m_args[0]))) { offset += vnStore->CoercedConstantValue<ssize_t>(funcAttr.m_args[0]); vn = funcAttr.m_args[1]; } else { break; } } if (fgIsBigOffset(offset)) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op1.kind = O1K_VALUE_NUMBER; } else { // If the local variable has its address exposed then bail if (lclVar->IsAddressExposed()) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op1.kind = O1K_LCLVAR; assertion.op1.lcl.lclNum = lclNum; assertion.op1.lcl.ssaNum = op1->AsLclVarCommon()->GetSsaNum(); vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); } assertion.op1.vn = vn; assertion.assertionKind = assertionKind; assertion.op2.kind = O2K_CONST_INT; assertion.op2.vn = ValueNumStore::VNForNull(); assertion.op2.u1.iconVal = 0; assertion.op2.u1.iconFlags = GTF_EMPTY; #ifdef TARGET_64BIT assertion.op2.u1.iconFlags |= GTF_ASSERTION_PROP_LONG; // Signify that this is really TYP_LONG #endif // TARGET_64BIT } // // Are we making an assertion about a local variable? // else if (op1->gtOper == GT_LCL_VAR) { unsigned lclNum = op1->AsLclVarCommon()->GetLclNum(); LclVarDsc* lclVar = lvaGetDesc(lclNum); // If the local variable has its address exposed then bail if (lclVar->IsAddressExposed()) { goto DONE_ASSERTION; // Don't make an assertion } if (helperCallArgs) { // // Must either be an OAK_EQUAL or an OAK_NOT_EQUAL assertion // if ((assertionKind != OAK_EQUAL) && (assertionKind != OAK_NOT_EQUAL)) { goto DONE_ASSERTION; // Don't make an assertion } if (op2->gtOper == GT_IND) { op2 = op2->AsOp()->gtOp1; assertion.op2.kind = O2K_IND_CNS_INT; } else { assertion.op2.kind = O2K_CONST_INT; } if (op2->gtOper != GT_CNS_INT) { goto DONE_ASSERTION; // Don't make an assertion } // // TODO-CQ: Check for Sealed class and change kind to O1K_EXACT_TYPE // And consider the special cases, like CORINFO_FLG_SHAREDINST or CORINFO_FLG_VARIANCE // where a class can be sealed, but they don't behave as exact types because casts to // non-base types sometimes still succeed. // assertion.op1.kind = O1K_SUBTYPE; assertion.op1.lcl.lclNum = lclNum; assertion.op1.vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); assertion.op1.lcl.ssaNum = op1->AsLclVarCommon()->GetSsaNum(); assertion.op2.u1.iconVal = op2->AsIntCon()->gtIconVal; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); assertion.op2.u1.iconFlags = op2->GetIconHandleFlag(); // // Ok everything has been set and the assertion looks good // assertion.assertionKind = assertionKind; } else // !helperCallArgs { /* Skip over a GT_COMMA node(s), if necessary */ while (op2->gtOper == GT_COMMA) { op2 = op2->AsOp()->gtOp2; } assertion.op1.kind = O1K_LCLVAR; assertion.op1.lcl.lclNum = lclNum; assertion.op1.vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); assertion.op1.lcl.ssaNum = op1->AsLclVarCommon()->GetSsaNum(); switch (op2->gtOper) { optOp2Kind op2Kind; // // Constant Assertions // case GT_CNS_INT: if (varTypeIsStruct(op1)) { assert(op2->IsIntegralConst(0)); op2Kind = O2K_ZEROOBJ; } else { op2Kind = O2K_CONST_INT; } goto CNS_COMMON; case GT_CNS_LNG: op2Kind = O2K_CONST_LONG; goto CNS_COMMON; case GT_CNS_DBL: op2Kind = O2K_CONST_DOUBLE; goto CNS_COMMON; CNS_COMMON: { // // Must either be an OAK_EQUAL or an OAK_NOT_EQUAL assertion // if ((assertionKind != OAK_EQUAL) && (assertionKind != OAK_NOT_EQUAL)) { goto DONE_ASSERTION; // Don't make an assertion } // If the LclVar is a TYP_LONG then we only make // assertions where op2 is also TYP_LONG // if ((lclVar->TypeGet() == TYP_LONG) && (op2->TypeGet() != TYP_LONG)) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op2.kind = op2Kind; assertion.op2.lconVal = 0; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); if (op2->gtOper == GT_CNS_INT) { #ifdef TARGET_ARM // Do not Constant-Prop large constants for ARM // TODO-CrossBitness: we wouldn't need the cast below if GenTreeIntCon::gtIconVal had // target_ssize_t type. if (!codeGen->validImmForMov((target_ssize_t)op2->AsIntCon()->gtIconVal)) { goto DONE_ASSERTION; // Don't make an assertion } #endif // TARGET_ARM assertion.op2.u1.iconVal = op2->AsIntCon()->gtIconVal; assertion.op2.u1.iconFlags = op2->GetIconHandleFlag(); #ifdef TARGET_64BIT if (op2->TypeGet() == TYP_LONG || op2->TypeGet() == TYP_BYREF) { assertion.op2.u1.iconFlags |= GTF_ASSERTION_PROP_LONG; // Signify that this is really TYP_LONG } #endif // TARGET_64BIT } else if (op2->gtOper == GT_CNS_LNG) { assertion.op2.lconVal = op2->AsLngCon()->gtLconVal; } else { noway_assert(op2->gtOper == GT_CNS_DBL); /* If we have an NaN value then don't record it */ if (_isnan(op2->AsDblCon()->gtDconVal)) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op2.dconVal = op2->AsDblCon()->gtDconVal; } // // Ok everything has been set and the assertion looks good // assertion.assertionKind = assertionKind; goto DONE_ASSERTION; } // // Copy Assertions // case GT_LCL_VAR: { // // Must either be an OAK_EQUAL or an OAK_NOT_EQUAL assertion // if ((assertionKind != OAK_EQUAL) && (assertionKind != OAK_NOT_EQUAL)) { goto DONE_ASSERTION; // Don't make an assertion } unsigned lclNum2 = op2->AsLclVarCommon()->GetLclNum(); LclVarDsc* lclVar2 = lvaGetDesc(lclNum2); // If the two locals are the same then bail if (lclNum == lclNum2) { goto DONE_ASSERTION; // Don't make an assertion } // If the types are different then bail */ if (lclVar->lvType != lclVar2->lvType) { goto DONE_ASSERTION; // Don't make an assertion } // If we're making a copy of a "normalize on load" lclvar then the destination // has to be "normalize on load" as well, otherwise we risk skipping normalization. if (lclVar2->lvNormalizeOnLoad() && !lclVar->lvNormalizeOnLoad()) { goto DONE_ASSERTION; // Don't make an assertion } // If the local variable has its address exposed then bail if (lclVar2->IsAddressExposed()) { goto DONE_ASSERTION; // Don't make an assertion } FieldSeqNode* zeroOffsetFieldSeq = nullptr; GetZeroOffsetFieldMap()->Lookup(op2, &zeroOffsetFieldSeq); assertion.op2.kind = O2K_LCLVAR_COPY; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); assertion.op2.lcl.lclNum = lclNum2; assertion.op2.lcl.ssaNum = op2->AsLclVarCommon()->GetSsaNum(); assertion.op2.zeroOffsetFieldSeq = zeroOffsetFieldSeq; // Ok everything has been set and the assertion looks good assertion.assertionKind = assertionKind; goto DONE_ASSERTION; } default: break; } // Try and see if we can make a subrange assertion. if (((assertionKind == OAK_SUBRANGE) || (assertionKind == OAK_EQUAL)) && varTypeIsIntegral(op2)) { IntegralRange nodeRange = IntegralRange::ForNode(op2, this); IntegralRange typeRange = IntegralRange::ForType(genActualType(op2)); assert(typeRange.Contains(nodeRange)); if (!typeRange.Equals(nodeRange)) { assertion.op2.kind = O2K_SUBRANGE; assertion.assertionKind = OAK_SUBRANGE; assertion.op2.u2 = nodeRange; } } } } // // Are we making an IsType assertion? // else if (op1->gtOper == GT_IND) { op1 = op1->AsOp()->gtOp1; // // Is this an indirection of a local variable? // if (op1->gtOper == GT_LCL_VAR) { unsigned lclNum = op1->AsLclVarCommon()->GetLclNum(); // If the local variable is not in SSA then bail if (!lvaInSsa(lclNum)) { goto DONE_ASSERTION; } // If we have an typeHnd indirection then op1 must be a TYP_REF // and the indirection must produce a TYP_I // if (op1->gtType != TYP_REF) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op1.kind = O1K_EXACT_TYPE; assertion.op1.lcl.lclNum = lclNum; assertion.op1.vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); assertion.op1.lcl.ssaNum = op1->AsLclVarCommon()->GetSsaNum(); assert((assertion.op1.lcl.ssaNum == SsaConfig::RESERVED_SSA_NUM) || (assertion.op1.vn == vnStore->VNConservativeNormalValue( lvaGetDesc(lclNum)->GetPerSsaData(assertion.op1.lcl.ssaNum)->m_vnPair))); ssize_t cnsValue = 0; GenTreeFlags iconFlags = GTF_EMPTY; // Ngen case if (op2->gtOper == GT_IND) { if (!optIsTreeKnownIntValue(!optLocalAssertionProp, op2->AsOp()->gtOp1, &cnsValue, &iconFlags)) { goto DONE_ASSERTION; // Don't make an assertion } assertion.assertionKind = assertionKind; assertion.op2.kind = O2K_IND_CNS_INT; assertion.op2.u1.iconVal = cnsValue; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->AsOp()->gtOp1->gtVNPair); /* iconFlags should only contain bits in GTF_ICON_HDL_MASK */ assert((iconFlags & ~GTF_ICON_HDL_MASK) == 0); assertion.op2.u1.iconFlags = iconFlags; #ifdef TARGET_64BIT if (op2->AsOp()->gtOp1->TypeGet() == TYP_LONG) { assertion.op2.u1.iconFlags |= GTF_ASSERTION_PROP_LONG; // Signify that this is really TYP_LONG } #endif // TARGET_64BIT } // JIT case else if (optIsTreeKnownIntValue(!optLocalAssertionProp, op2, &cnsValue, &iconFlags)) { assertion.assertionKind = assertionKind; assertion.op2.kind = O2K_CONST_INT; assertion.op2.u1.iconVal = cnsValue; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); /* iconFlags should only contain bits in GTF_ICON_HDL_MASK */ assert((iconFlags & ~GTF_ICON_HDL_MASK) == 0); assertion.op2.u1.iconFlags = iconFlags; #ifdef TARGET_64BIT if (op2->TypeGet() == TYP_LONG) { assertion.op2.u1.iconFlags |= GTF_ASSERTION_PROP_LONG; // Signify that this is really TYP_LONG } #endif // TARGET_64BIT } else { goto DONE_ASSERTION; // Don't make an assertion } } } DONE_ASSERTION: return optFinalizeCreatingAssertion(&assertion); } //------------------------------------------------------------------------ // optFinalizeCreatingAssertion: Add the assertion, if well-formed, to the table. // // Checks that in global assertion propagation assertions do not have missing // value and SSA numbers. // // Arguments: // assertion - assertion to check and add to the table // // Return Value: // Index of the assertion if it was successfully created, NO_ASSERTION_INDEX otherwise. // AssertionIndex Compiler::optFinalizeCreatingAssertion(AssertionDsc* assertion) { if (assertion->assertionKind == OAK_INVALID) { return NO_ASSERTION_INDEX; } if (!optLocalAssertionProp) { if ((assertion->op1.vn == ValueNumStore::NoVN) || (assertion->op2.vn == ValueNumStore::NoVN) || (assertion->op1.vn == ValueNumStore::VNForVoid()) || (assertion->op2.vn == ValueNumStore::VNForVoid())) { return NO_ASSERTION_INDEX; } // TODO: only copy assertions rely on valid SSA number so we could generate more assertions here if ((assertion->op1.kind != O1K_VALUE_NUMBER) && (assertion->op1.lcl.ssaNum == SsaConfig::RESERVED_SSA_NUM)) { return NO_ASSERTION_INDEX; } } // Now add the assertion to our assertion table noway_assert(assertion->op1.kind != O1K_INVALID); noway_assert((assertion->op1.kind == O1K_ARR_BND) || (assertion->op2.kind != O2K_INVALID)); return optAddAssertion(assertion); } /***************************************************************************** * * If tree is a constant node holding an integral value, retrieve the value in * pConstant. If the method returns true, pConstant holds the appropriate * constant. Set "vnBased" to true to indicate local or global assertion prop. * "pFlags" indicates if the constant is a handle marked by GTF_ICON_HDL_MASK. */ bool Compiler::optIsTreeKnownIntValue(bool vnBased, GenTree* tree, ssize_t* pConstant, GenTreeFlags* pFlags) { // Is Local assertion prop? if (!vnBased) { if (tree->OperGet() == GT_CNS_INT) { *pConstant = tree->AsIntCon()->IconValue(); *pFlags = tree->GetIconHandleFlag(); return true; } #ifdef TARGET_64BIT // Just to be clear, get it from gtLconVal rather than // overlapping gtIconVal. else if (tree->OperGet() == GT_CNS_LNG) { *pConstant = tree->AsLngCon()->gtLconVal; *pFlags = tree->GetIconHandleFlag(); return true; } #endif return false; } // Global assertion prop ValueNum vn = vnStore->VNConservativeNormalValue(tree->gtVNPair); if (!vnStore->IsVNConstant(vn)) { return false; } // ValueNumber 'vn' indicates that this node evaluates to a constant var_types vnType = vnStore->TypeOfVN(vn); if (vnType == TYP_INT) { *pConstant = vnStore->ConstantValue<int>(vn); *pFlags = vnStore->IsVNHandle(vn) ? vnStore->GetHandleFlags(vn) : GTF_EMPTY; return true; } #ifdef TARGET_64BIT else if (vnType == TYP_LONG) { *pConstant = vnStore->ConstantValue<INT64>(vn); *pFlags = vnStore->IsVNHandle(vn) ? vnStore->GetHandleFlags(vn) : GTF_EMPTY; return true; } #endif return false; } #ifdef DEBUG /***************************************************************************** * * Print the assertions related to a VN for all VNs. * */ void Compiler::optPrintVnAssertionMapping() { printf("\nVN Assertion Mapping\n"); printf("---------------------\n"); for (ValueNumToAssertsMap::KeyIterator ki = optValueNumToAsserts->Begin(); !ki.Equal(optValueNumToAsserts->End()); ++ki) { printf("(%d => ", ki.Get()); printf("%s)\n", BitVecOps::ToString(apTraits, ki.GetValue())); } } #endif /***************************************************************************** * * Maintain a map "optValueNumToAsserts" i.e., vn -> to set of assertions * about that VN. Given "assertions" about a "vn" add it to the previously * mapped assertions about that "vn." */ void Compiler::optAddVnAssertionMapping(ValueNum vn, AssertionIndex index) { ASSERT_TP* cur = optValueNumToAsserts->LookupPointer(vn); if (cur == nullptr) { optValueNumToAsserts->Set(vn, BitVecOps::MakeSingleton(apTraits, index - 1)); } else { BitVecOps::AddElemD(apTraits, *cur, index - 1); } } /***************************************************************************** * Statically if we know that this assertion's VN involves a NaN don't bother * wasting an assertion table slot. */ bool Compiler::optAssertionVnInvolvesNan(AssertionDsc* assertion) { if (optLocalAssertionProp) { return false; } static const int SZ = 2; ValueNum vns[SZ] = {assertion->op1.vn, assertion->op2.vn}; for (int i = 0; i < SZ; ++i) { if (vnStore->IsVNConstant(vns[i])) { var_types type = vnStore->TypeOfVN(vns[i]); if ((type == TYP_FLOAT && _isnan(vnStore->ConstantValue<float>(vns[i])) != 0) || (type == TYP_DOUBLE && _isnan(vnStore->ConstantValue<double>(vns[i])) != 0)) { return true; } } } return false; } /***************************************************************************** * * Given an assertion add it to the assertion table * * If it is already in the assertion table return the assertionIndex that * we use to refer to this element. * Otherwise add it to the assertion table ad return the assertionIndex that * we use to refer to this element. * If we need to add to the table and the table is full return the value zero */ AssertionIndex Compiler::optAddAssertion(AssertionDsc* newAssertion) { noway_assert(newAssertion->assertionKind != OAK_INVALID); // Even though the propagation step takes care of NaN, just a check // to make sure there is no slot involving a NaN. if (optAssertionVnInvolvesNan(newAssertion)) { JITDUMP("Assertion involved Nan not adding\n"); return NO_ASSERTION_INDEX; } // Check if exists already, so we can skip adding new one. Search backwards. for (AssertionIndex index = optAssertionCount; index >= 1; index--) { AssertionDsc* curAssertion = optGetAssertion(index); if (curAssertion->Equals(newAssertion, !optLocalAssertionProp)) { return index; } } // Check if we are within max count. if (optAssertionCount >= optMaxAssertionCount) { return NO_ASSERTION_INDEX; } optAssertionTabPrivate[optAssertionCount] = *newAssertion; optAssertionCount++; #ifdef DEBUG if (verbose) { printf("GenTreeNode creates assertion:\n"); gtDispTree(optAssertionPropCurrentTree, nullptr, nullptr, true); printf(optLocalAssertionProp ? "In " FMT_BB " New Local " : "In " FMT_BB " New Global ", compCurBB->bbNum); optPrintAssertion(newAssertion, optAssertionCount); } #endif // DEBUG // Assertion mask bits are [index + 1]. if (optLocalAssertionProp) { assert(newAssertion->op1.kind == O1K_LCLVAR); // Mark the variables this index depends on unsigned lclNum = newAssertion->op1.lcl.lclNum; BitVecOps::AddElemD(apTraits, GetAssertionDep(lclNum), optAssertionCount - 1); if (newAssertion->op2.kind == O2K_LCLVAR_COPY) { lclNum = newAssertion->op2.lcl.lclNum; BitVecOps::AddElemD(apTraits, GetAssertionDep(lclNum), optAssertionCount - 1); } } else // If global assertion prop, then add it to the dependents map. { optAddVnAssertionMapping(newAssertion->op1.vn, optAssertionCount); if (newAssertion->op2.kind == O2K_LCLVAR_COPY) { optAddVnAssertionMapping(newAssertion->op2.vn, optAssertionCount); } } #ifdef DEBUG optDebugCheckAssertions(optAssertionCount); #endif return optAssertionCount; } #ifdef DEBUG void Compiler::optDebugCheckAssertion(AssertionDsc* assertion) { assert(assertion->assertionKind < OAK_COUNT); assert(assertion->op1.kind < O1K_COUNT); assert(assertion->op2.kind < O2K_COUNT); // It would be good to check that op1.vn and op2.vn are valid value numbers. switch (assertion->op1.kind) { case O1K_LCLVAR: case O1K_EXACT_TYPE: case O1K_SUBTYPE: assert(optLocalAssertionProp || lvaGetDesc(assertion->op1.lcl.lclNum)->lvPerSsaData.IsValidSsaNum(assertion->op1.lcl.ssaNum)); break; case O1K_ARR_BND: // It would be good to check that bnd.vnIdx and bnd.vnLen are valid value numbers. break; case O1K_BOUND_OPER_BND: case O1K_BOUND_LOOP_BND: case O1K_CONSTANT_LOOP_BND: case O1K_CONSTANT_LOOP_BND_UN: case O1K_VALUE_NUMBER: assert(!optLocalAssertionProp); break; default: break; } switch (assertion->op2.kind) { case O2K_IND_CNS_INT: case O2K_CONST_INT: { // The only flags that can be set are those in the GTF_ICON_HDL_MASK, or GTF_ASSERTION_PROP_LONG, which is // used to indicate a long constant. #ifdef TARGET_64BIT assert((assertion->op2.u1.iconFlags & ~(GTF_ICON_HDL_MASK | GTF_ASSERTION_PROP_LONG)) == 0); #else assert((assertion->op2.u1.iconFlags & ~GTF_ICON_HDL_MASK) == 0); #endif switch (assertion->op1.kind) { case O1K_EXACT_TYPE: case O1K_SUBTYPE: assert(assertion->op2.u1.iconFlags != GTF_EMPTY); break; case O1K_LCLVAR: assert((lvaGetDesc(assertion->op1.lcl.lclNum)->lvType != TYP_REF) || (assertion->op2.u1.iconVal == 0) || doesMethodHaveFrozenString()); break; case O1K_VALUE_NUMBER: assert((vnStore->TypeOfVN(assertion->op1.vn) != TYP_REF) || (assertion->op2.u1.iconVal == 0)); break; default: break; } } break; case O2K_CONST_LONG: { // All handles should be represented by O2K_CONST_INT, // so no handle bits should be set here. assert((assertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK) == 0); } break; case O2K_ZEROOBJ: { // We only make these assertion for assignments (not control flow). assert(assertion->assertionKind == OAK_EQUAL); // We use "optLocalAssertionIsEqualOrNotEqual" to find these. assert(assertion->op2.u1.iconVal == 0); } break; default: // for all other 'assertion->op2.kind' values we don't check anything break; } } /***************************************************************************** * * Verify that assertion prop related assumptions are valid. If "index" * is 0 (i.e., NO_ASSERTION_INDEX) then verify all assertions in the table. * If "index" is between 1 and optAssertionCount, then verify the assertion * desc corresponding to "index." */ void Compiler::optDebugCheckAssertions(AssertionIndex index) { AssertionIndex start = (index == NO_ASSERTION_INDEX) ? 1 : index; AssertionIndex end = (index == NO_ASSERTION_INDEX) ? optAssertionCount : index; for (AssertionIndex ind = start; ind <= end; ++ind) { AssertionDsc* assertion = optGetAssertion(ind); optDebugCheckAssertion(assertion); } } #endif //------------------------------------------------------------------------ // optCreateComplementaryAssertion: Create an assertion that is the complementary // of the specified assertion. // // Arguments: // assertionIndex - the index of the assertion // op1 - the first assertion operand // op2 - the second assertion operand // helperCallArgs - when true this indicates that the assertion operands // are the arguments of a type cast helper call such as // CORINFO_HELP_ISINSTANCEOFCLASS // // Notes: // The created complementary assertion is associated with the original // assertion such that it can be found by optFindComplementary. // void Compiler::optCreateComplementaryAssertion(AssertionIndex assertionIndex, GenTree* op1, GenTree* op2, bool helperCallArgs) { if (assertionIndex == NO_ASSERTION_INDEX) { return; } AssertionDsc& candidateAssertion = *optGetAssertion(assertionIndex); if ((candidateAssertion.op1.kind == O1K_BOUND_OPER_BND) || (candidateAssertion.op1.kind == O1K_BOUND_LOOP_BND) || (candidateAssertion.op1.kind == O1K_CONSTANT_LOOP_BND) || (candidateAssertion.op1.kind == O1K_CONSTANT_LOOP_BND_UN)) { AssertionDsc dsc = candidateAssertion; dsc.assertionKind = dsc.assertionKind == OAK_EQUAL ? OAK_NOT_EQUAL : OAK_EQUAL; optAddAssertion(&dsc); return; } if (candidateAssertion.assertionKind == OAK_EQUAL) { AssertionIndex index = optCreateAssertion(op1, op2, OAK_NOT_EQUAL, helperCallArgs); optMapComplementary(index, assertionIndex); } else if (candidateAssertion.assertionKind == OAK_NOT_EQUAL) { AssertionIndex index = optCreateAssertion(op1, op2, OAK_EQUAL, helperCallArgs); optMapComplementary(index, assertionIndex); } // Are we making a subtype or exact type assertion? if ((candidateAssertion.op1.kind == O1K_SUBTYPE) || (candidateAssertion.op1.kind == O1K_EXACT_TYPE)) { optCreateAssertion(op1, nullptr, OAK_NOT_EQUAL); } } // optAssertionGenCast: Create a tentative subrange assertion for a cast. // // This function will try to create an assertion that the cast's operand // is within the "input" range for the cast, so that this assertion can // later be proven via implication and the cast removed. Such assertions // are only generated during global propagation, and only for LCL_VARs. // // Arguments: // cast - the cast node for which to create the assertion // // Return Value: // Index of the generated assertion, or NO_ASSERTION_INDEX if it was not // legal, profitable, or possible to create one. // AssertionIndex Compiler::optAssertionGenCast(GenTreeCast* cast) { if (optLocalAssertionProp || !varTypeIsIntegral(cast) || !varTypeIsIntegral(cast->CastOp())) { return NO_ASSERTION_INDEX; } // This condition exists to preverve previous behavior. if (!cast->CastOp()->OperIs(GT_LCL_VAR)) { return NO_ASSERTION_INDEX; } GenTreeLclVar* lclVar = cast->CastOp()->AsLclVar(); LclVarDsc* varDsc = lvaGetDesc(lclVar); // It is not useful to make assertions about address-exposed variables, they will never be proven. if (varDsc->IsAddressExposed()) { return NO_ASSERTION_INDEX; } // A representation-changing cast cannot be simplified if it is not checked. if (!cast->gtOverflow() && (genActualType(cast) != genActualType(lclVar))) { return NO_ASSERTION_INDEX; } AssertionDsc assertion = {OAK_SUBRANGE}; assertion.op1.kind = O1K_LCLVAR; assertion.op1.vn = vnStore->VNConservativeNormalValue(lclVar->gtVNPair); assertion.op1.lcl.lclNum = lclVar->GetLclNum(); assertion.op1.lcl.ssaNum = lclVar->GetSsaNum(); assertion.op2.kind = O2K_SUBRANGE; assertion.op2.u2 = IntegralRange::ForCastInput(cast); return optFinalizeCreatingAssertion(&assertion); } //------------------------------------------------------------------------ // optCreateJtrueAssertions: Create assertions about a JTRUE's relop operands. // // Arguments: // op1 - the first assertion operand // op2 - the second assertion operand // assertionKind - the assertion kind // helperCallArgs - when true this indicates that the assertion operands // are the arguments of a type cast helper call such as // CORINFO_HELP_ISINSTANCEOFCLASS // Return Value: // The new assertion index or NO_ASSERTION_INDEX if a new assertion // was not created. // // Notes: // Assertion creation may fail either because the provided assertion // operands aren't supported or because the assertion table is full. // If an assertion is created succesfully then an attempt is made to also // create a second, complementary assertion. This may too fail, for the // same reasons as the first one. // AssertionIndex Compiler::optCreateJtrueAssertions(GenTree* op1, GenTree* op2, Compiler::optAssertionKind assertionKind, bool helperCallArgs) { AssertionIndex assertionIndex = optCreateAssertion(op1, op2, assertionKind, helperCallArgs); // Don't bother if we don't have an assertion on the JTrue False path. Current implementation // allows for a complementary only if there is an assertion on the False path (tree->HasAssertion()). if (assertionIndex != NO_ASSERTION_INDEX) { optCreateComplementaryAssertion(assertionIndex, op1, op2, helperCallArgs); } return assertionIndex; } AssertionInfo Compiler::optCreateJTrueBoundsAssertion(GenTree* tree) { GenTree* relop = tree->gtGetOp1(); if (!relop->OperIsCompare()) { return NO_ASSERTION_INDEX; } GenTree* op1 = relop->gtGetOp1(); GenTree* op2 = relop->gtGetOp2(); ValueNum op1VN = vnStore->VNConservativeNormalValue(op1->gtVNPair); ValueNum op2VN = vnStore->VNConservativeNormalValue(op2->gtVNPair); ValueNum relopVN = vnStore->VNConservativeNormalValue(relop->gtVNPair); bool hasTestAgainstZero = (relop->gtOper == GT_EQ || relop->gtOper == GT_NE) && (op2VN == vnStore->VNZeroForType(op2->TypeGet())); ValueNumStore::UnsignedCompareCheckedBoundInfo unsignedCompareBnd; // Cases where op1 holds the upper bound arithmetic and op2 is 0. // Loop condition like: "i < bnd +/-k == 0" // Assertion: "i < bnd +/- k == 0" if (hasTestAgainstZero && vnStore->IsVNCompareCheckedBoundArith(op1VN)) { AssertionDsc dsc; dsc.assertionKind = relop->gtOper == GT_EQ ? OAK_EQUAL : OAK_NOT_EQUAL; dsc.op1.kind = O1K_BOUND_OPER_BND; dsc.op1.vn = op1VN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(op2->TypeGet()); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Cases where op1 holds the lhs of the condition and op2 holds the bound arithmetic. // Loop condition like: "i < bnd +/-k" // Assertion: "i < bnd +/- k != 0" else if (vnStore->IsVNCompareCheckedBoundArith(relopVN)) { AssertionDsc dsc; dsc.assertionKind = OAK_NOT_EQUAL; dsc.op1.kind = O1K_BOUND_OPER_BND; dsc.op1.vn = relopVN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(op2->TypeGet()); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Cases where op1 holds the upper bound and op2 is 0. // Loop condition like: "i < bnd == 0" // Assertion: "i < bnd == false" else if (hasTestAgainstZero && vnStore->IsVNCompareCheckedBound(op1VN)) { AssertionDsc dsc; dsc.assertionKind = relop->gtOper == GT_EQ ? OAK_EQUAL : OAK_NOT_EQUAL; dsc.op1.kind = O1K_BOUND_LOOP_BND; dsc.op1.vn = op1VN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(op2->TypeGet()); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Cases where op1 holds the lhs of the condition op2 holds the bound. // Loop condition like "i < bnd" // Assertion: "i < bnd != 0" else if (vnStore->IsVNCompareCheckedBound(relopVN)) { AssertionDsc dsc; dsc.assertionKind = OAK_NOT_EQUAL; dsc.op1.kind = O1K_BOUND_LOOP_BND; dsc.op1.vn = relopVN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(TYP_INT); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Loop condition like "(uint)i < (uint)bnd" or equivalent // Assertion: "no throw" since this condition guarantees that i is both >= 0 and < bnd (on the appropiate edge) else if (vnStore->IsVNUnsignedCompareCheckedBound(relopVN, &unsignedCompareBnd)) { assert(unsignedCompareBnd.vnIdx != ValueNumStore::NoVN); assert((unsignedCompareBnd.cmpOper == VNF_LT_UN) || (unsignedCompareBnd.cmpOper == VNF_GE_UN)); assert(vnStore->IsVNCheckedBound(unsignedCompareBnd.vnBound)); AssertionDsc dsc; dsc.assertionKind = OAK_NO_THROW; dsc.op1.kind = O1K_ARR_BND; dsc.op1.vn = relopVN; dsc.op1.bnd.vnIdx = unsignedCompareBnd.vnIdx; dsc.op1.bnd.vnLen = vnStore->VNNormalValue(unsignedCompareBnd.vnBound); dsc.op2.kind = O2K_INVALID; dsc.op2.vn = ValueNumStore::NoVN; AssertionIndex index = optAddAssertion(&dsc); if (unsignedCompareBnd.cmpOper == VNF_GE_UN) { // By default JTRUE generated assertions hold on the "jump" edge. We have i >= bnd but we're really // after i < bnd so we need to change the assertion edge to "next". return AssertionInfo::ForNextEdge(index); } return index; } // Cases where op1 holds the condition bound check and op2 is 0. // Loop condition like: "i < 100 == 0" // Assertion: "i < 100 == false" else if (hasTestAgainstZero && vnStore->IsVNConstantBound(op1VN)) { AssertionDsc dsc; dsc.assertionKind = relop->gtOper == GT_EQ ? OAK_EQUAL : OAK_NOT_EQUAL; dsc.op1.kind = O1K_CONSTANT_LOOP_BND; dsc.op1.vn = op1VN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(op2->TypeGet()); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Cases where op1 holds the lhs of the condition op2 holds rhs. // Loop condition like "i < 100" // Assertion: "i < 100 != 0" else if (vnStore->IsVNConstantBound(relopVN)) { AssertionDsc dsc; dsc.assertionKind = OAK_NOT_EQUAL; dsc.op1.kind = O1K_CONSTANT_LOOP_BND; dsc.op1.vn = relopVN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(TYP_INT); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } else if (vnStore->IsVNConstantBoundUnsigned(relopVN)) { AssertionDsc dsc; dsc.assertionKind = OAK_NOT_EQUAL; dsc.op1.kind = O1K_CONSTANT_LOOP_BND_UN; dsc.op1.vn = relopVN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(TYP_INT); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Compute assertions for the JTrue node. */ AssertionInfo Compiler::optAssertionGenJtrue(GenTree* tree) { // Only create assertions for JTRUE when we are in the global phase if (optLocalAssertionProp) { return NO_ASSERTION_INDEX; } GenTree* relop = tree->AsOp()->gtOp1; if (!relop->OperIsCompare()) { return NO_ASSERTION_INDEX; } Compiler::optAssertionKind assertionKind = OAK_INVALID; AssertionInfo info = optCreateJTrueBoundsAssertion(tree); if (info.HasAssertion()) { return info; } // Find assertion kind. switch (relop->gtOper) { case GT_EQ: assertionKind = OAK_EQUAL; break; case GT_NE: assertionKind = OAK_NOT_EQUAL; break; default: // TODO-CQ: add other relop operands. Disabled for now to measure perf // and not occupy assertion table slots. We'll add them when used. return NO_ASSERTION_INDEX; } // Look through any CSEs so we see the actual trees providing values, if possible. // This is important for exact type assertions, which need to see the GT_IND. // GenTree* op1 = relop->AsOp()->gtOp1->gtCommaAssignVal(); GenTree* op2 = relop->AsOp()->gtOp2->gtCommaAssignVal(); // Check for op1 or op2 to be lcl var and if so, keep it in op1. if ((op1->gtOper != GT_LCL_VAR) && (op2->gtOper == GT_LCL_VAR)) { std::swap(op1, op2); } ValueNum op1VN = vnStore->VNConservativeNormalValue(op1->gtVNPair); ValueNum op2VN = vnStore->VNConservativeNormalValue(op2->gtVNPair); // If op1 is lcl and op2 is const or lcl, create assertion. if ((op1->gtOper == GT_LCL_VAR) && (op2->OperIsConst() || (op2->gtOper == GT_LCL_VAR))) // Fix for Dev10 851483 { return optCreateJtrueAssertions(op1, op2, assertionKind); } else if (vnStore->IsVNCheckedBound(op1VN) && vnStore->IsVNInt32Constant(op2VN)) { assert(relop->OperIs(GT_EQ, GT_NE)); int con = vnStore->ConstantValue<int>(op2VN); if (con >= 0) { AssertionDsc dsc; // For arr.Length != 0, we know that 0 is a valid index // For arr.Length == con, we know that con - 1 is the greatest valid index if (con == 0) { dsc.assertionKind = OAK_NOT_EQUAL; dsc.op1.bnd.vnIdx = vnStore->VNForIntCon(0); } else { dsc.assertionKind = OAK_EQUAL; dsc.op1.bnd.vnIdx = vnStore->VNForIntCon(con - 1); } dsc.op1.vn = op1VN; dsc.op1.kind = O1K_ARR_BND; dsc.op1.bnd.vnLen = op1VN; dsc.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); dsc.op2.kind = O2K_CONST_INT; dsc.op2.u1.iconFlags = GTF_EMPTY; dsc.op2.u1.iconVal = 0; // when con is not zero, create an assertion on the arr.Length == con edge // when con is zero, create an assertion on the arr.Length != 0 edge AssertionIndex index = optAddAssertion(&dsc); if (relop->OperIs(GT_NE) != (con == 0)) { return AssertionInfo::ForNextEdge(index); } else { return index; } } } // Check op1 and op2 for an indirection of a GT_LCL_VAR and keep it in op1. if (((op1->gtOper != GT_IND) || (op1->AsOp()->gtOp1->gtOper != GT_LCL_VAR)) && ((op2->gtOper == GT_IND) && (op2->AsOp()->gtOp1->gtOper == GT_LCL_VAR))) { std::swap(op1, op2); } // If op1 is ind, then extract op1's oper. if ((op1->gtOper == GT_IND) && (op1->AsOp()->gtOp1->gtOper == GT_LCL_VAR)) { return optCreateJtrueAssertions(op1, op2, assertionKind); } // Look for a call to an IsInstanceOf helper compared to a nullptr if ((op2->gtOper != GT_CNS_INT) && (op1->gtOper == GT_CNS_INT)) { std::swap(op1, op2); } // Validate op1 and op2 if ((op1->gtOper != GT_CALL) || (op1->AsCall()->gtCallType != CT_HELPER) || (op1->TypeGet() != TYP_REF) || // op1 (op2->gtOper != GT_CNS_INT) || (op2->AsIntCon()->gtIconVal != 0)) // op2 { return NO_ASSERTION_INDEX; } GenTreeCall* call = op1->AsCall(); // Note CORINFO_HELP_READYTORUN_ISINSTANCEOF does not have the same argument pattern. // In particular, it is not possible to deduce what class is being tested from its args. // // Also note The CASTCLASS helpers won't appear in predicates as they throw on failure. // So the helper list here is smaller than the one in optAssertionProp_Call. if ((call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFINTERFACE)) || (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFARRAY)) || (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFCLASS)) || (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFANY))) { fgArgInfo* const argInfo = call->fgArgInfo; GenTree* objectNode = argInfo->GetArgNode(1); GenTree* methodTableNode = argInfo->GetArgNode(0); assert(objectNode->TypeGet() == TYP_REF); assert(methodTableNode->TypeGet() == TYP_I_IMPL); // Reverse the assertion assert((assertionKind == OAK_EQUAL) || (assertionKind == OAK_NOT_EQUAL)); assertionKind = (assertionKind == OAK_EQUAL) ? OAK_NOT_EQUAL : OAK_EQUAL; if (objectNode->OperIs(GT_LCL_VAR)) { return optCreateJtrueAssertions(objectNode, methodTableNode, assertionKind, /* helperCallArgs */ true); } } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Create an assertion on the phi node if some information can be gleaned * from all of the constituent phi operands. * */ AssertionIndex Compiler::optAssertionGenPhiDefn(GenTree* tree) { if (!tree->IsPhiDefn()) { return NO_ASSERTION_INDEX; } // Try to find if all phi arguments are known to be non-null. bool isNonNull = true; for (GenTreePhi::Use& use : tree->AsOp()->gtGetOp2()->AsPhi()->Uses()) { if (!vnStore->IsKnownNonNull(use.GetNode()->gtVNPair.GetConservative())) { isNonNull = false; break; } } // All phi arguments are non-null implies phi rhs is non-null. if (isNonNull) { return optCreateAssertion(tree->AsOp()->gtOp1, nullptr, OAK_NOT_EQUAL); } return NO_ASSERTION_INDEX; } /***************************************************************************** * * If this statement creates a value assignment or assertion * then assign an index to the given value assignment by adding * it to the lookup table, if necessary. */ void Compiler::optAssertionGen(GenTree* tree) { tree->ClearAssertion(); // If there are QMARKs in the IR, we won't generate assertions // for conditionally executed code. // if (optLocalAssertionProp && ((tree->gtFlags & GTF_COLON_COND) != 0)) { return; } #ifdef DEBUG optAssertionPropCurrentTree = tree; #endif // For most of the assertions that we create below // the assertion is true after the tree is processed bool assertionProven = true; AssertionInfo assertionInfo; switch (tree->gtOper) { case GT_ASG: // An indirect store - we can create a non-null assertion. Note that we do not lose out // on the dataflow assertions here as local propagation only deals with LCL_VAR LHSs. if (tree->AsOp()->gtGetOp1()->OperIsIndir()) { assertionInfo = optCreateAssertion(tree->AsOp()->gtGetOp1()->AsIndir()->Addr(), nullptr, OAK_NOT_EQUAL); } // VN takes care of non local assertions for assignments and data flow. else if (optLocalAssertionProp) { assertionInfo = optCreateAssertion(tree->AsOp()->gtOp1, tree->AsOp()->gtOp2, OAK_EQUAL); } else { assertionInfo = optAssertionGenPhiDefn(tree); } break; case GT_OBJ: case GT_BLK: case GT_IND: // R-value indirections create non-null assertions, but not all indirections are R-values. // Those under ADDR nodes or on the LHS of ASGs are "locations", and will not end up // dereferencing their operands. We cannot reliably detect them here, however, and so // will have to rely on the conservative approximation of the GTF_NO_CSE flag. if (tree->CanCSE()) { assertionInfo = optCreateAssertion(tree->AsIndir()->Addr(), nullptr, OAK_NOT_EQUAL); } break; case GT_ARR_LENGTH: // An array length is an (always R-value) indirection (but doesn't derive from GenTreeIndir). assertionInfo = optCreateAssertion(tree->AsArrLen()->ArrRef(), nullptr, OAK_NOT_EQUAL); break; case GT_NULLCHECK: // Explicit null checks always create non-null assertions. assertionInfo = optCreateAssertion(tree->AsIndir()->Addr(), nullptr, OAK_NOT_EQUAL); break; case GT_INTRINSIC: if (tree->AsIntrinsic()->gtIntrinsicName == NI_System_Object_GetType) { assertionInfo = optCreateAssertion(tree->AsIntrinsic()->gtGetOp1(), nullptr, OAK_NOT_EQUAL); } break; case GT_BOUNDS_CHECK: if (!optLocalAssertionProp) { assertionInfo = optCreateAssertion(tree, nullptr, OAK_NO_THROW); } break; case GT_ARR_ELEM: // An array element reference can create a non-null assertion assertionInfo = optCreateAssertion(tree->AsArrElem()->gtArrObj, nullptr, OAK_NOT_EQUAL); break; case GT_CALL: { // A virtual call can create a non-null assertion. We transform some virtual calls into non-virtual calls // with a GTF_CALL_NULLCHECK flag set. // Ignore tail calls because they have 'this` pointer in the regular arg list and an implicit null check. GenTreeCall* const call = tree->AsCall(); if (call->NeedsNullCheck() || (call->IsVirtual() && !call->IsTailCall())) { // Retrieve the 'this' arg. GenTree* thisArg = gtGetThisArg(call); assert(thisArg != nullptr); assertionInfo = optCreateAssertion(thisArg, nullptr, OAK_NOT_EQUAL); } } break; case GT_CAST: // This represets an assertion that we would like to prove to be true. // If we can prove this assertion true then we can eliminate this cast. // We only create this assertion for global assertion propagation. assertionInfo = optAssertionGenCast(tree->AsCast()); assertionProven = false; break; case GT_JTRUE: assertionInfo = optAssertionGenJtrue(tree); break; default: // All other gtOper node kinds, leave 'assertionIndex' = NO_ASSERTION_INDEX break; } // For global assertion prop we must store the assertion number in the tree node if (assertionInfo.HasAssertion() && assertionProven && !optLocalAssertionProp) { tree->SetAssertionInfo(assertionInfo); } } /***************************************************************************** * * Maps a complementary assertion to its original assertion so it can be * retrieved faster. */ void Compiler::optMapComplementary(AssertionIndex assertionIndex, AssertionIndex index) { if (assertionIndex == NO_ASSERTION_INDEX || index == NO_ASSERTION_INDEX) { return; } assert(assertionIndex <= optMaxAssertionCount); assert(index <= optMaxAssertionCount); optComplementaryAssertionMap[assertionIndex] = index; optComplementaryAssertionMap[index] = assertionIndex; } /***************************************************************************** * * Given an assertion index, return the assertion index of the complementary * assertion or 0 if one does not exist. */ AssertionIndex Compiler::optFindComplementary(AssertionIndex assertIndex) { if (assertIndex == NO_ASSERTION_INDEX) { return NO_ASSERTION_INDEX; } AssertionDsc* inputAssertion = optGetAssertion(assertIndex); // Must be an equal or not equal assertion. if (inputAssertion->assertionKind != OAK_EQUAL && inputAssertion->assertionKind != OAK_NOT_EQUAL) { return NO_ASSERTION_INDEX; } AssertionIndex index = optComplementaryAssertionMap[assertIndex]; if (index != NO_ASSERTION_INDEX && index <= optAssertionCount) { return index; } for (AssertionIndex index = 1; index <= optAssertionCount; ++index) { // Make sure assertion kinds are complementary and op1, op2 kinds match. AssertionDsc* curAssertion = optGetAssertion(index); if (curAssertion->Complementary(inputAssertion, !optLocalAssertionProp)) { optMapComplementary(assertIndex, index); return index; } } return NO_ASSERTION_INDEX; } //------------------------------------------------------------------------ // optAssertionIsSubrange: Find a subrange assertion for the given range and tree. // // This function will return the index of the first assertion in "assertions" // which claims that the value of "tree" is withing the bounds of the provided // "range" (i. e. "range.Contains(assertedRange)"). // // Arguments: // tree - the tree for which to find the assertion // range - range the subrange of which to look for // assertions - the set of assertions // // Return Value: // Index of the found assertion, NO_ASSERTION_INDEX otherwise. // AssertionIndex Compiler::optAssertionIsSubrange(GenTree* tree, IntegralRange range, ASSERT_VALARG_TP assertions) { if (!optLocalAssertionProp && BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } for (AssertionIndex index = 1; index <= optAssertionCount; index++) { AssertionDsc* curAssertion = optGetAssertion(index); if ((optLocalAssertionProp || BitVecOps::IsMember(apTraits, assertions, index - 1)) && // either local prop or use propagated assertions (curAssertion->assertionKind == OAK_SUBRANGE) && (curAssertion->op1.kind == O1K_LCLVAR)) { // For local assertion prop use comparison on locals, and use comparison on vns for global prop. bool isEqual = optLocalAssertionProp ? (curAssertion->op1.lcl.lclNum == tree->AsLclVarCommon()->GetLclNum()) : (curAssertion->op1.vn == vnStore->VNConservativeNormalValue(tree->gtVNPair)); if (!isEqual) { continue; } if (range.Contains(curAssertion->op2.u2)) { return index; } } } return NO_ASSERTION_INDEX; } /********************************************************************************** * * Given a "tree" that is usually arg1 of a isinst/cast kind of GT_CALL (a class * handle), and "methodTableArg" which is a const int (a class handle), then search * if there is an assertion in "assertions", that asserts the equality of the two * class handles and then returns the index of the assertion. If one such assertion * could not be found, then it returns NO_ASSERTION_INDEX. * */ AssertionIndex Compiler::optAssertionIsSubtype(GenTree* tree, GenTree* methodTableArg, ASSERT_VALARG_TP assertions) { if (!optLocalAssertionProp && BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } for (AssertionIndex index = 1; index <= optAssertionCount; index++) { if (!optLocalAssertionProp && !BitVecOps::IsMember(apTraits, assertions, index - 1)) { continue; } AssertionDsc* curAssertion = optGetAssertion(index); if (curAssertion->assertionKind != OAK_EQUAL || (curAssertion->op1.kind != O1K_SUBTYPE && curAssertion->op1.kind != O1K_EXACT_TYPE)) { continue; } // If local assertion prop use "lcl" based comparison, if global assertion prop use vn based comparison. if ((optLocalAssertionProp) ? (curAssertion->op1.lcl.lclNum != tree->AsLclVarCommon()->GetLclNum()) : (curAssertion->op1.vn != vnStore->VNConservativeNormalValue(tree->gtVNPair))) { continue; } if (curAssertion->op2.kind == O2K_IND_CNS_INT) { if (methodTableArg->gtOper != GT_IND) { continue; } methodTableArg = methodTableArg->AsOp()->gtOp1; } else if (curAssertion->op2.kind != O2K_CONST_INT) { continue; } ssize_t methodTableVal = 0; GenTreeFlags iconFlags = GTF_EMPTY; if (!optIsTreeKnownIntValue(!optLocalAssertionProp, methodTableArg, &methodTableVal, &iconFlags)) { continue; } if (curAssertion->op2.u1.iconVal == methodTableVal) { return index; } } return NO_ASSERTION_INDEX; } //------------------------------------------------------------------------------ // optVNConstantPropOnTree: Substitutes tree with an evaluated constant while // managing side-effects. // // Arguments: // block - The block containing the tree. // stmt - The statement in the block containing the tree. // tree - The tree node whose value is known at compile time. // The tree should have a constant value number. // // Return Value: // Returns a potentially new or a transformed tree node. // Returns nullptr when no transformation is possible. // // Description: // Transforms a tree node if its result evaluates to a constant. The // transformation can be a "ChangeOper" to a constant or a new constant node // with extracted side-effects. // // Before replacing or substituting the "tree" with a constant, extracts any // side effects from the "tree" and creates a comma separated side effect list // and then appends the transformed node at the end of the list. // This comma separated list is then returned. // // For JTrue nodes, side effects are not put into a comma separated list. If // the relop will evaluate to "true" or "false" statically, then the side-effects // will be put into new statements, presuming the JTrue will be folded away. // GenTree* Compiler::optVNConstantPropOnTree(BasicBlock* block, GenTree* tree) { if (tree->OperGet() == GT_JTRUE) { // Treat JTRUE separately to extract side effects into respective statements rather // than using a COMMA separated op1. return optVNConstantPropOnJTrue(block, tree); } // If relop is part of JTRUE, this should be optimized as part of the parent JTRUE. // Or if relop is part of QMARK or anything else, we simply bail here. else if (tree->OperIsCompare() && (tree->gtFlags & GTF_RELOP_JMP_USED)) { return nullptr; } // We want to use the Normal ValueNumber when checking for constants. ValueNumPair vnPair = tree->gtVNPair; ValueNum vnCns = vnStore->VNConservativeNormalValue(vnPair); // Check if node evaluates to a constant or Vector.Zero. if (!vnStore->IsVNConstant(vnCns) && !vnStore->IsVNVectorZero(vnCns)) { return nullptr; } GenTree* conValTree = nullptr; switch (vnStore->TypeOfVN(vnCns)) { case TYP_FLOAT: { float value = vnStore->ConstantValue<float>(vnCns); if (tree->TypeGet() == TYP_INT) { // Same sized reinterpretation of bits to integer conValTree = gtNewIconNode(*(reinterpret_cast<int*>(&value))); } else { // Implicit assignment conversion to float or double assert(varTypeIsFloating(tree->TypeGet())); conValTree = gtNewDconNode(value, tree->TypeGet()); } break; } case TYP_DOUBLE: { double value = vnStore->ConstantValue<double>(vnCns); if (tree->TypeGet() == TYP_LONG) { conValTree = gtNewLconNode(*(reinterpret_cast<INT64*>(&value))); } else { // Implicit assignment conversion to float or double assert(varTypeIsFloating(tree->TypeGet())); conValTree = gtNewDconNode(value, tree->TypeGet()); } break; } case TYP_LONG: { INT64 value = vnStore->ConstantValue<INT64>(vnCns); #ifdef TARGET_64BIT if (vnStore->IsVNHandle(vnCns)) { // Don't perform constant folding that involves a handle that needs // to be recorded as a relocation with the VM. if (!opts.compReloc) { conValTree = gtNewIconHandleNode(value, vnStore->GetHandleFlags(vnCns)); } } else #endif { switch (tree->TypeGet()) { case TYP_INT: // Implicit assignment conversion to smaller integer conValTree = gtNewIconNode(static_cast<int>(value)); break; case TYP_LONG: // Same type no conversion required conValTree = gtNewLconNode(value); break; case TYP_FLOAT: // No implicit conversions from long to float and value numbering will // not propagate through memory reinterpretations of different size. unreached(); break; case TYP_DOUBLE: // Same sized reinterpretation of bits to double conValTree = gtNewDconNode(*(reinterpret_cast<double*>(&value))); break; default: // Do not support such optimization. break; } } } break; case TYP_REF: { assert(vnStore->ConstantValue<size_t>(vnCns) == 0); // Support onle ref(ref(0)), do not support other forms (e.g byref(ref(0)). if (tree->TypeGet() == TYP_REF) { conValTree = gtNewIconNode(0, TYP_REF); } } break; case TYP_INT: { int value = vnStore->ConstantValue<int>(vnCns); #ifndef TARGET_64BIT if (vnStore->IsVNHandle(vnCns)) { // Don't perform constant folding that involves a handle that needs // to be recorded as a relocation with the VM. if (!opts.compReloc) { conValTree = gtNewIconHandleNode(value, vnStore->GetHandleFlags(vnCns)); } } else #endif { switch (tree->TypeGet()) { case TYP_REF: case TYP_INT: // Same type no conversion required conValTree = gtNewIconNode(value); break; case TYP_LONG: // Implicit assignment conversion to larger integer conValTree = gtNewLconNode(value); break; case TYP_FLOAT: // Same sized reinterpretation of bits to float conValTree = gtNewDconNode(*reinterpret_cast<float*>(&value), TYP_FLOAT); break; case TYP_DOUBLE: // No implicit conversions from int to double and value numbering will // not propagate through memory reinterpretations of different size. unreached(); break; case TYP_BOOL: case TYP_BYTE: case TYP_UBYTE: case TYP_SHORT: case TYP_USHORT: assert(FitsIn(tree->TypeGet(), value)); conValTree = gtNewIconNode(value); break; default: // Do not support (e.g. byref(const int)). break; } } } break; #if FEATURE_HW_INTRINSICS case TYP_SIMD8: case TYP_SIMD12: case TYP_SIMD16: case TYP_SIMD32: { assert(vnStore->IsVNVectorZero(vnCns)); VNSimdTypeInfo vnInfo = vnStore->GetVectorZeroSimdTypeOfVN(vnCns); assert(vnInfo.m_simdBaseJitType != CORINFO_TYPE_UNDEF); assert(vnInfo.m_simdSize != 0); assert(getSIMDTypeForSize(vnInfo.m_simdSize) == vnStore->TypeOfVN(vnCns)); conValTree = gtNewSimdZeroNode(tree->TypeGet(), vnInfo.m_simdBaseJitType, vnInfo.m_simdSize, true); } break; #endif case TYP_BYREF: // Do not support const byref optimization. break; default: // We do not record constants of other types. unreached(); break; } if (conValTree != nullptr) { // Were able to optimize. conValTree->gtVNPair = vnPair; GenTree* sideEffList = optExtractSideEffListFromConst(tree); if (sideEffList != nullptr) { // Replace as COMMA(side_effects, const value tree); assert((sideEffList->gtFlags & GTF_SIDE_EFFECT) != 0); return gtNewOperNode(GT_COMMA, conValTree->TypeGet(), sideEffList, conValTree); } else { // No side effects, replace as const value tree. return conValTree; } } else { // Was not able to optimize. return nullptr; } } //------------------------------------------------------------------------------ // optConstantAssertionProp: Possibly substitute a constant for a local use // // Arguments: // curAssertion - assertion to propagate // tree - tree to possibly modify // stmt - statement containing the tree // index - index of this assertion in the assertion table // // Returns: // Updated tree (may be the input tree, modified in place), or nullptr // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optConstantAssertionProp(AssertionDsc* curAssertion, GenTreeLclVarCommon* tree, Statement* stmt DEBUGARG(AssertionIndex index)) { const unsigned lclNum = tree->GetLclNum(); if (lclNumIsCSE(lclNum)) { return nullptr; } GenTree* newTree = tree; // Update 'newTree' with the new value from our table // Typically newTree == tree and we are updating the node in place switch (curAssertion->op2.kind) { case O2K_CONST_DOUBLE: // There could be a positive zero and a negative zero, so don't propagate zeroes. if (curAssertion->op2.dconVal == 0.0) { return nullptr; } newTree->BashToConst(curAssertion->op2.dconVal, tree->TypeGet()); break; case O2K_CONST_LONG: if (newTree->TypeIs(TYP_LONG)) { newTree->BashToConst(curAssertion->op2.lconVal); } else { newTree->BashToConst(static_cast<int32_t>(curAssertion->op2.lconVal)); } break; case O2K_CONST_INT: // Don't propagate handles if we need to report relocs. if (opts.compReloc && ((curAssertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK) != 0)) { return nullptr; } if (curAssertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK) { // Here we have to allocate a new 'large' node to replace the old one newTree = gtNewIconHandleNode(curAssertion->op2.u1.iconVal, curAssertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK); } else { bool isArrIndex = ((tree->gtFlags & GTF_VAR_ARR_INDEX) != 0); assert(varTypeIsIntegralOrI(tree)); newTree->BashToConst(curAssertion->op2.u1.iconVal, genActualType(tree)); // If we're doing an array index address, assume any constant propagated contributes to the index. if (isArrIndex) { newTree->AsIntCon()->gtFieldSeq = GetFieldSeqStore()->CreateSingleton(FieldSeqStore::ConstantIndexPseudoField); } newTree->gtFlags &= ~GTF_VAR_ARR_INDEX; } break; default: return nullptr; } if (!optLocalAssertionProp) { assert(newTree->OperIsConst()); // We should have a simple Constant node for newTree assert(vnStore->IsVNConstant(curAssertion->op2.vn)); // The value number stored for op2 should be a valid // VN representing the constant newTree->gtVNPair.SetBoth(curAssertion->op2.vn); // Set the ValueNumPair to the constant VN from op2 // of the assertion } #ifdef DEBUG if (verbose) { printf("\nAssertion prop in " FMT_BB ":\n", compCurBB->bbNum); optPrintAssertion(curAssertion, index); gtDispTree(newTree, nullptr, nullptr, true); } #endif return optAssertionProp_Update(newTree, tree, stmt); } //------------------------------------------------------------------------------ // optZeroObjAssertionProp: Find and propagate a ZEROOBJ assertion for the given tree. // // Arguments: // assertions - set of live assertions // tree - the tree to possibly replace, in-place, with a zero // // Returns: // Whether propagation took place. // // Notes: // Because not all users of struct nodes support "zero" operands, instead of // propagating ZEROOBJ on locals, we propagate it on their parents. // bool Compiler::optZeroObjAssertionProp(GenTree* tree, ASSERT_VALARG_TP assertions) { assert(varTypeIsStruct(tree)); // We only make ZEROOBJ assertions in local propagation. if (!optLocalAssertionProp) { return false; } if (!tree->OperIs(GT_LCL_VAR) || lvaGetDesc(tree->AsLclVar())->IsAddressExposed()) { return false; } unsigned lclNum = tree->AsLclVar()->GetLclNum(); AssertionIndex assertionIndex = optLocalAssertionIsEqualOrNotEqual(O1K_LCLVAR, lclNum, O2K_ZEROOBJ, 0, assertions); if (assertionIndex == NO_ASSERTION_INDEX) { return false; } AssertionDsc* assertion = optGetAssertion(assertionIndex); JITDUMP("\nAssertion prop in " FMT_BB ":\n", compCurBB->bbNum); JITDUMPEXEC(optPrintAssertion(assertion, assertionIndex)); DISPNODE(tree); tree->BashToZeroConst(TYP_INT); JITDUMP(" =>\n"); DISPNODE(tree); return true; } //------------------------------------------------------------------------------ // optAssertionProp_LclVarTypeCheck: verify compatible types for copy prop // // Arguments: // tree - tree to possibly modify // lclVarDsc - local accessed by tree // copyVarDsc - local to possibly copy prop into tree // // Returns: // True if copy prop is safe. // // Notes: // Before substituting copyVar for lclVar, make sure using copyVar doesn't widen access. // bool Compiler::optAssertionProp_LclVarTypeCheck(GenTree* tree, LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc) { /* Small struct field locals are stored using the exact width and loaded widened (i.e. lvNormalizeOnStore==false lvNormalizeOnLoad==true), because the field locals might end up embedded in the parent struct local with the exact width. In other words, a store to a short field local should always done using an exact width store [00254538] 0x0009 ------------ const int 0x1234 [002545B8] 0x000B -A--G--NR--- = short [00254570] 0x000A D------N---- lclVar short V43 tmp40 mov word ptr [L_043], 0x1234 Now, if we copy prop, say a short field local V43, to another short local V34 for the following tree: [04E18650] 0x0001 ------------ lclVar int V34 tmp31 [04E19714] 0x0002 -A---------- = int [04E196DC] 0x0001 D------N---- lclVar int V36 tmp33 We will end with this tree: [04E18650] 0x0001 ------------ lclVar int V43 tmp40 [04E19714] 0x0002 -A-----NR--- = int [04E196DC] 0x0001 D------N---- lclVar int V36 tmp33 EAX And eventually causing a fetch of 4-byte out from [L_043] :( mov EAX, dword ptr [L_043] The following check is to make sure we only perform the copy prop when we don't retrieve the wider value. */ if (copyVarDsc->lvIsStructField) { var_types varType = (var_types)copyVarDsc->lvType; // Make sure we don't retrieve the wider value. return !varTypeIsSmall(varType) || (varType == tree->TypeGet()); } // Called in the context of a single copy assertion, so the types should have been // taken care by the assertion gen logic for other cases. Just return true. return true; } //------------------------------------------------------------------------ // optCopyAssertionProp: copy prop use of one local with another // // Arguments: // curAssertion - assertion triggering the possible copy // tree - tree use to consider replacing // stmt - statment containing the tree // index - index of the assertion // // Returns: // Updated tree, or nullptr // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optCopyAssertionProp(AssertionDsc* curAssertion, GenTreeLclVarCommon* tree, Statement* stmt DEBUGARG(AssertionIndex index)) { const AssertionDsc::AssertionDscOp1& op1 = curAssertion->op1; const AssertionDsc::AssertionDscOp2& op2 = curAssertion->op2; noway_assert(op1.lcl.lclNum != op2.lcl.lclNum); const unsigned lclNum = tree->GetLclNum(); // Make sure one of the lclNum of the assertion matches with that of the tree. if (op1.lcl.lclNum != lclNum && op2.lcl.lclNum != lclNum) { return nullptr; } // Extract the matching lclNum and ssaNum, as well as the field sequence. unsigned copyLclNum; unsigned copySsaNum; FieldSeqNode* zeroOffsetFieldSeq; if (op1.lcl.lclNum == lclNum) { copyLclNum = op2.lcl.lclNum; copySsaNum = op2.lcl.ssaNum; zeroOffsetFieldSeq = op2.zeroOffsetFieldSeq; } else { copyLclNum = op1.lcl.lclNum; copySsaNum = op1.lcl.ssaNum; zeroOffsetFieldSeq = nullptr; // Only the RHS of an assignment can have a FldSeq. assert(optLocalAssertionProp); // Were we to perform replacements in global propagation, that makes copy // assertions for control flow ("if (a == b) { ... }"), where both operands // could have a FldSeq, we'd need to save it for "op1" too. } if (!optLocalAssertionProp) { // Extract the ssaNum of the matching lclNum. unsigned ssaNum = (op1.lcl.lclNum == lclNum) ? op1.lcl.ssaNum : op2.lcl.ssaNum; if (ssaNum != tree->GetSsaNum()) { return nullptr; } } LclVarDsc* const copyVarDsc = lvaGetDesc(copyLclNum); LclVarDsc* const lclVarDsc = lvaGetDesc(lclNum); // Make sure the types are compatible. if (!optAssertionProp_LclVarTypeCheck(tree, lclVarDsc, copyVarDsc)) { return nullptr; } // Make sure we can perform this copy prop. if (optCopyProp_LclVarScore(lclVarDsc, copyVarDsc, curAssertion->op1.lcl.lclNum == lclNum) <= 0) { return nullptr; } tree->SetLclNum(copyLclNum); tree->SetSsaNum(copySsaNum); // The sequence we are propagating (if any) represents the inner fields. if (zeroOffsetFieldSeq != nullptr) { FieldSeqNode* outerZeroOffsetFieldSeq = nullptr; if (GetZeroOffsetFieldMap()->Lookup(tree, &outerZeroOffsetFieldSeq)) { zeroOffsetFieldSeq = GetFieldSeqStore()->Append(zeroOffsetFieldSeq, outerZeroOffsetFieldSeq); GetZeroOffsetFieldMap()->Remove(tree); } fgAddFieldSeqForZeroOffset(tree, zeroOffsetFieldSeq); } #ifdef DEBUG if (verbose) { printf("\nAssertion prop in " FMT_BB ":\n", compCurBB->bbNum); optPrintAssertion(curAssertion, index); DISPNODE(tree); } #endif // Update and morph the tree. return optAssertionProp_Update(tree, tree, stmt); } //------------------------------------------------------------------------ // optAssertionProp_LclVar: try and optimize a local var use via assertions // // Arguments: // assertions - set of live assertions // tree - local use to optimize // stmt - statement containing the tree // // Returns: // Updated tree, or nullptr // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optAssertionProp_LclVar(ASSERT_VALARG_TP assertions, GenTreeLclVarCommon* tree, Statement* stmt) { // If we have a var definition then bail or // If this is the address of the var then it will have the GTF_DONT_CSE // flag set and we don't want to to assertion prop on it. if (tree->gtFlags & (GTF_VAR_DEF | GTF_DONT_CSE)) { return nullptr; } BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } // See if the variable is equal to a constant or another variable. AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if (curAssertion->assertionKind != OAK_EQUAL || curAssertion->op1.kind != O1K_LCLVAR) { continue; } // Copy prop. if (curAssertion->op2.kind == O2K_LCLVAR_COPY) { // Cannot do copy prop during global assertion prop because of no knowledge // of kill sets. We will still make a == b copy assertions during the global phase to allow // for any implied assertions that can be retrieved. Because implied assertions look for // matching SSA numbers (i.e., if a0 == b1 and b1 == c0 then a0 == c0) they don't need kill sets. if (optLocalAssertionProp) { // Perform copy assertion prop. GenTree* newTree = optCopyAssertionProp(curAssertion, tree, stmt DEBUGARG(assertionIndex)); if (newTree != nullptr) { return newTree; } } continue; } // There are no constant assertions for structs. // if (varTypeIsStruct(tree)) { continue; } // Constant prop. // // The case where the tree type could be different than the LclVar type is caused by // gtFoldExpr, specifically the case of a cast, where the fold operation changes the type of the LclVar // node. In such a case is not safe to perform the substitution since later on the JIT will assert mismatching // types between trees. const unsigned lclNum = tree->GetLclNum(); if (curAssertion->op1.lcl.lclNum == lclNum) { LclVarDsc* const lclDsc = lvaGetDesc(lclNum); // Verify types match if (tree->TypeGet() == lclDsc->lvType) { // If local assertion prop, just perform constant prop. if (optLocalAssertionProp) { return optConstantAssertionProp(curAssertion, tree, stmt DEBUGARG(assertionIndex)); } // If global assertion, perform constant propagation only if the VN's match. if (curAssertion->op1.vn == vnStore->VNConservativeNormalValue(tree->gtVNPair)) { return optConstantAssertionProp(curAssertion, tree, stmt DEBUGARG(assertionIndex)); } } } } return nullptr; } //------------------------------------------------------------------------ // optAssertionProp_Asg: Try and optimize an assignment via assertions. // // Propagates ZEROOBJ for the RHS. // // Arguments: // assertions - set of live assertions // asg - the store to optimize // stmt - statement containing "asg" // // Returns: // Updated "asg", or "nullptr" // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optAssertionProp_Asg(ASSERT_VALARG_TP assertions, GenTreeOp* asg, Statement* stmt) { GenTree* rhs = asg->gtGetOp2(); if (asg->OperIsCopyBlkOp() && varTypeIsStruct(rhs)) { if (optZeroObjAssertionProp(rhs, assertions)) { return optAssertionProp_Update(asg, asg, stmt); } } return nullptr; } //------------------------------------------------------------------------ // optAssertionProp_Return: Try and optimize a GT_RETURN via assertions. // // Propagates ZEROOBJ for the return value. // // Arguments: // assertions - set of live assertions // ret - the return node to optimize // stmt - statement containing "ret" // // Returns: // Updated "ret", or "nullptr" // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optAssertionProp_Return(ASSERT_VALARG_TP assertions, GenTreeUnOp* ret, Statement* stmt) { GenTree* retValue = ret->gtGetOp1(); // Only propagate zeroes that lowering can deal with. if (!ret->TypeIs(TYP_VOID) && varTypeIsStruct(retValue) && !varTypeIsStruct(info.compRetNativeType)) { if (optZeroObjAssertionProp(retValue, assertions)) { return optAssertionProp_Update(ret, ret, stmt); } } return nullptr; } /***************************************************************************** * * Given a set of "assertions" to search, find an assertion that matches * op1Kind and lclNum, op2Kind and the constant value and is either equal or * not equal assertion. */ AssertionIndex Compiler::optLocalAssertionIsEqualOrNotEqual( optOp1Kind op1Kind, unsigned lclNum, optOp2Kind op2Kind, ssize_t cnsVal, ASSERT_VALARG_TP assertions) { noway_assert((op1Kind == O1K_LCLVAR) || (op1Kind == O1K_EXACT_TYPE) || (op1Kind == O1K_SUBTYPE)); noway_assert((op2Kind == O2K_CONST_INT) || (op2Kind == O2K_IND_CNS_INT) || (op2Kind == O2K_ZEROOBJ)); if (!optLocalAssertionProp && BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } for (AssertionIndex index = 1; index <= optAssertionCount; ++index) { AssertionDsc* curAssertion = optGetAssertion(index); if (optLocalAssertionProp || BitVecOps::IsMember(apTraits, assertions, index - 1)) { if ((curAssertion->assertionKind != OAK_EQUAL) && (curAssertion->assertionKind != OAK_NOT_EQUAL)) { continue; } if ((curAssertion->op1.kind == op1Kind) && (curAssertion->op1.lcl.lclNum == lclNum) && (curAssertion->op2.kind == op2Kind)) { bool constantIsEqual = (curAssertion->op2.u1.iconVal == cnsVal); bool assertionIsEqual = (curAssertion->assertionKind == OAK_EQUAL); if (constantIsEqual || assertionIsEqual) { return index; } } } } return NO_ASSERTION_INDEX; } //------------------------------------------------------------------------ // optGlobalAssertionIsEqualOrNotEqual: Look for an assertion in the specified // set that is one of op1 == op1, op1 != op2, or *op1 == op2, // where equality is based on value numbers. // // Arguments: // assertions: bit vector describing set of assertions // op1, op2: the treen nodes in question // // Returns: // Index of first matching assertion, or NO_ASSERTION_INDEX if no // assertions in the set are matches. // // Notes: // Assertions based on *op1 are the result of exact type tests and are // only returned when op1 is a local var with ref type and the assertion // is an exact type equality. // AssertionIndex Compiler::optGlobalAssertionIsEqualOrNotEqual(ASSERT_VALARG_TP assertions, GenTree* op1, GenTree* op2) { if (BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if ((curAssertion->assertionKind != OAK_EQUAL && curAssertion->assertionKind != OAK_NOT_EQUAL)) { continue; } if ((curAssertion->op1.vn == vnStore->VNConservativeNormalValue(op1->gtVNPair)) && (curAssertion->op2.vn == vnStore->VNConservativeNormalValue(op2->gtVNPair))) { return assertionIndex; } // Look for matching exact type assertions based on vtable accesses if ((curAssertion->assertionKind == OAK_EQUAL) && (curAssertion->op1.kind == O1K_EXACT_TYPE) && op1->OperIs(GT_IND)) { GenTree* indirAddr = op1->AsIndir()->Addr(); if (indirAddr->OperIs(GT_LCL_VAR) && (indirAddr->TypeGet() == TYP_REF)) { // op1 is accessing vtable of a ref type local var if ((curAssertion->op1.vn == vnStore->VNConservativeNormalValue(indirAddr->gtVNPair)) && (curAssertion->op2.vn == vnStore->VNConservativeNormalValue(op2->gtVNPair))) { return assertionIndex; } } } } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Given a set of "assertions" to search for, find an assertion that is either * op == 0 or op != 0 * */ AssertionIndex Compiler::optGlobalAssertionIsEqualOrNotEqualZero(ASSERT_VALARG_TP assertions, GenTree* op1) { if (BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if ((curAssertion->assertionKind != OAK_EQUAL && curAssertion->assertionKind != OAK_NOT_EQUAL)) { continue; } if ((curAssertion->op1.vn == vnStore->VNConservativeNormalValue(op1->gtVNPair)) && (curAssertion->op2.vn == vnStore->VNZeroForType(op1->TypeGet()))) { return assertionIndex; } } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Given a tree consisting of a RelOp and a set of available assertions * we try to propagate an assertion and modify the RelOp tree if we can. * We pass in the root of the tree via 'stmt', for local copy prop 'stmt' will be nullptr * Returns the modified tree, or nullptr if no assertion prop took place */ GenTree* Compiler::optAssertionProp_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { assert(tree->OperIsCompare()); if (!optLocalAssertionProp) { // If global assertion prop then use value numbering. return optAssertionPropGlobal_RelOp(assertions, tree, stmt); } // // Currently only GT_EQ or GT_NE are supported Relops for local AssertionProp // if ((tree->gtOper != GT_EQ) && (tree->gtOper != GT_NE)) { return nullptr; } // If local assertion prop then use variable based prop. return optAssertionPropLocal_RelOp(assertions, tree, stmt); } //------------------------------------------------------------------------ // optAssertionProp: try and optimize a relop via assertion propagation // // Arguments: // assertions - set of live assertions // tree - tree to possibly optimize // stmt - statement containing the tree // // Returns: // The modified tree, or nullptr if no assertion prop took place. // GenTree* Compiler::optAssertionPropGlobal_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { GenTree* newTree = tree; GenTree* op1 = tree->AsOp()->gtOp1; GenTree* op2 = tree->AsOp()->gtOp2; // Look for assertions of the form (tree EQ/NE 0) AssertionIndex index = optGlobalAssertionIsEqualOrNotEqualZero(assertions, tree); if (index != NO_ASSERTION_INDEX) { // We know that this relop is either 0 or != 0 (1) AssertionDsc* curAssertion = optGetAssertion(index); #ifdef DEBUG if (verbose) { printf("\nVN relop based constant assertion prop in " FMT_BB ":\n", compCurBB->bbNum); printf("Assertion index=#%02u: ", index); printTreeID(tree); printf(" %s 0\n", (curAssertion->assertionKind == OAK_EQUAL) ? "==" : "!="); } #endif // Bail out if tree is not side effect free. if ((tree->gtFlags & GTF_SIDE_EFFECT) != 0) { JITDUMP("sorry, blocked by side effects\n"); return nullptr; } if (curAssertion->assertionKind == OAK_EQUAL) { tree->BashToConst(0); } else { tree->BashToConst(1); } newTree = fgMorphTree(tree); DISPTREE(newTree); return optAssertionProp_Update(newTree, tree, stmt); } // Else check if we have an equality check involving a local or an indir if (!tree->OperIs(GT_EQ, GT_NE)) { return nullptr; } // Bail out if tree is not side effect free. if ((tree->gtFlags & GTF_SIDE_EFFECT) != 0) { return nullptr; } if (!op1->OperIs(GT_LCL_VAR, GT_IND)) { return nullptr; } // Find an equal or not equal assertion involving "op1" and "op2". index = optGlobalAssertionIsEqualOrNotEqual(assertions, op1, op2); if (index == NO_ASSERTION_INDEX) { return nullptr; } AssertionDsc* curAssertion = optGetAssertion(index); bool assertionKindIsEqual = (curAssertion->assertionKind == OAK_EQUAL); // Allow or not to reverse condition for OAK_NOT_EQUAL assertions. bool allowReverse = true; // If the assertion involves "op2" and it is a constant, then check if "op1" also has a constant value. ValueNum vnCns = vnStore->VNConservativeNormalValue(op2->gtVNPair); if (vnStore->IsVNConstant(vnCns)) { #ifdef DEBUG if (verbose) { printf("\nVN relop based constant assertion prop in " FMT_BB ":\n", compCurBB->bbNum); printf("Assertion index=#%02u: ", index); printTreeID(op1); printf(" %s ", assertionKindIsEqual ? "==" : "!="); if (genActualType(op1->TypeGet()) == TYP_INT) { printf("%d\n", vnStore->ConstantValue<int>(vnCns)); } else if (op1->TypeGet() == TYP_LONG) { printf("%I64d\n", vnStore->ConstantValue<INT64>(vnCns)); } else if (op1->TypeGet() == TYP_DOUBLE) { printf("%f\n", vnStore->ConstantValue<double>(vnCns)); } else if (op1->TypeGet() == TYP_FLOAT) { printf("%f\n", vnStore->ConstantValue<float>(vnCns)); } else if (op1->TypeGet() == TYP_REF) { // The only constant of TYP_REF that ValueNumbering supports is 'null' assert(vnStore->ConstantValue<size_t>(vnCns) == 0); printf("null\n"); } else if (op1->TypeGet() == TYP_BYREF) { printf("%d (byref)\n", static_cast<target_ssize_t>(vnStore->ConstantValue<size_t>(vnCns))); } else { printf("??unknown\n"); } gtDispTree(tree, nullptr, nullptr, true); } #endif // Change the oper to const. if (genActualType(op1->TypeGet()) == TYP_INT) { op1->BashToConst(vnStore->ConstantValue<int>(vnCns)); if (vnStore->IsVNHandle(vnCns)) { op1->gtFlags |= (vnStore->GetHandleFlags(vnCns) & GTF_ICON_HDL_MASK); } } else if (op1->TypeGet() == TYP_LONG) { op1->BashToConst(vnStore->ConstantValue<INT64>(vnCns)); if (vnStore->IsVNHandle(vnCns)) { op1->gtFlags |= (vnStore->GetHandleFlags(vnCns) & GTF_ICON_HDL_MASK); } } else if (op1->TypeGet() == TYP_DOUBLE) { double constant = vnStore->ConstantValue<double>(vnCns); op1->BashToConst(constant); // Nothing can be equal to NaN. So if IL had "op1 == NaN", then we already made op1 NaN, // which will yield a false correctly. Instead if IL had "op1 != NaN", then we already // made op1 NaN which will yield a true correctly. Note that this is irrespective of the // assertion we have made. allowReverse = (_isnan(constant) == 0); } else if (op1->TypeGet() == TYP_FLOAT) { float constant = vnStore->ConstantValue<float>(vnCns); op1->BashToConst(constant); // See comments for TYP_DOUBLE. allowReverse = (_isnan(constant) == 0); } else if (op1->TypeGet() == TYP_REF) { op1->BashToConst(0, TYP_REF); // The only constant of TYP_REF that ValueNumbering supports is 'null' noway_assert(vnStore->ConstantValue<size_t>(vnCns) == 0); } else if (op1->TypeGet() == TYP_BYREF) { op1->BashToConst(static_cast<target_ssize_t>(vnStore->ConstantValue<size_t>(vnCns)), TYP_BYREF); } else { noway_assert(!"unknown type in Global_RelOp"); } op1->gtVNPair.SetBoth(vnCns); // Preserve the ValueNumPair, as BashToConst will clear it. // set foldResult to either 0 or 1 bool foldResult = assertionKindIsEqual; if (tree->gtOper == GT_NE) { foldResult = !foldResult; } // Set the value number on the relop to 1 (true) or 0 (false) if (foldResult) { tree->gtVNPair.SetBoth(vnStore->VNOneForType(TYP_INT)); } else { tree->gtVNPair.SetBoth(vnStore->VNZeroForType(TYP_INT)); } } // If the assertion involves "op2" and "op1" is also a local var, then just morph the tree. else if (op2->gtOper == GT_LCL_VAR) { #ifdef DEBUG if (verbose) { printf("\nVN relop based copy assertion prop in " FMT_BB ":\n", compCurBB->bbNum); printf("Assertion index=#%02u: V%02d.%02d %s V%02d.%02d\n", index, op1->AsLclVar()->GetLclNum(), op1->AsLclVar()->GetSsaNum(), (curAssertion->assertionKind == OAK_EQUAL) ? "==" : "!=", op2->AsLclVar()->GetLclNum(), op2->AsLclVar()->GetSsaNum()); gtDispTree(tree, nullptr, nullptr, true); } #endif // If floating point, don't just substitute op1 with op2, this won't work if // op2 is NaN. Just turn it into a "true" or "false" yielding expression. if (op1->TypeIs(TYP_FLOAT, TYP_DOUBLE)) { // Note we can't trust the OAK_EQUAL as the value could end up being a NaN // violating the assertion. However, we create OAK_EQUAL assertions for floating // point only on JTrue nodes, so if the condition held earlier, it will hold // now. We don't create OAK_EQUAL assertion on floating point from GT_ASG // because we depend on value num which would constant prop the NaN. op1->BashToConst(0.0, op1->TypeGet()); op2->BashToConst(0.0, op2->TypeGet()); } // Change the op1 LclVar to the op2 LclVar else { noway_assert(varTypeIsIntegralOrI(op1->TypeGet())); op1->AsLclVarCommon()->SetLclNum(op2->AsLclVarCommon()->GetLclNum()); op1->AsLclVarCommon()->SetSsaNum(op2->AsLclVarCommon()->GetSsaNum()); } } else { return nullptr; } // Finally reverse the condition, if we have a not equal assertion. if (allowReverse && curAssertion->assertionKind == OAK_NOT_EQUAL) { gtReverseCond(tree); } newTree = fgMorphTree(tree); #ifdef DEBUG if (verbose) { gtDispTree(newTree, nullptr, nullptr, true); } #endif return optAssertionProp_Update(newTree, tree, stmt); } /************************************************************************************* * * Given the set of "assertions" to look up a relop assertion about the relop "tree", * perform local variable name based relop assertion propagation on the tree. * */ GenTree* Compiler::optAssertionPropLocal_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { assert(tree->OperGet() == GT_EQ || tree->OperGet() == GT_NE); GenTree* op1 = tree->AsOp()->gtOp1; GenTree* op2 = tree->AsOp()->gtOp2; // For Local AssertionProp we only can fold when op1 is a GT_LCL_VAR if (op1->gtOper != GT_LCL_VAR) { return nullptr; } // For Local AssertionProp we only can fold when op2 is a GT_CNS_INT if (op2->gtOper != GT_CNS_INT) { return nullptr; } optOp1Kind op1Kind = O1K_LCLVAR; optOp2Kind op2Kind = O2K_CONST_INT; ssize_t cnsVal = op2->AsIntCon()->gtIconVal; var_types cmpType = op1->TypeGet(); // Don't try to fold/optimize Floating Compares; there are multiple zero values. if (varTypeIsFloating(cmpType)) { return nullptr; } // Find an equal or not equal assertion about op1 var. unsigned lclNum = op1->AsLclVarCommon()->GetLclNum(); noway_assert(lclNum < lvaCount); AssertionIndex index = optLocalAssertionIsEqualOrNotEqual(op1Kind, lclNum, op2Kind, cnsVal, assertions); if (index == NO_ASSERTION_INDEX) { return nullptr; } AssertionDsc* curAssertion = optGetAssertion(index); bool assertionKindIsEqual = (curAssertion->assertionKind == OAK_EQUAL); bool constantIsEqual = false; if (genTypeSize(cmpType) == TARGET_POINTER_SIZE) { constantIsEqual = (curAssertion->op2.u1.iconVal == cnsVal); } #ifdef TARGET_64BIT else if (genTypeSize(cmpType) == sizeof(INT32)) { // Compare the low 32-bits only constantIsEqual = (((INT32)curAssertion->op2.u1.iconVal) == ((INT32)cnsVal)); } #endif else { // We currently don't fold/optimize when the GT_LCL_VAR has been cast to a small type return nullptr; } noway_assert(constantIsEqual || assertionKindIsEqual); #ifdef DEBUG if (verbose) { printf("\nAssertion prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); gtDispTree(tree, nullptr, nullptr, true); } #endif // Return either CNS_INT 0 or CNS_INT 1. bool foldResult = (constantIsEqual == assertionKindIsEqual); if (tree->gtOper == GT_NE) { foldResult = !foldResult; } op2->AsIntCon()->gtIconVal = foldResult; op2->gtType = TYP_INT; return optAssertionProp_Update(op2, tree, stmt); } //------------------------------------------------------------------------ // optAssertionProp_Cast: Propagate assertion for a cast, possibly removing it. // // The function use "optAssertionIsSubrange" to find an assertion which claims the // cast's operand (only locals are supported) is a subrange of the "input" range // for the cast, as computed by "IntegralRange::ForCastInput", and, if such // assertion is found, act on it - either remove the cast if it is not changing // representation, or try to remove the GTF_OVERFLOW flag from it. // // Arguments: // assertions - the set of live assertions // cast - the cast for which to propagate the assertions // stmt - statement "cast" is a part of, "nullptr" for local prop // // Return Value: // The, possibly modified, cast tree or "nullptr" if no propagation took place. // GenTree* Compiler::optAssertionProp_Cast(ASSERT_VALARG_TP assertions, GenTreeCast* cast, Statement* stmt) { GenTree* op1 = cast->CastOp(); // Bail if we have a cast involving floating point or GC types. if (!varTypeIsIntegral(cast) || !varTypeIsIntegral(op1)) { return nullptr; } // Skip over a GT_COMMA node(s), if necessary to get to the lcl. GenTree* lcl = op1->gtEffectiveVal(); // If we don't have a cast of a LCL_VAR then bail. if (!lcl->OperIs(GT_LCL_VAR)) { return nullptr; } IntegralRange range = IntegralRange::ForCastInput(cast); AssertionIndex index = optAssertionIsSubrange(lcl, range, assertions); if (index != NO_ASSERTION_INDEX) { LclVarDsc* varDsc = lvaGetDesc(lcl->AsLclVarCommon()); // Representation-changing casts cannot be removed. if ((genActualType(cast) != genActualType(lcl))) { // Can we just remove the GTF_OVERFLOW flag? if (!cast->gtOverflow()) { return nullptr; } #ifdef DEBUG if (verbose) { printf("\nSubrange prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); DISPNODE(cast); } #endif cast->ClearOverflow(); return optAssertionProp_Update(cast, cast, stmt); } // We might need to retype a "normalize on load" local back to its original small type // so that codegen recognizes it needs to use narrow loads if the local ends up in memory. if (varDsc->lvNormalizeOnLoad()) { // The Jit is known to play somewhat loose with small types, so let's restrict this code // to the pattern we know is "safe and sound", i. e. CAST(type <- LCL_VAR(int, V00 type)). if ((varDsc->TypeGet() != cast->CastToType()) || !lcl->TypeIs(TYP_INT)) { return nullptr; } op1->ChangeType(varDsc->TypeGet()); } #ifdef DEBUG if (verbose) { printf("\nSubrange prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); DISPNODE(cast); } #endif return optAssertionProp_Update(op1, cast, stmt); } return nullptr; } /***************************************************************************** * * Given a tree with an array bounds check node, eliminate it because it was * checked already in the program. */ GenTree* Compiler::optAssertionProp_Comma(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { // Remove the bounds check as part of the GT_COMMA node since we need parent pointer to remove nodes. // When processing visits the bounds check, it sets the throw kind to None if the check is redundant. if (tree->gtGetOp1()->OperIs(GT_BOUNDS_CHECK) && ((tree->gtGetOp1()->gtFlags & GTF_CHK_INDEX_INBND) != 0)) { optRemoveCommaBasedRangeCheck(tree, stmt); return optAssertionProp_Update(tree, tree, stmt); } return nullptr; } //------------------------------------------------------------------------ // optAssertionProp_Ind: see if we can prove the indirection can't cause // and exception. // // Arguments: // assertions - set of live assertions // tree - tree to possibly optimize // stmt - statement containing the tree // // Returns: // The modified tree, or nullptr if no assertion prop took place. // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optAssertionProp_Ind(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { assert(tree->OperIsIndir()); if (!(tree->gtFlags & GTF_EXCEPT)) { return nullptr; } // Check for add of a constant. GenTree* op1 = tree->AsIndir()->Addr(); if ((op1->gtOper == GT_ADD) && (op1->AsOp()->gtOp2->gtOper == GT_CNS_INT)) { op1 = op1->AsOp()->gtOp1; } if (op1->gtOper != GT_LCL_VAR) { return nullptr; } #ifdef DEBUG bool vnBased = false; AssertionIndex index = NO_ASSERTION_INDEX; #endif if (optAssertionIsNonNull(op1, assertions DEBUGARG(&vnBased) DEBUGARG(&index))) { #ifdef DEBUG if (verbose) { (vnBased) ? printf("\nVN based non-null prop in " FMT_BB ":\n", compCurBB->bbNum) : printf("\nNon-null prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); gtDispTree(tree, nullptr, nullptr, true); } #endif tree->gtFlags &= ~GTF_EXCEPT; tree->gtFlags |= GTF_IND_NONFAULTING; // Set this flag to prevent reordering tree->gtFlags |= GTF_ORDER_SIDEEFF; return optAssertionProp_Update(tree, tree, stmt); } return nullptr; } //------------------------------------------------------------------------ // optAssertionIsNonNull: see if we can prove a tree's value will be non-null // based on assertions // // Arguments: // op - tree to check // assertions - set of live assertions // pVnBased - [out] set to true if value numbers were used // pIndex - [out] the assertion used in the proof // // Returns: // true if the tree's value will be non-null // // Notes: // Sets "pVnBased" if the assertion is value number based. If no matching // assertions are found from the table, then returns "NO_ASSERTION_INDEX." // // If both VN and assertion table yield a matching assertion, "pVnBased" // is only set and the return value is "NO_ASSERTION_INDEX." // bool Compiler::optAssertionIsNonNull(GenTree* op, ASSERT_VALARG_TP assertions DEBUGARG(bool* pVnBased) DEBUGARG(AssertionIndex* pIndex)) { bool vnBased = (!optLocalAssertionProp && vnStore->IsKnownNonNull(op->gtVNPair.GetConservative())); #ifdef DEBUG *pVnBased = vnBased; #endif if (vnBased) { #ifdef DEBUG *pIndex = NO_ASSERTION_INDEX; #endif return true; } AssertionIndex index = optAssertionIsNonNullInternal(op, assertions DEBUGARG(pVnBased)); #ifdef DEBUG *pIndex = index; #endif return index != NO_ASSERTION_INDEX; } //------------------------------------------------------------------------ // optAssertionIsNonNullInternal: see if we can prove a tree's value will // be non-null based on assertions // // Arguments: // op - tree to check // assertions - set of live assertions // pVnBased - [out] set to true if value numbers were used // // Returns: // index of assertion, or NO_ASSERTION_INDEX // AssertionIndex Compiler::optAssertionIsNonNullInternal(GenTree* op, ASSERT_VALARG_TP assertions DEBUGARG(bool* pVnBased)) { #ifdef DEBUG // Initialize the out param // *pVnBased = false; #endif // If local assertion prop use lcl comparison, else use VN comparison. if (!optLocalAssertionProp) { if (BitVecOps::MayBeUninit(assertions) || BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } // Look at both the top-level vn, and // the vn we get by stripping off any constant adds. // ValueNum vn = vnStore->VNConservativeNormalValue(op->gtVNPair); ValueNum vnBase = vn; VNFuncApp funcAttr; while (vnStore->GetVNFunc(vnBase, &funcAttr) && (funcAttr.m_func == (VNFunc)GT_ADD)) { if (vnStore->IsVNConstant(funcAttr.m_args[1]) && varTypeIsIntegral(vnStore->TypeOfVN(funcAttr.m_args[1]))) { vnBase = funcAttr.m_args[0]; } else if (vnStore->IsVNConstant(funcAttr.m_args[0]) && varTypeIsIntegral(vnStore->TypeOfVN(funcAttr.m_args[0]))) { vnBase = funcAttr.m_args[1]; } else { break; } } // Check each assertion to find if we have a vn != null assertion. // BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if (curAssertion->assertionKind != OAK_NOT_EQUAL) { continue; } if (curAssertion->op2.vn != ValueNumStore::VNForNull()) { continue; } if ((curAssertion->op1.vn != vn) && (curAssertion->op1.vn != vnBase)) { continue; } #ifdef DEBUG *pVnBased = true; #endif return assertionIndex; } } else { unsigned lclNum = op->AsLclVarCommon()->GetLclNum(); // Check each assertion to find if we have a variable == or != null assertion. for (AssertionIndex index = 1; index <= optAssertionCount; index++) { AssertionDsc* curAssertion = optGetAssertion(index); if ((curAssertion->assertionKind == OAK_NOT_EQUAL) && // kind (curAssertion->op1.kind == O1K_LCLVAR) && // op1 (curAssertion->op2.kind == O2K_CONST_INT) && // op2 (curAssertion->op1.lcl.lclNum == lclNum) && (curAssertion->op2.u1.iconVal == 0)) { return index; } } } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Given a tree consisting of a call and a set of available assertions, we * try to propagate a non-null assertion and modify the Call tree if we can. * Returns the modified tree, or nullptr if no assertion prop took place. * */ GenTree* Compiler::optNonNullAssertionProp_Call(ASSERT_VALARG_TP assertions, GenTreeCall* call) { if ((call->gtFlags & GTF_CALL_NULLCHECK) == 0) { return nullptr; } GenTree* op1 = gtGetThisArg(call); noway_assert(op1 != nullptr); if (op1->gtOper != GT_LCL_VAR) { return nullptr; } #ifdef DEBUG bool vnBased = false; AssertionIndex index = NO_ASSERTION_INDEX; #endif if (optAssertionIsNonNull(op1, assertions DEBUGARG(&vnBased) DEBUGARG(&index))) { #ifdef DEBUG if (verbose) { (vnBased) ? printf("\nVN based non-null prop in " FMT_BB ":\n", compCurBB->bbNum) : printf("\nNon-null prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); gtDispTree(call, nullptr, nullptr, true); } #endif call->gtFlags &= ~GTF_CALL_NULLCHECK; call->gtFlags &= ~GTF_EXCEPT; noway_assert(call->gtFlags & GTF_SIDE_EFFECT); return call; } return nullptr; } /***************************************************************************** * * Given a tree consisting of a call and a set of available assertions, we * try to propagate an assertion and modify the Call tree if we can. Our * current modifications are limited to removing the nullptrCHECK flag from * the call. * We pass in the root of the tree via 'stmt', for local copy prop 'stmt' * will be nullptr. Returns the modified tree, or nullptr if no assertion prop * took place. * */ GenTree* Compiler::optAssertionProp_Call(ASSERT_VALARG_TP assertions, GenTreeCall* call, Statement* stmt) { if (optNonNullAssertionProp_Call(assertions, call)) { return optAssertionProp_Update(call, call, stmt); } else if (!optLocalAssertionProp && (call->gtCallType == CT_HELPER)) { if (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFINTERFACE) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFARRAY) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFCLASS) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFANY) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTINTERFACE) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTARRAY) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTCLASS) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTANY) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTCLASS_SPECIAL)) { GenTree* arg1 = gtArgEntryByArgNum(call, 1)->GetNode(); if (arg1->gtOper != GT_LCL_VAR) { return nullptr; } GenTree* arg2 = gtArgEntryByArgNum(call, 0)->GetNode(); unsigned index = optAssertionIsSubtype(arg1, arg2, assertions); if (index != NO_ASSERTION_INDEX) { #ifdef DEBUG if (verbose) { printf("\nDid VN based subtype prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); gtDispTree(call, nullptr, nullptr, true); } #endif GenTree* list = nullptr; gtExtractSideEffList(call, &list, GTF_SIDE_EFFECT, true); if (list != nullptr) { arg1 = gtNewOperNode(GT_COMMA, call->TypeGet(), list, arg1); fgSetTreeSeq(arg1); } return optAssertionProp_Update(arg1, call, stmt); } } } return nullptr; } /***************************************************************************** * * Given a tree with a bounds check, remove it if it has already been checked in the program flow. */ GenTree* Compiler::optAssertionProp_BndsChk(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { if (optLocalAssertionProp) { return nullptr; } assert(tree->OperIs(GT_BOUNDS_CHECK)); #ifdef FEATURE_ENABLE_NO_RANGE_CHECKS if (JitConfig.JitNoRangeChks()) { #ifdef DEBUG if (verbose) { printf("\nFlagging check redundant due to JitNoRangeChks in " FMT_BB ":\n", compCurBB->bbNum); gtDispTree(tree, nullptr, nullptr, true); } #endif // DEBUG tree->gtFlags |= GTF_CHK_INDEX_INBND; return nullptr; } #endif // FEATURE_ENABLE_NO_RANGE_CHECKS BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } // If it is not a nothrow assertion, skip. AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if (!curAssertion->IsBoundsCheckNoThrow()) { continue; } GenTreeBoundsChk* arrBndsChk = tree->AsBoundsChk(); // Set 'isRedundant' to true if we can determine that 'arrBndsChk' can be // classified as a redundant bounds check using 'curAssertion' bool isRedundant = false; #ifdef DEBUG const char* dbgMsg = "Not Set"; #endif // Do we have a previous range check involving the same 'vnLen' upper bound? if (curAssertion->op1.bnd.vnLen == vnStore->VNConservativeNormalValue(arrBndsChk->GetArrayLength()->gtVNPair)) { ValueNum vnCurIdx = vnStore->VNConservativeNormalValue(arrBndsChk->GetIndex()->gtVNPair); // Do we have the exact same lower bound 'vnIdx'? // a[i] followed by a[i] if (curAssertion->op1.bnd.vnIdx == vnCurIdx) { isRedundant = true; #ifdef DEBUG dbgMsg = "a[i] followed by a[i]"; #endif } // Are we using zero as the index? // It can always be considered as redundant with any previous value // a[*] followed by a[0] else if (vnCurIdx == vnStore->VNZeroForType(arrBndsChk->GetIndex()->TypeGet())) { isRedundant = true; #ifdef DEBUG dbgMsg = "a[*] followed by a[0]"; #endif } // Do we have two constant indexes? else if (vnStore->IsVNConstant(curAssertion->op1.bnd.vnIdx) && vnStore->IsVNConstant(vnCurIdx)) { // Make sure the types match. var_types type1 = vnStore->TypeOfVN(curAssertion->op1.bnd.vnIdx); var_types type2 = vnStore->TypeOfVN(vnCurIdx); if (type1 == type2 && type1 == TYP_INT) { int index1 = vnStore->ConstantValue<int>(curAssertion->op1.bnd.vnIdx); int index2 = vnStore->ConstantValue<int>(vnCurIdx); // the case where index1 == index2 should have been handled above assert(index1 != index2); // It can always be considered as redundant with any previous higher constant value // a[K1] followed by a[K2], with K2 >= 0 and K1 >= K2 if (index2 >= 0 && index1 >= index2) { isRedundant = true; #ifdef DEBUG dbgMsg = "a[K1] followed by a[K2], with K2 >= 0 and K1 >= K2"; #endif } } } // Extend this to remove additional redundant bounds checks: // i.e. a[i+1] followed by a[i] by using the VN(i+1) >= VN(i) // a[i] followed by a[j] when j is known to be >= i // a[i] followed by a[5] when i is known to be >= 5 } if (!isRedundant) { continue; } #ifdef DEBUG if (verbose) { printf("\nVN based redundant (%s) bounds check assertion prop for index #%02u in " FMT_BB ":\n", dbgMsg, assertionIndex, compCurBB->bbNum); gtDispTree(tree, nullptr, nullptr, true); } #endif if (arrBndsChk == stmt->GetRootNode()) { // We have a top-level bounds check node. // This can happen when trees are broken up due to inlining. // optRemoveStandaloneRangeCheck will return the modified tree (side effects or a no-op). GenTree* newTree = optRemoveStandaloneRangeCheck(arrBndsChk, stmt); return optAssertionProp_Update(newTree, arrBndsChk, stmt); } // Defer actually removing the tree until processing reaches its parent comma, since // optRemoveCommaBasedRangeCheck needs to rewrite the whole comma tree. arrBndsChk->gtFlags |= GTF_CHK_INDEX_INBND; return nullptr; } return nullptr; } /***************************************************************************** * * Called when we have a successfully performed an assertion prop. We have * the newTree in hand. This method will replace the existing tree in the * stmt with the newTree. * */ GenTree* Compiler::optAssertionProp_Update(GenTree* newTree, GenTree* tree, Statement* stmt) { assert(newTree != nullptr); assert(tree != nullptr); if (stmt == nullptr) { noway_assert(optLocalAssertionProp); } else { noway_assert(!optLocalAssertionProp); // If newTree == tree then we modified the tree in-place otherwise we have to // locate our parent node and update it so that it points to newTree. if (newTree != tree) { FindLinkData linkData = gtFindLink(stmt, tree); GenTree** useEdge = linkData.result; GenTree* parent = linkData.parent; noway_assert(useEdge != nullptr); if (parent != nullptr) { parent->ReplaceOperand(useEdge, newTree); } else { // If there's no parent, the tree being replaced is the root of the // statement. assert((stmt->GetRootNode() == tree) && (stmt->GetRootNodePointer() == useEdge)); stmt->SetRootNode(newTree); } // We only need to ensure that the gtNext field is set as it is used to traverse // to the next node in the tree. We will re-morph this entire statement in // optAssertionPropMain(). It will reset the gtPrev and gtNext links for all nodes. newTree->gtNext = tree->gtNext; // Old tree should not be referenced anymore. DEBUG_DESTROY_NODE(tree); } } // Record that we propagated the assertion. optAssertionPropagated = true; optAssertionPropagatedCurrentStmt = true; return newTree; } //------------------------------------------------------------------------ // optAssertionProp: try and optimize a tree via assertion propagation // // Arguments: // assertions - set of live assertions // tree - tree to possibly optimize // stmt - statement containing the tree // block - block containing the statement // // Returns: // The modified tree, or nullptr if no assertion prop took place. // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optAssertionProp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt, BasicBlock* block) { switch (tree->gtOper) { case GT_LCL_VAR: return optAssertionProp_LclVar(assertions, tree->AsLclVarCommon(), stmt); case GT_ASG: return optAssertionProp_Asg(assertions, tree->AsOp(), stmt); case GT_RETURN: return optAssertionProp_Return(assertions, tree->AsUnOp(), stmt); case GT_OBJ: case GT_BLK: case GT_IND: case GT_NULLCHECK: case GT_STORE_DYN_BLK: return optAssertionProp_Ind(assertions, tree, stmt); case GT_BOUNDS_CHECK: return optAssertionProp_BndsChk(assertions, tree, stmt); case GT_COMMA: return optAssertionProp_Comma(assertions, tree, stmt); case GT_CAST: return optAssertionProp_Cast(assertions, tree->AsCast(), stmt); case GT_CALL: return optAssertionProp_Call(assertions, tree->AsCall(), stmt); case GT_EQ: case GT_NE: case GT_LT: case GT_LE: case GT_GT: case GT_GE: return optAssertionProp_RelOp(assertions, tree, stmt); case GT_JTRUE: if (block != nullptr) { return optVNConstantPropOnJTrue(block, tree); } return nullptr; default: return nullptr; } } //------------------------------------------------------------------------ // optImpliedAssertions: Given an assertion this method computes the set // of implied assertions that are also true. // // Arguments: // assertionIndex : The id of the assertion. // activeAssertions : The assertions that are already true at this point. // This method will add the discovered implied assertions // to this set. // void Compiler::optImpliedAssertions(AssertionIndex assertionIndex, ASSERT_TP& activeAssertions) { noway_assert(!optLocalAssertionProp); noway_assert(assertionIndex != 0); noway_assert(assertionIndex <= optAssertionCount); AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if (!BitVecOps::IsEmpty(apTraits, activeAssertions)) { const ASSERT_TP mappedAssertions = optGetVnMappedAssertions(curAssertion->op1.vn); if (mappedAssertions == nullptr) { return; } ASSERT_TP chkAssertions = BitVecOps::MakeCopy(apTraits, mappedAssertions); if (curAssertion->op2.kind == O2K_LCLVAR_COPY) { const ASSERT_TP op2Assertions = optGetVnMappedAssertions(curAssertion->op2.vn); if (op2Assertions != nullptr) { BitVecOps::UnionD(apTraits, chkAssertions, op2Assertions); } } BitVecOps::IntersectionD(apTraits, chkAssertions, activeAssertions); if (BitVecOps::IsEmpty(apTraits, chkAssertions)) { return; } // Check each assertion in chkAssertions to see if it can be applied to curAssertion BitVecOps::Iter chkIter(apTraits, chkAssertions); unsigned chkIndex = 0; while (chkIter.NextElem(&chkIndex)) { AssertionIndex chkAssertionIndex = GetAssertionIndex(chkIndex); if (chkAssertionIndex > optAssertionCount) { break; } if (chkAssertionIndex == assertionIndex) { continue; } // Determine which one is a copy assertion and use the other to check for implied assertions. AssertionDsc* iterAssertion = optGetAssertion(chkAssertionIndex); if (curAssertion->IsCopyAssertion()) { optImpliedByCopyAssertion(curAssertion, iterAssertion, activeAssertions); } else if (iterAssertion->IsCopyAssertion()) { optImpliedByCopyAssertion(iterAssertion, curAssertion, activeAssertions); } } } // Is curAssertion a constant assignment of a 32-bit integer? // (i.e GT_LVL_VAR X == GT_CNS_INT) else if ((curAssertion->assertionKind == OAK_EQUAL) && (curAssertion->op1.kind == O1K_LCLVAR) && (curAssertion->op2.kind == O2K_CONST_INT)) { optImpliedByConstAssertion(curAssertion, activeAssertions); } } /***************************************************************************** * * Given a set of active assertions this method computes the set * of non-Null implied assertions that are also true */ void Compiler::optImpliedByTypeOfAssertions(ASSERT_TP& activeAssertions) { if (BitVecOps::IsEmpty(apTraits, activeAssertions)) { return; } // Check each assertion in activeAssertions to see if it can be applied to constAssertion BitVecOps::Iter chkIter(apTraits, activeAssertions); unsigned chkIndex = 0; while (chkIter.NextElem(&chkIndex)) { AssertionIndex chkAssertionIndex = GetAssertionIndex(chkIndex); if (chkAssertionIndex > optAssertionCount) { break; } // chkAssertion must be Type/Subtype is equal assertion AssertionDsc* chkAssertion = optGetAssertion(chkAssertionIndex); if ((chkAssertion->op1.kind != O1K_SUBTYPE && chkAssertion->op1.kind != O1K_EXACT_TYPE) || (chkAssertion->assertionKind != OAK_EQUAL)) { continue; } // Search the assertion table for a non-null assertion on op1 that matches chkAssertion for (AssertionIndex impIndex = 1; impIndex <= optAssertionCount; impIndex++) { AssertionDsc* impAssertion = optGetAssertion(impIndex); // The impAssertion must be different from the chkAssertion if (impIndex == chkAssertionIndex) { continue; } // impAssertion must be a Non Null assertion on lclNum if ((impAssertion->assertionKind != OAK_NOT_EQUAL) || ((impAssertion->op1.kind != O1K_LCLVAR) && (impAssertion->op1.kind != O1K_VALUE_NUMBER)) || (impAssertion->op2.kind != O2K_CONST_INT) || (impAssertion->op1.vn != chkAssertion->op1.vn)) { continue; } // The bit may already be in the result set if (!BitVecOps::IsMember(apTraits, activeAssertions, impIndex - 1)) { BitVecOps::AddElemD(apTraits, activeAssertions, impIndex - 1); #ifdef DEBUG if (verbose) { printf("\nCompiler::optImpliedByTypeOfAssertions: %s Assertion #%02d, implies assertion #%02d", (chkAssertion->op1.kind == O1K_SUBTYPE) ? "Subtype" : "Exact-type", chkAssertionIndex, impIndex); } #endif } // There is at most one non-null assertion that is implied by the current chkIndex assertion break; } } } //------------------------------------------------------------------------ // optGetVnMappedAssertions: Given a value number, get the assertions // we have about the value number. // // Arguments: // vn - The given value number. // // Return Value: // The assertions we have about the value number. // ASSERT_VALRET_TP Compiler::optGetVnMappedAssertions(ValueNum vn) { ASSERT_TP set = BitVecOps::UninitVal(); if (optValueNumToAsserts->Lookup(vn, &set)) { return set; } return BitVecOps::UninitVal(); } /***************************************************************************** * * Given a const assertion this method computes the set of implied assertions * that are also true */ void Compiler::optImpliedByConstAssertion(AssertionDsc* constAssertion, ASSERT_TP& result) { noway_assert(constAssertion->assertionKind == OAK_EQUAL); noway_assert(constAssertion->op1.kind == O1K_LCLVAR); noway_assert(constAssertion->op2.kind == O2K_CONST_INT); ssize_t iconVal = constAssertion->op2.u1.iconVal; const ASSERT_TP chkAssertions = optGetVnMappedAssertions(constAssertion->op1.vn); if (chkAssertions == nullptr || BitVecOps::IsEmpty(apTraits, chkAssertions)) { return; } // Check each assertion in chkAssertions to see if it can be applied to constAssertion BitVecOps::Iter chkIter(apTraits, chkAssertions); unsigned chkIndex = 0; while (chkIter.NextElem(&chkIndex)) { AssertionIndex chkAssertionIndex = GetAssertionIndex(chkIndex); if (chkAssertionIndex > optAssertionCount) { break; } // The impAssertion must be different from the const assertion. AssertionDsc* impAssertion = optGetAssertion(chkAssertionIndex); if (impAssertion == constAssertion) { continue; } // The impAssertion must be an assertion about the same local var. if (impAssertion->op1.vn != constAssertion->op1.vn) { continue; } bool usable = false; switch (impAssertion->op2.kind) { case O2K_SUBRANGE: // Is the const assertion's constant, within implied assertion's bounds? usable = impAssertion->op2.u2.Contains(iconVal); break; case O2K_CONST_INT: // Is the const assertion's constant equal/not equal to the implied assertion? usable = ((impAssertion->assertionKind == OAK_EQUAL) && (impAssertion->op2.u1.iconVal == iconVal)) || ((impAssertion->assertionKind == OAK_NOT_EQUAL) && (impAssertion->op2.u1.iconVal != iconVal)); break; default: // leave 'usable' = false; break; } if (usable) { BitVecOps::AddElemD(apTraits, result, chkIndex); #ifdef DEBUG if (verbose) { AssertionDsc* firstAssertion = optGetAssertion(1); printf("Compiler::optImpliedByConstAssertion: const assertion #%02d implies assertion #%02d\n", (constAssertion - firstAssertion) + 1, (impAssertion - firstAssertion) + 1); } #endif } } } /***************************************************************************** * * Given a copy assertion and a dependent assertion this method computes the * set of implied assertions that are also true. * For copy assertions, exact SSA num and LCL nums should match, because * we don't have kill sets and we depend on their value num for dataflow. */ void Compiler::optImpliedByCopyAssertion(AssertionDsc* copyAssertion, AssertionDsc* depAssertion, ASSERT_TP& result) { noway_assert(copyAssertion->IsCopyAssertion()); // Get the copyAssert's lcl/ssa nums. unsigned copyAssertLclNum = BAD_VAR_NUM; unsigned copyAssertSsaNum = SsaConfig::RESERVED_SSA_NUM; // Check if copyAssertion's op1 or op2 matches the depAssertion's op1. if (depAssertion->op1.lcl.lclNum == copyAssertion->op1.lcl.lclNum) { copyAssertLclNum = copyAssertion->op2.lcl.lclNum; copyAssertSsaNum = copyAssertion->op2.lcl.ssaNum; } else if (depAssertion->op1.lcl.lclNum == copyAssertion->op2.lcl.lclNum) { copyAssertLclNum = copyAssertion->op1.lcl.lclNum; copyAssertSsaNum = copyAssertion->op1.lcl.ssaNum; } // Check if copyAssertion's op1 or op2 matches the depAssertion's op2. else if (depAssertion->op2.kind == O2K_LCLVAR_COPY) { if (depAssertion->op2.lcl.lclNum == copyAssertion->op1.lcl.lclNum) { copyAssertLclNum = copyAssertion->op2.lcl.lclNum; copyAssertSsaNum = copyAssertion->op2.lcl.ssaNum; } else if (depAssertion->op2.lcl.lclNum == copyAssertion->op2.lcl.lclNum) { copyAssertLclNum = copyAssertion->op1.lcl.lclNum; copyAssertSsaNum = copyAssertion->op1.lcl.ssaNum; } } if (copyAssertLclNum == BAD_VAR_NUM || copyAssertSsaNum == SsaConfig::RESERVED_SSA_NUM) { return; } // Get the depAssert's lcl/ssa nums. unsigned depAssertLclNum = BAD_VAR_NUM; unsigned depAssertSsaNum = SsaConfig::RESERVED_SSA_NUM; if ((depAssertion->op1.kind == O1K_LCLVAR) && (depAssertion->op2.kind == O2K_LCLVAR_COPY)) { if ((depAssertion->op1.lcl.lclNum == copyAssertion->op1.lcl.lclNum) || (depAssertion->op1.lcl.lclNum == copyAssertion->op2.lcl.lclNum)) { depAssertLclNum = depAssertion->op2.lcl.lclNum; depAssertSsaNum = depAssertion->op2.lcl.ssaNum; } else if ((depAssertion->op2.lcl.lclNum == copyAssertion->op1.lcl.lclNum) || (depAssertion->op2.lcl.lclNum == copyAssertion->op2.lcl.lclNum)) { depAssertLclNum = depAssertion->op1.lcl.lclNum; depAssertSsaNum = depAssertion->op1.lcl.ssaNum; } } if (depAssertLclNum == BAD_VAR_NUM || depAssertSsaNum == SsaConfig::RESERVED_SSA_NUM) { return; } // Is depAssertion a constant assignment of a 32-bit integer? // (i.e GT_LVL_VAR X == GT_CNS_INT) bool depIsConstAssertion = ((depAssertion->assertionKind == OAK_EQUAL) && (depAssertion->op1.kind == O1K_LCLVAR) && (depAssertion->op2.kind == O2K_CONST_INT)); // Search the assertion table for an assertion on op1 that matches depAssertion // The matching assertion is the implied assertion. for (AssertionIndex impIndex = 1; impIndex <= optAssertionCount; impIndex++) { AssertionDsc* impAssertion = optGetAssertion(impIndex); // The impAssertion must be different from the copy and dependent assertions if (impAssertion == copyAssertion || impAssertion == depAssertion) { continue; } if (!AssertionDsc::SameKind(depAssertion, impAssertion)) { continue; } bool op1MatchesCopy = (copyAssertLclNum == impAssertion->op1.lcl.lclNum) && (copyAssertSsaNum == impAssertion->op1.lcl.ssaNum); bool usable = false; switch (impAssertion->op2.kind) { case O2K_SUBRANGE: usable = op1MatchesCopy && impAssertion->op2.u2.Contains(depAssertion->op2.u2); break; case O2K_CONST_LONG: usable = op1MatchesCopy && (impAssertion->op2.lconVal == depAssertion->op2.lconVal); break; case O2K_CONST_DOUBLE: // Exact memory match because of positive and negative zero usable = op1MatchesCopy && (memcmp(&impAssertion->op2.dconVal, &depAssertion->op2.dconVal, sizeof(double)) == 0); break; case O2K_IND_CNS_INT: // This is the ngen case where we have an indirection of an address. noway_assert((impAssertion->op1.kind == O1K_EXACT_TYPE) || (impAssertion->op1.kind == O1K_SUBTYPE)); FALLTHROUGH; case O2K_CONST_INT: usable = op1MatchesCopy && (impAssertion->op2.u1.iconVal == depAssertion->op2.u1.iconVal); break; case O2K_LCLVAR_COPY: // Check if op1 of impAssertion matches copyAssertion and also op2 of impAssertion matches depAssertion. if (op1MatchesCopy && (depAssertLclNum == impAssertion->op2.lcl.lclNum && depAssertSsaNum == impAssertion->op2.lcl.ssaNum)) { usable = true; } else { // Otherwise, op2 of impAssertion should match copyAssertion and also op1 of impAssertion matches // depAssertion. usable = ((copyAssertLclNum == impAssertion->op2.lcl.lclNum && copyAssertSsaNum == impAssertion->op2.lcl.ssaNum) && (depAssertLclNum == impAssertion->op1.lcl.lclNum && depAssertSsaNum == impAssertion->op1.lcl.ssaNum)); } break; default: // leave 'usable' = false; break; } if (usable) { BitVecOps::AddElemD(apTraits, result, impIndex - 1); #ifdef DEBUG if (verbose) { AssertionDsc* firstAssertion = optGetAssertion(1); printf("\nCompiler::optImpliedByCopyAssertion: copyAssertion #%02d and depAssertion #%02d, implies " "assertion #%02d", (copyAssertion - firstAssertion) + 1, (depAssertion - firstAssertion) + 1, (impAssertion - firstAssertion) + 1); } #endif // If the depAssertion is a const assertion then any other assertions that it implies could also imply a // subrange assertion. if (depIsConstAssertion) { optImpliedByConstAssertion(impAssertion, result); } } } } #include "dataflow.h" /***************************************************************************** * * Dataflow visitor like callback so that all dataflow is in a single place * */ class AssertionPropFlowCallback { private: ASSERT_TP preMergeOut; ASSERT_TP preMergeJumpDestOut; ASSERT_TP* mJumpDestOut; ASSERT_TP* mJumpDestGen; BitVecTraits* apTraits; public: AssertionPropFlowCallback(Compiler* pCompiler, ASSERT_TP* jumpDestOut, ASSERT_TP* jumpDestGen) : preMergeOut(BitVecOps::UninitVal()) , preMergeJumpDestOut(BitVecOps::UninitVal()) , mJumpDestOut(jumpDestOut) , mJumpDestGen(jumpDestGen) , apTraits(pCompiler->apTraits) { } // At the start of the merge function of the dataflow equations, initialize premerge state (to detect change.) void StartMerge(BasicBlock* block) { if (VerboseDataflow()) { JITDUMP("StartMerge: " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("in -> ", block->bbAssertionIn, "\n"); } BitVecOps::Assign(apTraits, preMergeOut, block->bbAssertionOut); BitVecOps::Assign(apTraits, preMergeJumpDestOut, mJumpDestOut[block->bbNum]); } // During merge, perform the actual merging of the predecessor's (since this is a forward analysis) dataflow flags. void Merge(BasicBlock* block, BasicBlock* predBlock, unsigned dupCount) { ASSERT_TP pAssertionOut; if (predBlock->bbJumpKind == BBJ_COND && (predBlock->bbJumpDest == block)) { pAssertionOut = mJumpDestOut[predBlock->bbNum]; if (dupCount > 1) { // Scenario where next block and conditional block, both point to the same block. // In such case, intersect the assertions present on both the out edges of predBlock. assert(predBlock->bbNext == block); BitVecOps::IntersectionD(apTraits, pAssertionOut, predBlock->bbAssertionOut); if (VerboseDataflow()) { JITDUMP("Merge : Duplicate flow, " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("in -> ", block->bbAssertionIn, "; "); JITDUMP("pred " FMT_BB " ", predBlock->bbNum); Compiler::optDumpAssertionIndices("out1 -> ", mJumpDestOut[predBlock->bbNum], "; "); Compiler::optDumpAssertionIndices("out2 -> ", predBlock->bbAssertionOut, "\n"); } } } else { pAssertionOut = predBlock->bbAssertionOut; } if (VerboseDataflow()) { JITDUMP("Merge : " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("in -> ", block->bbAssertionIn, "; "); JITDUMP("pred " FMT_BB " ", predBlock->bbNum); Compiler::optDumpAssertionIndices("out -> ", pAssertionOut, "\n"); } BitVecOps::IntersectionD(apTraits, block->bbAssertionIn, pAssertionOut); } //------------------------------------------------------------------------ // MergeHandler: Merge assertions into the first exception handler/filter block. // // Arguments: // block - the block that is the start of a handler or filter; // firstTryBlock - the first block of the try for "block" handler; // lastTryBlock - the last block of the try for "block" handler;. // // Notes: // We can jump to the handler from any instruction in the try region. // It means we can propagate only assertions that are valid for the whole try region. void MergeHandler(BasicBlock* block, BasicBlock* firstTryBlock, BasicBlock* lastTryBlock) { if (VerboseDataflow()) { JITDUMP("Merge : " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("in -> ", block->bbAssertionIn, "; "); JITDUMP("firstTryBlock " FMT_BB " ", firstTryBlock->bbNum); Compiler::optDumpAssertionIndices("in -> ", firstTryBlock->bbAssertionIn, "; "); JITDUMP("lastTryBlock " FMT_BB " ", lastTryBlock->bbNum); Compiler::optDumpAssertionIndices("out -> ", lastTryBlock->bbAssertionOut, "\n"); } BitVecOps::IntersectionD(apTraits, block->bbAssertionIn, firstTryBlock->bbAssertionIn); BitVecOps::IntersectionD(apTraits, block->bbAssertionIn, lastTryBlock->bbAssertionOut); } // At the end of the merge store results of the dataflow equations, in a postmerge state. bool EndMerge(BasicBlock* block) { if (VerboseDataflow()) { JITDUMP("EndMerge : " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("in -> ", block->bbAssertionIn, "\n\n"); } BitVecOps::DataFlowD(apTraits, block->bbAssertionOut, block->bbAssertionGen, block->bbAssertionIn); BitVecOps::DataFlowD(apTraits, mJumpDestOut[block->bbNum], mJumpDestGen[block->bbNum], block->bbAssertionIn); bool changed = (!BitVecOps::Equal(apTraits, preMergeOut, block->bbAssertionOut) || !BitVecOps::Equal(apTraits, preMergeJumpDestOut, mJumpDestOut[block->bbNum])); if (VerboseDataflow()) { if (changed) { JITDUMP("Changed : " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("before out -> ", preMergeOut, "; "); Compiler::optDumpAssertionIndices("after out -> ", block->bbAssertionOut, ";\n "); Compiler::optDumpAssertionIndices("jumpDest before out -> ", preMergeJumpDestOut, "; "); Compiler::optDumpAssertionIndices("jumpDest after out -> ", mJumpDestOut[block->bbNum], ";\n\n"); } else { JITDUMP("Unchanged : " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("out -> ", block->bbAssertionOut, "; "); Compiler::optDumpAssertionIndices("jumpDest out -> ", mJumpDestOut[block->bbNum], "\n\n"); } } return changed; } // Can be enabled to get detailed debug output about dataflow for assertions. bool VerboseDataflow() { #if 0 return VERBOSE; #endif return false; } }; /***************************************************************************** * * Compute the assertions generated by each block. */ ASSERT_TP* Compiler::optComputeAssertionGen() { ASSERT_TP* jumpDestGen = fgAllocateTypeForEachBlk<ASSERT_TP>(); for (BasicBlock* const block : Blocks()) { ASSERT_TP valueGen = BitVecOps::MakeEmpty(apTraits); GenTree* jtrue = nullptr; // Walk the statement trees in this basic block. for (Statement* const stmt : block->Statements()) { for (GenTree* const tree : stmt->TreeList()) { if (tree->gtOper == GT_JTRUE) { // A GT_TRUE is always the last node in a tree, so we can break here assert((tree->gtNext == nullptr) && (stmt->GetNextStmt() == nullptr)); jtrue = tree; break; } if (tree->GeneratesAssertion()) { AssertionInfo info = tree->GetAssertionInfo(); optImpliedAssertions(info.GetAssertionIndex(), valueGen); BitVecOps::AddElemD(apTraits, valueGen, info.GetAssertionIndex() - 1); } } } if (jtrue != nullptr) { // Copy whatever we have accumulated into jumpDest edge's valueGen. ASSERT_TP jumpDestValueGen = BitVecOps::MakeCopy(apTraits, valueGen); if (jtrue->GeneratesAssertion()) { AssertionInfo info = jtrue->GetAssertionInfo(); AssertionIndex valueAssertionIndex; AssertionIndex jumpDestAssertionIndex; if (info.IsNextEdgeAssertion()) { valueAssertionIndex = info.GetAssertionIndex(); jumpDestAssertionIndex = optFindComplementary(info.GetAssertionIndex()); } else // is jump edge assertion { jumpDestAssertionIndex = info.GetAssertionIndex(); valueAssertionIndex = optFindComplementary(jumpDestAssertionIndex); } if (valueAssertionIndex != NO_ASSERTION_INDEX) { // Update valueGen if we have an assertion for the bbNext edge optImpliedAssertions(valueAssertionIndex, valueGen); BitVecOps::AddElemD(apTraits, valueGen, valueAssertionIndex - 1); } if (jumpDestAssertionIndex != NO_ASSERTION_INDEX) { // Update jumpDestValueGen if we have an assertion for the bbJumpDest edge optImpliedAssertions(jumpDestAssertionIndex, jumpDestValueGen); BitVecOps::AddElemD(apTraits, jumpDestValueGen, jumpDestAssertionIndex - 1); } } jumpDestGen[block->bbNum] = jumpDestValueGen; } else { jumpDestGen[block->bbNum] = BitVecOps::MakeEmpty(apTraits); } block->bbAssertionGen = valueGen; #ifdef DEBUG if (verbose) { if (block == fgFirstBB) { printf("\n"); } printf(FMT_BB " valueGen = ", block->bbNum); optPrintAssertionIndices(block->bbAssertionGen); if (block->bbJumpKind == BBJ_COND) { printf(" => " FMT_BB " valueGen = ", block->bbJumpDest->bbNum); optPrintAssertionIndices(jumpDestGen[block->bbNum]); } printf("\n"); if (block == fgLastBB) { printf("\n"); } } #endif } return jumpDestGen; } /***************************************************************************** * * Initialize the assertion data flow flags that will be propagated. */ ASSERT_TP* Compiler::optInitAssertionDataflowFlags() { ASSERT_TP* jumpDestOut = fgAllocateTypeForEachBlk<ASSERT_TP>(); // The local assertion gen phase may have created unreachable blocks. // They will never be visited in the dataflow propagation phase, so they need to // be initialized correctly. This means that instead of setting their sets to // apFull (i.e. all possible bits set), we need to set the bits only for valid // assertions (note that at this point we are not creating any new assertions). // Also note that assertion indices start from 1. ASSERT_TP apValidFull = BitVecOps::MakeEmpty(apTraits); for (int i = 1; i <= optAssertionCount; i++) { BitVecOps::AddElemD(apTraits, apValidFull, i - 1); } // Initially estimate the OUT sets to everything except killed expressions // Also set the IN sets to 1, so that we can perform the intersection. for (BasicBlock* const block : Blocks()) { block->bbAssertionIn = BitVecOps::MakeCopy(apTraits, apValidFull); block->bbAssertionGen = BitVecOps::MakeEmpty(apTraits); block->bbAssertionOut = BitVecOps::MakeCopy(apTraits, apValidFull); jumpDestOut[block->bbNum] = BitVecOps::MakeCopy(apTraits, apValidFull); } // Compute the data flow values for all tracked expressions // IN and OUT never change for the initial basic block B1 BitVecOps::ClearD(apTraits, fgFirstBB->bbAssertionIn); return jumpDestOut; } // Callback data for the VN based constant prop visitor. struct VNAssertionPropVisitorInfo { Compiler* pThis; Statement* stmt; BasicBlock* block; VNAssertionPropVisitorInfo(Compiler* pThis, BasicBlock* block, Statement* stmt) : pThis(pThis), stmt(stmt), block(block) { } }; //------------------------------------------------------------------------------ // optExtractSideEffListFromConst // Extracts side effects from a tree so it can be replaced with a comma // separated list of side effects + a const tree. // // Note: // The caller expects that the root of the tree has no side effects and it // won't be extracted. Otherwise the resulting comma tree would be bigger // than the tree before optimization. // // Arguments: // tree - The tree node with constant value to extrace side-effects from. // // Return Value: // 1. Returns the extracted side-effects from "tree" // 2. When no side-effects are present, returns null. // // GenTree* Compiler::optExtractSideEffListFromConst(GenTree* tree) { assert(vnStore->IsVNConstant(vnStore->VNConservativeNormalValue(tree->gtVNPair)) || vnStore->IsVNVectorZero(vnStore->VNConservativeNormalValue(tree->gtVNPair))); GenTree* sideEffList = nullptr; // If we have side effects, extract them. if ((tree->gtFlags & GTF_SIDE_EFFECT) != 0) { // Do a sanity check to ensure persistent side effects aren't discarded and // tell gtExtractSideEffList to ignore the root of the tree. // We are relying here on an invariant that VN will only fold non-throwing expressions. const bool ignoreExceptions = true; const bool ignoreCctors = false; // We have to check "AsCall()->HasSideEffects()" here separately because "gtNodeHasSideEffects" // also checks for side effects that arguments introduce (incosistently so, it otherwise only // checks for the side effects the node itself has). TODO-Cleanup: change it to not do that? assert(!gtNodeHasSideEffects(tree, GTF_PERSISTENT_SIDE_EFFECTS) || (tree->IsCall() && !tree->AsCall()->HasSideEffects(this, ignoreExceptions, ignoreCctors))); // Exception side effects may be ignored because the root is known to be a constant // (e.g. VN may evaluate a DIV/MOD node to a constant and the node may still // have GTF_EXCEPT set, even if it does not actually throw any exceptions). bool ignoreRoot = true; gtExtractSideEffList(tree, &sideEffList, GTF_SIDE_EFFECT, ignoreRoot); JITDUMP("Extracted side effects from a constant tree [%06u]:\n", tree->gtTreeID); DISPTREE(sideEffList); } return sideEffList; } //------------------------------------------------------------------------------ // optVNConstantPropOnJTrue // Constant propagate on the JTrue node by extracting side effects and moving // them into their own statements. The relop node is then modified to yield // true or false, so the branch can be folded. // // Arguments: // block - The block that contains the JTrue. // test - The JTrue node whose relop evaluates to 0 or non-zero value. // // Return Value: // The jmpTrue tree node that has relop of the form "0 =/!= 0". // If "tree" evaluates to "true" relop is "0 == 0". Else relop is "0 != 0". // // Description: // Special treatment for JTRUE nodes' constant propagation. This is because // for JTRUE(1) or JTRUE(0), if there are side effects they need to be put // in separate statements. This is to prevent relop's constant // propagation from doing a simple minded conversion from // (1) STMT(JTRUE(RELOP(COMMA(sideEffect, OP1), OP2)), S.T. op1 =/!= op2 to // (2) STMT(JTRUE(COMMA(sideEffect, 1/0)). // // fgFoldConditional doesn't fold (2), a side-effecting JTRUE's op1. So, let us, // here, convert (1) as two statements: STMT(sideEffect), STMT(JTRUE(1/0)), // so that the JTRUE will get folded by fgFoldConditional. // // Note: fgFoldConditional is called from other places as well, which may be // sensitive to adding new statements. Hence the change is not made directly // into fgFoldConditional. // GenTree* Compiler::optVNConstantPropOnJTrue(BasicBlock* block, GenTree* test) { GenTree* relop = test->gtGetOp1(); // VN based assertion non-null on this relop has been performed. if (!relop->OperIsCompare()) { return nullptr; } // // Make sure GTF_RELOP_JMP_USED flag is set so that we can later skip constant // prop'ing a JTRUE's relop child node for a second time in the pre-order // tree walk. // assert((relop->gtFlags & GTF_RELOP_JMP_USED) != 0); // We want to use the Normal ValueNumber when checking for constants. ValueNum vnCns = vnStore->VNConservativeNormalValue(relop->gtVNPair); ValueNum vnLib = vnStore->VNLiberalNormalValue(relop->gtVNPair); if (!vnStore->IsVNConstant(vnCns)) { return nullptr; } // Prepare the tree for replacement so any side effects can be extracted. GenTree* sideEffList = optExtractSideEffListFromConst(relop); // Transform the relop's operands to be both zeroes. ValueNum vnZero = vnStore->VNZeroForType(TYP_INT); relop->AsOp()->gtOp1 = gtNewIconNode(0); relop->AsOp()->gtOp1->gtVNPair = ValueNumPair(vnZero, vnZero); relop->AsOp()->gtOp2 = gtNewIconNode(0); relop->AsOp()->gtOp2->gtVNPair = ValueNumPair(vnZero, vnZero); // Update the oper and restore the value numbers. bool evalsToTrue = (vnStore->CoercedConstantValue<INT64>(vnCns) != 0); relop->SetOper(evalsToTrue ? GT_EQ : GT_NE); relop->gtVNPair = ValueNumPair(vnLib, vnCns); // Insert side effects back after they were removed from the JTrue stmt. // It is important not to allow duplicates exist in the IR, that why we delete // these side effects from the JTrue stmt before insert them back here. while (sideEffList != nullptr) { Statement* newStmt; if (sideEffList->OperGet() == GT_COMMA) { newStmt = fgNewStmtNearEnd(block, sideEffList->gtGetOp1()); sideEffList = sideEffList->gtGetOp2(); } else { newStmt = fgNewStmtNearEnd(block, sideEffList); sideEffList = nullptr; } // fgMorphBlockStmt could potentially affect stmts after the current one, // for example when it decides to fgRemoveRestOfBlock. fgMorphBlockStmt(block, newStmt DEBUGARG(__FUNCTION__)); } return test; } //------------------------------------------------------------------------------ // optVNConstantPropCurStmt // Performs constant prop on the current statement's tree nodes. // // Assumption: // This function is called as part of a pre-order tree walk. // // Arguments: // tree - The currently visited tree node. // stmt - The statement node in which the "tree" is present. // block - The block that contains the statement that contains the tree. // // Return Value: // Returns the standard visitor walk result. // // Description: // Checks if a node is an R-value and evaluates to a constant. If the node // evaluates to constant, then the tree is replaced by its side effects and // the constant node. // Compiler::fgWalkResult Compiler::optVNConstantPropCurStmt(BasicBlock* block, Statement* stmt, GenTree* tree) { // Don't perform const prop on expressions marked with GTF_DONT_CSE if (!tree->CanCSE()) { return WALK_CONTINUE; } // Don't propagate floating-point constants into a TYP_STRUCT LclVar // This can occur for HFA return values (see hfa_sf3E_r.exe) if (tree->TypeGet() == TYP_STRUCT) { return WALK_CONTINUE; } switch (tree->OperGet()) { // Make sure we have an R-value. case GT_ADD: case GT_SUB: case GT_DIV: case GT_MOD: case GT_UDIV: case GT_UMOD: case GT_EQ: case GT_NE: case GT_LT: case GT_LE: case GT_GE: case GT_GT: case GT_OR: case GT_XOR: case GT_AND: case GT_LSH: case GT_RSH: case GT_RSZ: case GT_NEG: case GT_CAST: case GT_INTRINSIC: break; case GT_JTRUE: break; case GT_MUL: // Don't transform long multiplies. if (tree->gtFlags & GTF_MUL_64RSLT) { return WALK_SKIP_SUBTREES; } break; case GT_LCL_VAR: case GT_LCL_FLD: // Make sure the local variable is an R-value. if ((tree->gtFlags & (GTF_VAR_USEASG | GTF_VAR_DEF | GTF_DONT_CSE)) != GTF_EMPTY) { return WALK_CONTINUE; } // Let's not conflict with CSE (to save the movw/movt). if (lclNumIsCSE(tree->AsLclVarCommon()->GetLclNum())) { return WALK_CONTINUE; } break; case GT_CALL: if (!tree->AsCall()->IsPure(this)) { return WALK_CONTINUE; } break; default: // Unknown node, continue to walk. return WALK_CONTINUE; } // Perform the constant propagation GenTree* newTree = optVNConstantPropOnTree(block, tree); if (newTree == nullptr) { // Not propagated, keep going. return WALK_CONTINUE; } // Successful propagation, mark as assertion propagated and skip // sub-tree (with side-effects) visits. // TODO #18291: at that moment stmt could be already removed from the stmt list. optAssertionProp_Update(newTree, tree, stmt); JITDUMP("After constant propagation on [%06u]:\n", tree->gtTreeID); DBEXEC(VERBOSE, gtDispStmt(stmt)); return WALK_SKIP_SUBTREES; } //------------------------------------------------------------------------------ // optVnNonNullPropCurStmt // Performs VN based non-null propagation on the tree node. // // Assumption: // This function is called as part of a pre-order tree walk. // // Arguments: // block - The block that contains the statement that contains the tree. // stmt - The statement node in which the "tree" is present. // tree - The currently visited tree node. // // Return Value: // None. // // Description: // Performs value number based non-null propagation on GT_CALL and // indirections. This is different from flow based assertions and helps // unify VN based constant prop and non-null prop in a single pre-order walk. // void Compiler::optVnNonNullPropCurStmt(BasicBlock* block, Statement* stmt, GenTree* tree) { ASSERT_TP empty = BitVecOps::UninitVal(); GenTree* newTree = nullptr; if (tree->OperGet() == GT_CALL) { newTree = optNonNullAssertionProp_Call(empty, tree->AsCall()); } else if (tree->OperIsIndir()) { newTree = optAssertionProp_Ind(empty, tree, stmt); } if (newTree) { assert(newTree == tree); optAssertionProp_Update(newTree, tree, stmt); } } //------------------------------------------------------------------------------ // optVNAssertionPropCurStmtVisitor // Unified Value Numbering based assertion propagation visitor. // // Assumption: // This function is called as part of a pre-order tree walk. // // Return Value: // WALK_RESULTs. // // Description: // An unified value numbering based assertion prop visitor that // performs non-null and constant assertion propagation based on // value numbers. // /* static */ Compiler::fgWalkResult Compiler::optVNAssertionPropCurStmtVisitor(GenTree** ppTree, fgWalkData* data) { VNAssertionPropVisitorInfo* pData = (VNAssertionPropVisitorInfo*)data->pCallbackData; Compiler* pThis = pData->pThis; pThis->optVnNonNullPropCurStmt(pData->block, pData->stmt, *ppTree); return pThis->optVNConstantPropCurStmt(pData->block, pData->stmt, *ppTree); } /***************************************************************************** * * Perform VN based i.e., data flow based assertion prop first because * even if we don't gen new control flow assertions, we still propagate * these first. * * Returns the skipped next stmt if the current statement or next few * statements got removed, else just returns the incoming stmt. */ Statement* Compiler::optVNAssertionPropCurStmt(BasicBlock* block, Statement* stmt) { // TODO-Review: EH successor/predecessor iteration seems broken. // See: SELF_HOST_TESTS_ARM\jit\Directed\ExcepFilters\fault\fault.exe if (block->bbCatchTyp == BBCT_FAULT) { return stmt; } // Preserve the prev link before the propagation and morph. Statement* prev = (stmt == block->firstStmt()) ? nullptr : stmt->GetPrevStmt(); // Perform VN based assertion prop first, in case we don't find // anything in assertion gen. optAssertionPropagatedCurrentStmt = false; VNAssertionPropVisitorInfo data(this, block, stmt); fgWalkTreePre(stmt->GetRootNodePointer(), Compiler::optVNAssertionPropCurStmtVisitor, &data); if (optAssertionPropagatedCurrentStmt) { fgMorphBlockStmt(block, stmt DEBUGARG("optVNAssertionPropCurStmt")); } // Check if propagation removed statements starting from current stmt. // If so, advance to the next good statement. Statement* nextStmt = (prev == nullptr) ? block->firstStmt() : prev->GetNextStmt(); return nextStmt; } /***************************************************************************** * * The entry point for assertion propagation */ void Compiler::optAssertionPropMain() { if (fgSsaPassesCompleted == 0) { return; } #ifdef DEBUG if (verbose) { printf("*************** In optAssertionPropMain()\n"); printf("Blocks/Trees at start of phase\n"); fgDispBasicBlocks(true); } #endif optAssertionInit(false); noway_assert(optAssertionCount == 0); // First discover all value assignments and record them in the table. for (BasicBlock* const block : Blocks()) { compCurBB = block; fgRemoveRestOfBlock = false; Statement* stmt = block->firstStmt(); while (stmt != nullptr) { // We need to remove the rest of the block. if (fgRemoveRestOfBlock) { fgRemoveStmt(block, stmt); stmt = stmt->GetNextStmt(); continue; } else { // Perform VN based assertion prop before assertion gen. Statement* nextStmt = optVNAssertionPropCurStmt(block, stmt); // Propagation resulted in removal of the remaining stmts, perform it. if (fgRemoveRestOfBlock) { stmt = stmt->GetNextStmt(); continue; } // Propagation removed the current stmt or next few stmts, so skip them. if (stmt != nextStmt) { stmt = nextStmt; continue; } } // Perform assertion gen for control flow based assertions. for (GenTree* const tree : stmt->TreeList()) { optAssertionGen(tree); } // Advance the iterator stmt = stmt->GetNextStmt(); } } if (optAssertionCount == 0) { // Zero out the bbAssertionIn values, as these can be referenced in RangeCheck::MergeAssertion // and this is sharedstate with the CSE phase: bbCseIn // for (BasicBlock* const block : Blocks()) { block->bbAssertionIn = BitVecOps::MakeEmpty(apTraits); } return; } #ifdef DEBUG fgDebugCheckLinks(); #endif // Allocate the bits for the predicate sensitive dataflow analysis bbJtrueAssertionOut = optInitAssertionDataflowFlags(); ASSERT_TP* jumpDestGen = optComputeAssertionGen(); // Modified dataflow algorithm for available expressions. DataFlow flow(this); AssertionPropFlowCallback ap(this, bbJtrueAssertionOut, jumpDestGen); if (ap.VerboseDataflow()) { JITDUMP("AssertionPropFlowCallback:\n\n") } flow.ForwardAnalysis(ap); for (BasicBlock* const block : Blocks()) { // Compute any implied non-Null assertions for block->bbAssertionIn optImpliedByTypeOfAssertions(block->bbAssertionIn); } #ifdef DEBUG if (verbose) { for (BasicBlock* const block : Blocks()) { printf(FMT_BB ":\n", block->bbNum); optDumpAssertionIndices(" in = ", block->bbAssertionIn, "\n"); optDumpAssertionIndices(" out = ", block->bbAssertionOut, "\n"); if (block->bbJumpKind == BBJ_COND) { printf(" " FMT_BB " = ", block->bbJumpDest->bbNum); optDumpAssertionIndices(bbJtrueAssertionOut[block->bbNum], "\n"); } } printf("\n"); } #endif // DEBUG ASSERT_TP assertions = BitVecOps::MakeEmpty(apTraits); // Perform assertion propagation (and constant folding) for (BasicBlock* const block : Blocks()) { BitVecOps::Assign(apTraits, assertions, block->bbAssertionIn); // TODO-Review: EH successor/predecessor iteration seems broken. // SELF_HOST_TESTS_ARM\jit\Directed\ExcepFilters\fault\fault.exe if (block->bbCatchTyp == BBCT_FAULT) { continue; } // Make the current basic block address available globally. compCurBB = block; fgRemoveRestOfBlock = false; // Walk the statement trees in this basic block Statement* stmt = block->FirstNonPhiDef(); while (stmt != nullptr) { // Propagation tells us to remove the rest of the block. Remove it. if (fgRemoveRestOfBlock) { fgRemoveStmt(block, stmt); stmt = stmt->GetNextStmt(); continue; } // Preserve the prev link before the propagation and morph, to check if propagation // removes the current stmt. Statement* prevStmt = (stmt == block->firstStmt()) ? nullptr : stmt->GetPrevStmt(); optAssertionPropagatedCurrentStmt = false; // set to true if a assertion propagation took place // and thus we must morph, set order, re-link for (GenTree* tree = stmt->GetTreeList(); tree != nullptr; tree = tree->gtNext) { optDumpAssertionIndices("Propagating ", assertions, " "); JITDUMP("for " FMT_BB ", stmt " FMT_STMT ", tree [%06d]", block->bbNum, stmt->GetID(), dspTreeID(tree)); JITDUMP(", tree -> "); JITDUMPEXEC(optPrintAssertionIndex(tree->GetAssertionInfo().GetAssertionIndex())); JITDUMP("\n"); GenTree* newTree = optAssertionProp(assertions, tree, stmt, block); if (newTree) { assert(optAssertionPropagatedCurrentStmt == true); tree = newTree; } // If this tree makes an assertion - make it available. if (tree->GeneratesAssertion()) { AssertionInfo info = tree->GetAssertionInfo(); optImpliedAssertions(info.GetAssertionIndex(), assertions); BitVecOps::AddElemD(apTraits, assertions, info.GetAssertionIndex() - 1); } } if (optAssertionPropagatedCurrentStmt) { #ifdef DEBUG if (verbose) { printf("Re-morphing this stmt:\n"); gtDispStmt(stmt); printf("\n"); } #endif // Re-morph the statement. fgMorphBlockStmt(block, stmt DEBUGARG("optAssertionPropMain")); } // Check if propagation removed statements starting from current stmt. // If so, advance to the next good statement. Statement* nextStmt = (prevStmt == nullptr) ? block->firstStmt() : prevStmt->GetNextStmt(); stmt = (stmt == nextStmt) ? stmt->GetNextStmt() : nextStmt; } optAssertionPropagatedCurrentStmt = false; // clear it back as we are done with stmts. } #ifdef DEBUG fgDebugCheckBBlist(); fgDebugCheckLinks(); #endif }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/libraries/System.Linq.Expressions/tests/DelegateType/ActionTypeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Linq.Expressions.Tests { public class ActionTypeTests : DelegateCreationTests { [Fact] public void NullTypeList() { AssertExtensions.Throws<ArgumentNullException>("typeArgs", () => Expression.GetActionType(default(Type[]))); } [Fact] public void NullInTypeList() { AssertExtensions.Throws<ArgumentNullException>("typeArgs", () => Expression.GetActionType(typeof(int), null)); } [Theory] [MemberData(nameof(EmptyTypeArgs))] [MemberData(nameof(ValidTypeArgs), false)] public void SuccessfulGetActionType(Type[] typeArgs) { Type funcType = Expression.GetActionType(typeArgs); if (typeArgs.Length == 0) { Assert.Equal(typeof(Action), funcType); } else { Assert.StartsWith("System.Action`" + typeArgs.Length, funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } } [Theory] [MemberData(nameof(EmptyTypeArgs))] [MemberData(nameof(ValidTypeArgs), false)] public void SuccessfulTryGetActionType(Type[] typeArgs) { Type funcType; Assert.True(Expression.TryGetActionType(typeArgs, out funcType)); if (typeArgs.Length == 0) { Assert.Equal(typeof(Action), funcType); } else { Assert.StartsWith("System.Action`" + typeArgs.Length, funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } } // Open generic type args aren't useful directly with Expressions, but creating them is allowed. [Theory, MemberData(nameof(OpenGenericTypeArgs), false)] public void SuccessfulGetActionTypeOpenGeneric(Type[] typeArgs) { Type funcType = Expression.GetActionType(typeArgs); Assert.Equal("Action`" + typeArgs.Length, funcType.Name); Assert.Null(funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Theory, MemberData(nameof(OpenGenericTypeArgs), false)] public void SuccessfulTryGetActionTypeWithOpenGeneric(Type[] typeArgs) { Type funcType; Assert.True(Expression.TryGetActionType(typeArgs, out funcType)); Assert.Equal("Action`" + typeArgs.Length, funcType.Name); Assert.Null(funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Theory] [MemberData(nameof(ExcessiveLengthTypeArgs))] [MemberData(nameof(ExcessiveLengthOpenGenericTypeArgs))] [MemberData(nameof(ByRefTypeArgs))] [MemberData(nameof(PointerTypeArgs))] [MemberData(nameof(ManagedPointerTypeArgs))] [MemberData(nameof(VoidTypeArgs), true)] public void UnsuccessfulGetActionType(Type[] typeArgs) { string paramName = typeArgs.Any(t => t == typeof(void)) || typeArgs.Count(t => t.IsPointer) == 1 ? null : "typeArgs"; AssertExtensions.Throws<ArgumentException>(paramName, () => Expression.GetActionType(typeArgs)); } [Theory] [MemberData(nameof(ExcessiveLengthTypeArgs))] [MemberData(nameof(ExcessiveLengthOpenGenericTypeArgs))] [MemberData(nameof(ByRefTypeArgs))] [MemberData(nameof(PointerTypeArgs))] [MemberData(nameof(ManagedPointerTypeArgs))] [MemberData(nameof(VoidTypeArgs), true)] public void UnsuccessfulTryGetActionType(Type[] typeArgs) { Type funcType; Assert.False(Expression.TryGetActionType(typeArgs, out funcType)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Linq.Expressions.Tests { public class ActionTypeTests : DelegateCreationTests { [Fact] public void NullTypeList() { AssertExtensions.Throws<ArgumentNullException>("typeArgs", () => Expression.GetActionType(default(Type[]))); } [Fact] public void NullInTypeList() { AssertExtensions.Throws<ArgumentNullException>("typeArgs", () => Expression.GetActionType(typeof(int), null)); } [Theory] [MemberData(nameof(EmptyTypeArgs))] [MemberData(nameof(ValidTypeArgs), false)] public void SuccessfulGetActionType(Type[] typeArgs) { Type funcType = Expression.GetActionType(typeArgs); if (typeArgs.Length == 0) { Assert.Equal(typeof(Action), funcType); } else { Assert.StartsWith("System.Action`" + typeArgs.Length, funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } } [Theory] [MemberData(nameof(EmptyTypeArgs))] [MemberData(nameof(ValidTypeArgs), false)] public void SuccessfulTryGetActionType(Type[] typeArgs) { Type funcType; Assert.True(Expression.TryGetActionType(typeArgs, out funcType)); if (typeArgs.Length == 0) { Assert.Equal(typeof(Action), funcType); } else { Assert.StartsWith("System.Action`" + typeArgs.Length, funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } } // Open generic type args aren't useful directly with Expressions, but creating them is allowed. [Theory, MemberData(nameof(OpenGenericTypeArgs), false)] public void SuccessfulGetActionTypeOpenGeneric(Type[] typeArgs) { Type funcType = Expression.GetActionType(typeArgs); Assert.Equal("Action`" + typeArgs.Length, funcType.Name); Assert.Null(funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Theory, MemberData(nameof(OpenGenericTypeArgs), false)] public void SuccessfulTryGetActionTypeWithOpenGeneric(Type[] typeArgs) { Type funcType; Assert.True(Expression.TryGetActionType(typeArgs, out funcType)); Assert.Equal("Action`" + typeArgs.Length, funcType.Name); Assert.Null(funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Theory] [MemberData(nameof(ExcessiveLengthTypeArgs))] [MemberData(nameof(ExcessiveLengthOpenGenericTypeArgs))] [MemberData(nameof(ByRefTypeArgs))] [MemberData(nameof(PointerTypeArgs))] [MemberData(nameof(ManagedPointerTypeArgs))] [MemberData(nameof(VoidTypeArgs), true)] public void UnsuccessfulGetActionType(Type[] typeArgs) { string paramName = typeArgs.Any(t => t == typeof(void)) || typeArgs.Count(t => t.IsPointer) == 1 ? null : "typeArgs"; AssertExtensions.Throws<ArgumentException>(paramName, () => Expression.GetActionType(typeArgs)); } [Theory] [MemberData(nameof(ExcessiveLengthTypeArgs))] [MemberData(nameof(ExcessiveLengthOpenGenericTypeArgs))] [MemberData(nameof(ByRefTypeArgs))] [MemberData(nameof(PointerTypeArgs))] [MemberData(nameof(ManagedPointerTypeArgs))] [MemberData(nameof(VoidTypeArgs), true)] public void UnsuccessfulTryGetActionType(Type[] typeArgs) { Type funcType; Assert.False(Expression.TryGetActionType(typeArgs, out funcType)); } } }
-1
dotnet/runtime
66,358
[MAUI][PERF] Add IPA file usage for iOS Maui SOD
Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
LoopedBard3
2022-03-08T21:20:42Z
2022-03-09T22:55:02Z
d4f7ef48ac016fe9e3cc2cba712d0224e04de8ac
f06d2c07d84f2b535ea0fae3ba7d8e4e3cad5a98
[MAUI][PERF] Add IPA file usage for iOS Maui SOD. Adds IPA file usage for iOS Maui SOD. This included adding necessary profile signing and provisioning in the building steps, piping the changes through the pipeline, and making changes in the Perf repository to support them.
./src/coreclr/vm/amd64/crthelpers.S
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .intel_syntax noprefix #include "unixasmmacros.inc" #include "asmconstants.h" // JIT_MemSet/JIT_MemCpy // // It is IMPORTANT that the exception handling code is able to find these guys // on the stack, but on non-windows platforms we can just defer to the platform // implementation. // // void JIT_MemSet(void* dest, int c, size_t count) // // Purpose: // Sets the first "count" bytes of the block of memory pointed byte // "dest" to the specified value (interpreted as an unsigned char). // // Entry: // RDI: void* dest - Pointer to the block of memory to fill. // RSI: int c - Value to be set. // RDX: size_t count - Number of bytes to be set to the value. // // Exit: // // Uses: // // Exceptions: // LEAF_ENTRY JIT_MemSet, _TEXT test rdx, rdx // check if count is zero jz Exit_MemSet // if zero, no bytes to set cmp byte ptr [rdi], 0 // check dest for null jmp C_PLTFUNC(memset) // forward to the CRT implementation Exit_MemSet: ret LEAF_END_MARKED JIT_MemSet, _TEXT // void JIT_MemCpy(void* dest, const void* src, size_t count) // // Purpose: // Copies the values of "count" bytes from the location pointed to // by "src" to the memory block pointed by "dest". // // Entry: // RDI: void* dest - Pointer to the destination array where content is to be copied. // RSI: const void* src - Pointer to the source of the data to be copied. // RDX: size_t count - Number of bytes to copy. // // Exit: // // Uses: // // Exceptions: // LEAF_ENTRY JIT_MemCpy, _TEXT test rdx, rdx // check if count is zero jz Exit_MemCpy // if zero, no bytes to set cmp byte ptr [rdi], 0 // check dest for null cmp byte ptr [rsi], 0 // check src for null jmp C_PLTFUNC(memcpy) // forward to the CRT implementation Exit_MemCpy: ret LEAF_END_MARKED JIT_MemCpy, _TEXT
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .intel_syntax noprefix #include "unixasmmacros.inc" #include "asmconstants.h" // JIT_MemSet/JIT_MemCpy // // It is IMPORTANT that the exception handling code is able to find these guys // on the stack, but on non-windows platforms we can just defer to the platform // implementation. // // void JIT_MemSet(void* dest, int c, size_t count) // // Purpose: // Sets the first "count" bytes of the block of memory pointed byte // "dest" to the specified value (interpreted as an unsigned char). // // Entry: // RDI: void* dest - Pointer to the block of memory to fill. // RSI: int c - Value to be set. // RDX: size_t count - Number of bytes to be set to the value. // // Exit: // // Uses: // // Exceptions: // LEAF_ENTRY JIT_MemSet, _TEXT test rdx, rdx // check if count is zero jz Exit_MemSet // if zero, no bytes to set cmp byte ptr [rdi], 0 // check dest for null jmp C_PLTFUNC(memset) // forward to the CRT implementation Exit_MemSet: ret LEAF_END_MARKED JIT_MemSet, _TEXT // void JIT_MemCpy(void* dest, const void* src, size_t count) // // Purpose: // Copies the values of "count" bytes from the location pointed to // by "src" to the memory block pointed by "dest". // // Entry: // RDI: void* dest - Pointer to the destination array where content is to be copied. // RSI: const void* src - Pointer to the source of the data to be copied. // RDX: size_t count - Number of bytes to copy. // // Exit: // // Uses: // // Exceptions: // LEAF_ENTRY JIT_MemCpy, _TEXT test rdx, rdx // check if count is zero jz Exit_MemCpy // if zero, no bytes to set cmp byte ptr [rdi], 0 // check dest for null cmp byte ptr [rsi], 0 // check src for null jmp C_PLTFUNC(memcpy) // forward to the CRT implementation Exit_MemCpy: ret LEAF_END_MARKED JIT_MemCpy, _TEXT
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Emitter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; // NOTE: The logic in this file is largely a copy of logic in RegexCompiler, emitting C# instead of MSIL. // Most changes made to this file should be kept in sync, so far as bug fixes and relevant optimizations // are concerned. namespace System.Text.RegularExpressions.Generator { public partial class RegexGenerator { /// <summary>Code for a [GeneratedCode] attribute to put on the top-level generated members.</summary> private static readonly string s_generatedCodeAttribute = $"[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{typeof(RegexGenerator).Assembly.GetName().Name}\", \"{typeof(RegexGenerator).Assembly.GetName().Version}\")]"; /// <summary>Header comments and usings to include at the top of every generated file.</summary> private static readonly string[] s_headers = new string[] { "// <auto-generated/>", "#nullable enable", "#pragma warning disable CS0162 // Unreachable code", "#pragma warning disable CS0164 // Unreferenced label", "#pragma warning disable CS0219 // Variable assigned but never used", "", }; /// <summary>Generates the code for one regular expression class.</summary> private static (string, ImmutableArray<Diagnostic>) EmitRegexType(RegexType regexClass, bool allowUnsafe) { var sb = new StringBuilder(1024); var writer = new IndentedTextWriter(new StringWriter(sb)); // Emit the namespace if (!string.IsNullOrWhiteSpace(regexClass.Namespace)) { writer.WriteLine($"namespace {regexClass.Namespace}"); writer.WriteLine("{"); writer.Indent++; } // Emit containing types RegexType? parent = regexClass.ParentClass; var parentClasses = new Stack<string>(); while (parent is not null) { parentClasses.Push($"partial {parent.Keyword} {parent.Name}"); parent = parent.ParentClass; } while (parentClasses.Count != 0) { writer.WriteLine($"{parentClasses.Pop()}"); writer.WriteLine("{"); writer.Indent++; } // Emit the direct parent type writer.WriteLine($"partial {regexClass.Keyword} {regexClass.Name}"); writer.WriteLine("{"); writer.Indent++; // Generate a name to describe the regex instance. This includes the method name // the user provided and a non-randomized (for determinism) hash of it to try to make // the name that much harder to predict. Debug.Assert(regexClass.Method is not null); string generatedName = $"GeneratedRegex_{regexClass.Method.MethodName}_"; generatedName += ComputeStringHash(generatedName).ToString("X"); // Generate the regex type ImmutableArray<Diagnostic> diagnostics = EmitRegexMethod(writer, regexClass.Method, generatedName, allowUnsafe); while (writer.Indent != 0) { writer.Indent--; writer.WriteLine("}"); } writer.Flush(); return (sb.ToString(), diagnostics); // FNV-1a hash function. The actual algorithm used doesn't matter; just something simple // to create a deterministic, pseudo-random value that's based on input text. static uint ComputeStringHash(string s) { uint hashCode = 2166136261; foreach (char c in s) { hashCode = (c ^ hashCode) * 16777619; } return hashCode; } } /// <summary>Generates the code for a regular expression method.</summary> private static ImmutableArray<Diagnostic> EmitRegexMethod(IndentedTextWriter writer, RegexMethod rm, string id, bool allowUnsafe) { string patternExpression = Literal(rm.Pattern); string optionsExpression = Literal(rm.Options); string timeoutExpression = rm.MatchTimeout == Timeout.Infinite ? "global::System.Threading.Timeout.InfiniteTimeSpan" : $"global::System.TimeSpan.FromMilliseconds({rm.MatchTimeout.ToString(CultureInfo.InvariantCulture)})"; writer.WriteLine(s_generatedCodeAttribute); writer.WriteLine($"{rm.Modifiers} global::System.Text.RegularExpressions.Regex {rm.MethodName}() => {id}.Instance;"); writer.WriteLine(); writer.WriteLine(s_generatedCodeAttribute); writer.WriteLine("[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]"); writer.WriteLine($"{(writer.Indent != 0 ? "private" : "internal")} sealed class {id} : global::System.Text.RegularExpressions.Regex"); writer.WriteLine("{"); writer.Write(" public static global::System.Text.RegularExpressions.Regex Instance { get; } = "); // If we can't support custom generation for this regex, spit out a Regex constructor call. if (!rm.Tree.Root.SupportsCompilation(out string? reason)) { writer.WriteLine(); writer.WriteLine($" // Cannot generate Regex-derived implementation because {reason}."); writer.WriteLine($" new global::System.Text.RegularExpressions.Regex({patternExpression}, {optionsExpression}, {timeoutExpression});"); writer.WriteLine("}"); return ImmutableArray.Create(Diagnostic.Create(DiagnosticDescriptors.LimitedSourceGeneration, rm.MethodSyntax.GetLocation())); } AnalysisResults analysis = RegexTreeAnalyzer.Analyze(rm.Tree); writer.WriteLine($"new {id}();"); writer.WriteLine(); writer.WriteLine($" private {id}()"); writer.WriteLine($" {{"); writer.WriteLine($" base.pattern = {patternExpression};"); writer.WriteLine($" base.roptions = {optionsExpression};"); writer.WriteLine($" base.internalMatchTimeout = {timeoutExpression};"); writer.WriteLine($" base.factory = new RunnerFactory();"); if (rm.Tree.CaptureNumberSparseMapping is not null) { writer.Write(" base.Caps = new global::System.Collections.Hashtable {"); AppendHashtableContents(writer, rm.Tree.CaptureNumberSparseMapping); writer.WriteLine(" };"); } if (rm.Tree.CaptureNameToNumberMapping is not null) { writer.Write(" base.CapNames = new global::System.Collections.Hashtable {"); AppendHashtableContents(writer, rm.Tree.CaptureNameToNumberMapping); writer.WriteLine(" };"); } if (rm.Tree.CaptureNames is not null) { writer.Write(" base.capslist = new string[] {"); string separator = ""; foreach (string s in rm.Tree.CaptureNames) { writer.Write(separator); writer.Write(Literal(s)); separator = ", "; } writer.WriteLine(" };"); } writer.WriteLine($" base.capsize = {rm.Tree.CaptureCount};"); writer.WriteLine($" }}"); writer.WriteLine(" "); writer.WriteLine($" private sealed class RunnerFactory : global::System.Text.RegularExpressions.RegexRunnerFactory"); writer.WriteLine($" {{"); writer.WriteLine($" protected override global::System.Text.RegularExpressions.RegexRunner CreateInstance() => new Runner();"); writer.WriteLine(); writer.WriteLine($" private sealed class Runner : global::System.Text.RegularExpressions.RegexRunner"); writer.WriteLine($" {{"); // Main implementation methods writer.WriteLine(" // Description:"); DescribeExpression(writer, rm.Tree.Root.Child(0), " // ", analysis); // skip implicit root capture writer.WriteLine(); writer.WriteLine($" protected override void Scan(global::System.ReadOnlySpan<char> text)"); writer.WriteLine($" {{"); writer.Indent += 4; EmitScan(writer, rm, id); writer.Indent -= 4; writer.WriteLine($" }}"); writer.WriteLine(); writer.WriteLine($" private bool TryFindNextPossibleStartingPosition(global::System.ReadOnlySpan<char> inputSpan)"); writer.WriteLine($" {{"); writer.Indent += 4; RequiredHelperFunctions requiredHelpers = EmitTryFindNextPossibleStartingPosition(writer, rm, id); writer.Indent -= 4; writer.WriteLine($" }}"); writer.WriteLine(); if (allowUnsafe) { writer.WriteLine($" [global::System.Runtime.CompilerServices.SkipLocalsInit]"); } writer.WriteLine($" private bool TryMatchAtCurrentPosition(global::System.ReadOnlySpan<char> inputSpan)"); writer.WriteLine($" {{"); writer.Indent += 4; requiredHelpers |= EmitTryMatchAtCurrentPosition(writer, rm, id, analysis); writer.Indent -= 4; writer.WriteLine($" }}"); if ((requiredHelpers & RequiredHelperFunctions.IsWordChar) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character is part of the [\\w] set.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsWordChar(char ch)"); writer.WriteLine($" {{"); writer.WriteLine($" global::System.ReadOnlySpan<byte> ascii = new byte[]"); writer.WriteLine($" {{"); writer.WriteLine($" 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03,"); writer.WriteLine($" 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07"); writer.WriteLine($" }};"); writer.WriteLine(); writer.WriteLine($" int chDiv8 = ch >> 3;"); writer.WriteLine($" return (uint)chDiv8 < (uint)ascii.Length ?"); writer.WriteLine($" (ascii[chDiv8] & (1 << (ch & 0x7))) != 0 :"); writer.WriteLine($" global::System.Globalization.CharUnicodeInfo.GetUnicodeCategory(ch) switch"); writer.WriteLine($" {{"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.UppercaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.LowercaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.TitlecaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.ModifierLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.OtherLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.NonSpacingMark or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.DecimalDigitNumber or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.ConnectorPunctuation => true,"); writer.WriteLine($" _ => false,"); writer.WriteLine($" }};"); writer.WriteLine($" }}"); } if ((requiredHelpers & RequiredHelperFunctions.IsBoundary) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character at the specified index is a boundary.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsBoundary(global::System.ReadOnlySpan<char> inputSpan, int index)"); writer.WriteLine($" {{"); writer.WriteLine($" int indexM1 = index - 1;"); writer.WriteLine($" return ((uint)indexM1 < (uint)inputSpan.Length && IsBoundaryWordChar(inputSpan[indexM1])) !="); writer.WriteLine($" ((uint)index < (uint)inputSpan.Length && IsBoundaryWordChar(inputSpan[index]));"); writer.WriteLine(); writer.WriteLine($" static bool IsBoundaryWordChar(char ch) =>"); writer.WriteLine($" IsWordChar(ch) || (ch == '\\u200C' | ch == '\\u200D');"); writer.WriteLine($" }}"); } if ((requiredHelpers & RequiredHelperFunctions.IsECMABoundary) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character at the specified index is a boundary.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsECMABoundary(global::System.ReadOnlySpan<char> inputSpan, int index)"); writer.WriteLine($" {{"); writer.WriteLine($" int indexM1 = index - 1;"); writer.WriteLine($" return ((uint)indexM1 < (uint)inputSpan.Length && IsECMAWordChar(inputSpan[indexM1])) !="); writer.WriteLine($" ((uint)index < (uint)inputSpan.Length && IsECMAWordChar(inputSpan[index]));"); writer.WriteLine(); writer.WriteLine($" static bool IsECMAWordChar(char ch) =>"); writer.WriteLine($" ((((uint)ch - 'A') & ~0x20) < 26) || // ASCII letter"); writer.WriteLine($" (((uint)ch - '0') < 10) || // digit"); writer.WriteLine($" ch == '_' || // underscore"); writer.WriteLine($" ch == '\\u0130'; // latin capital letter I with dot above"); writer.WriteLine($" }}"); } writer.WriteLine($" }}"); writer.WriteLine($" }}"); writer.WriteLine("}"); return ImmutableArray<Diagnostic>.Empty; static void AppendHashtableContents(IndentedTextWriter writer, Hashtable ht) { IDictionaryEnumerator en = ht.GetEnumerator(); string separator = ""; while (en.MoveNext()) { writer.Write(separator); separator = ", "; writer.Write(" { "); if (en.Key is int key) { writer.Write(key); } else { writer.Write($"\"{en.Key}\""); } writer.Write($", {en.Value} }} "); } } } /// <summary>Emits the body of the Scan method override.</summary> private static void EmitScan(IndentedTextWriter writer, RegexMethod rm, string id) { bool rtl = (rm.Options & RegexOptions.RightToLeft) != 0; using (EmitBlock(writer, "while (TryFindNextPossibleStartingPosition(text))")) { if (rm.MatchTimeout != Timeout.Infinite) { writer.WriteLine("base.CheckTimeout();"); writer.WriteLine(); } writer.WriteLine("// If we find a match on the current position, or we have reached the end of the input, we are done."); using (EmitBlock(writer, $"if (TryMatchAtCurrentPosition(text) || base.runtextpos == {(!rtl ? "text.Length" : "0")})")) { writer.WriteLine("return;"); } writer.WriteLine(); writer.WriteLine($"base.runtextpos{(!rtl ? "++" : "--")};"); } } /// <summary>Emits the body of the TryFindNextPossibleStartingPosition.</summary> private static RequiredHelperFunctions EmitTryFindNextPossibleStartingPosition(IndentedTextWriter writer, RegexMethod rm, string id) { RegexOptions options = (RegexOptions)rm.Options; RegexTree regexTree = rm.Tree; bool hasTextInfo = false; RequiredHelperFunctions requiredHelpers = RequiredHelperFunctions.None; bool rtl = (options & RegexOptions.RightToLeft) != 0; // In some cases, we need to emit declarations at the beginning of the method, but we only discover we need them later. // To handle that, we build up a collection of all the declarations to include, track where they should be inserted, // and then insert them at that position once everything else has been output. var additionalDeclarations = new HashSet<string>(); // Emit locals initialization writer.WriteLine("int pos = base.runtextpos;"); writer.Flush(); int additionalDeclarationsPosition = ((StringWriter)writer.InnerWriter).GetStringBuilder().Length; int additionalDeclarationsIndent = writer.Indent; writer.WriteLine(); // Generate length check. If the input isn't long enough to possibly match, fail quickly. // It's rare for min required length to be 0, so we don't bother special-casing the check, // especially since we want the "return false" code regardless. int minRequiredLength = rm.Tree.FindOptimizations.MinRequiredLength; Debug.Assert(minRequiredLength >= 0); string clause = (minRequiredLength, rtl) switch { (0, false) => "if (pos <= inputSpan.Length)", (1, false) => "if (pos < inputSpan.Length)", (_, false) => $"if (pos <= inputSpan.Length - {minRequiredLength})", (0, true) => "if (pos >= 0)", (1, true) => "if (pos > 0)", (_, true) => $"if (pos >= {minRequiredLength})", }; using (EmitBlock(writer, clause)) { // Emit any anchors. if (!EmitAnchors()) { // Either anchors weren't specified, or they don't completely root all matches to a specific location. // If whatever search operation we need to perform entails case-insensitive operations // that weren't already handled via creation of sets, we need to get an store the // TextInfo object to use (unless RegexOptions.CultureInvariant was specified). EmitTextInfo(writer, ref hasTextInfo, rm); // Emit the code for whatever find mode has been determined. switch (regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_LeftToRight(regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_RightToLeft(regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: Debug.Assert(regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_LeftToRight(); break; case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive: Debug.Assert(regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_RightToLeft(); break; case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: Debug.Assert(regexTree.FindOptimizations.LiteralAfterLoop is not null); EmitLiteralAfterAtomicLoop(); break; default: Debug.Fail($"Unexpected mode: {regexTree.FindOptimizations.FindMode}"); goto case FindNextStartingPositionMode.NoSearch; case FindNextStartingPositionMode.NoSearch: writer.WriteLine("return true;"); break; } } } writer.WriteLine(); const string NoStartingPositionFound = "NoStartingPositionFound"; writer.WriteLine("// No starting position found"); writer.WriteLine($"{NoStartingPositionFound}:"); writer.WriteLine($"base.runtextpos = {(!rtl ? "inputSpan.Length" : "0")};"); writer.WriteLine("return false;"); // We're done. Patch up any additional declarations. ReplaceAdditionalDeclarations(writer, additionalDeclarations, additionalDeclarationsPosition, additionalDeclarationsIndent); return requiredHelpers; // Emit a goto for the specified label. void Goto(string label) => writer.WriteLine($"goto {label};"); // Emits any anchors. Returns true if the anchor roots any match to a specific location and thus no further // searching is required; otherwise, false. bool EmitAnchors() { // Anchors that fully implement TryFindNextPossibleStartingPosition, with a check that leads to immediate success or failure determination. switch (regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: writer.WriteLine("// Beginning \\A anchor"); using (EmitBlock(writer, "if (pos != 0)")) { // If we're not currently at the beginning, we'll never be, so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start: writer.WriteLine("// Start \\G anchor"); using (EmitBlock(writer, "if (pos != base.runtextstart)")) { // For both left-to-right and right-to-left, if we're not currently at the starting (because // we've already moved beyond it), then we'll never be, so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: writer.WriteLine("// Leading end \\Z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length - 1)")) { // If we're not currently at the end (or a newline just before it), skip ahead // since nothing until then can possibly match. writer.WriteLine("base.runtextpos = inputSpan.Length - 1;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: writer.WriteLine("// Leading end \\z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length)")) { // If we're not currently at the end (or a newline just before it), skip ahead // since nothing until then can possibly match. writer.WriteLine("base.runtextpos = inputSpan.Length;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning: writer.WriteLine("// Beginning \\A anchor"); using (EmitBlock(writer, "if (pos != 0)")) { // If we're not currently at the beginning, skip ahead (or, rather, backwards) // since nothing until then can possibly match. (We're iterating from the end // to the beginning in RightToLeft mode.) writer.WriteLine("base.runtextpos = 0;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ: writer.WriteLine("// Leading end \\Z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length - 1 || ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\\n'))")) { // If we're not currently at the end, we'll never be (we're iterating from end to beginning), // so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End: writer.WriteLine("// Leading end \\z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length)")) { // If we're not currently at the end, we'll never be (we're iterating from end to beginning), // so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: // Jump to the end, minus the min required length, which in this case is actually the fixed length, minus 1 (for a possible ending \n). writer.WriteLine("// Trailing end \\Z anchor with fixed-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength + 1})")) { writer.WriteLine($"base.runtextpos = inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength + 1};"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: // Jump to the end, minus the min required length, which in this case is actually the fixed length. writer.WriteLine("// Trailing end \\z anchor with fixed-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength})")) { writer.WriteLine($"base.runtextpos = inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength};"); } writer.WriteLine("return true;"); return true; } // Now handle anchors that boost the position but may not determine immediate success or failure. switch (regexTree.FindOptimizations.LeadingAnchor) { case RegexNodeKind.Bol: // Optimize the handling of a Beginning-Of-Line (BOL) anchor. BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any searches. writer.WriteLine("// Beginning-of-line anchor"); using (EmitBlock(writer, "if (pos > 0 && inputSpan[pos - 1] != '\\n')")) { writer.WriteLine("int newlinePos = global::System.MemoryExtensions.IndexOf(inputSpan.Slice(pos), '\\n');"); using (EmitBlock(writer, "if ((uint)newlinePos > inputSpan.Length - pos - 1)")) { Goto(NoStartingPositionFound); } writer.WriteLine("pos = newlinePos + pos + 1;"); // We've updated the position. Make sure there's still enough room in the input for a possible match. using (EmitBlock(writer, minRequiredLength switch { 0 => "if (pos > inputSpan.Length)", 1 => "if (pos >= inputSpan.Length)", _ => $"if (pos > inputSpan.Length - {minRequiredLength})" })) { Goto(NoStartingPositionFound); } } writer.WriteLine(); break; } switch (regexTree.FindOptimizations.TrailingAnchor) { case RegexNodeKind.End when regexTree.FindOptimizations.MaxPossibleLength is int maxLength: writer.WriteLine("// End \\z anchor with maximum-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {maxLength})")) { writer.WriteLine($"pos = inputSpan.Length - {maxLength};"); } writer.WriteLine(); break; case RegexNodeKind.EndZ when regexTree.FindOptimizations.MaxPossibleLength is int maxLength: writer.WriteLine("// End \\Z anchor with maximum-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {maxLength + 1})")) { writer.WriteLine($"pos = inputSpan.Length - {maxLength + 1};"); } writer.WriteLine(); break; } return false; } // Emits a case-sensitive prefix search for a string at the beginning of the pattern. void EmitIndexOf_LeftToRight(string prefix) { writer.WriteLine($"int i = global::System.MemoryExtensions.IndexOf(inputSpan.Slice(pos), {Literal(prefix)});"); writer.WriteLine("if (i >= 0)"); writer.WriteLine("{"); writer.WriteLine(" base.runtextpos = pos + i;"); writer.WriteLine(" return true;"); writer.WriteLine("}"); } // Emits a case-sensitive right-to-left prefix search for a string at the beginning of the pattern. void EmitIndexOf_RightToLeft(string prefix) { writer.WriteLine($"pos = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice(0, pos), {Literal(prefix)});"); writer.WriteLine("if (pos >= 0)"); writer.WriteLine("{"); writer.WriteLine($" base.runtextpos = pos + {prefix.Length};"); writer.WriteLine(" return true;"); writer.WriteLine("}"); } // Emits a search for a set at a fixed position from the start of the pattern, // and potentially other sets at other fixed positions in the pattern. void EmitFixedSet_LeftToRight() { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? sets = regexTree.FindOptimizations.FixedDistanceSets; (char[]? Chars, string Set, int Distance, bool CaseInsensitive) primarySet = sets![0]; const int MaxSets = 4; int setsToUse = Math.Min(sets.Count, MaxSets); // If we can use IndexOf{Any}, try to accelerate the skip loop via vectorization to match the first prefix. // We can use it if this is a case-sensitive class with a small number of characters in the class. int setIndex = 0; bool canUseIndexOf = !primarySet.CaseInsensitive && primarySet.Chars is not null; bool needLoop = !canUseIndexOf || setsToUse > 1; FinishEmitScope loopBlock = default; if (needLoop) { writer.WriteLine("global::System.ReadOnlySpan<char> span = inputSpan.Slice(pos);"); string upperBound = "span.Length" + (setsToUse > 1 || primarySet.Distance != 0 ? $" - {minRequiredLength - 1}" : ""); loopBlock = EmitBlock(writer, $"for (int i = 0; i < {upperBound}; i++)"); } if (canUseIndexOf) { string span = needLoop ? "span" : "inputSpan.Slice(pos)"; span = (needLoop, primarySet.Distance) switch { (false, 0) => span, (true, 0) => $"{span}.Slice(i)", (false, _) => $"{span}.Slice({primarySet.Distance})", (true, _) => $"{span}.Slice(i + {primarySet.Distance})", }; string indexOf = primarySet.Chars!.Length switch { 1 => $"global::System.MemoryExtensions.IndexOf({span}, {Literal(primarySet.Chars[0])})", 2 => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(primarySet.Chars[0])}, {Literal(primarySet.Chars[1])})", 3 => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(primarySet.Chars[0])}, {Literal(primarySet.Chars[1])}, {Literal(primarySet.Chars[2])})", _ => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(new string(primarySet.Chars))})", }; if (needLoop) { writer.WriteLine($"int indexOfPos = {indexOf};"); using (EmitBlock(writer, "if (indexOfPos < 0)")) { Goto(NoStartingPositionFound); } writer.WriteLine("i += indexOfPos;"); writer.WriteLine(); if (setsToUse > 1) { using (EmitBlock(writer, $"if (i >= span.Length - {minRequiredLength - 1})")) { Goto(NoStartingPositionFound); } writer.WriteLine(); } } else { writer.WriteLine($"int i = {indexOf};"); using (EmitBlock(writer, "if (i >= 0)")) { writer.WriteLine("base.runtextpos = pos + i;"); writer.WriteLine("return true;"); } } setIndex = 1; } if (needLoop) { Debug.Assert(setIndex == 0 || setIndex == 1); bool hasCharClassConditions = false; if (setIndex < setsToUse) { // if (CharInClass(textSpan[i + charClassIndex], prefix[0], "...") && // ...) Debug.Assert(needLoop); int start = setIndex; for (; setIndex < setsToUse; setIndex++) { string spanIndex = $"span[i{(sets[setIndex].Distance > 0 ? $" + {sets[setIndex].Distance}" : "")}]"; string charInClassExpr = MatchCharacterClass(hasTextInfo, options, spanIndex, sets[setIndex].Set, sets[setIndex].CaseInsensitive, negate: false, additionalDeclarations, ref requiredHelpers); if (setIndex == start) { writer.Write($"if ({charInClassExpr}"); } else { writer.WriteLine(" &&"); writer.Write($" {charInClassExpr}"); } } writer.WriteLine(")"); hasCharClassConditions = true; } using (hasCharClassConditions ? EmitBlock(writer, null) : default) { writer.WriteLine("base.runtextpos = pos + i;"); writer.WriteLine("return true;"); } } loopBlock.Dispose(); } // Emits a right-to-left search for a set at a fixed position from the start of the pattern. // (Currently that position will always be a distance of 0, meaning the start of the pattern itself.) void EmitFixedSet_RightToLeft() { (char[]? Chars, string Set, int Distance, bool CaseInsensitive) set = regexTree.FindOptimizations.FixedDistanceSets![0]; Debug.Assert(set.Distance == 0); if (set.Chars is { Length: 1 } && !set.CaseInsensitive) { writer.WriteLine($"pos = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice(0, pos), {Literal(set.Chars[0])});"); writer.WriteLine("if (pos >= 0)"); writer.WriteLine("{"); writer.WriteLine(" base.runtextpos = pos + 1;"); writer.WriteLine(" return true;"); writer.WriteLine("}"); } else { using (EmitBlock(writer, "while ((uint)--pos < (uint)inputSpan.Length)")) { using (EmitBlock(writer, $"if ({MatchCharacterClass(hasTextInfo, options, "inputSpan[pos]", set.Set, set.CaseInsensitive, negate: false, additionalDeclarations, ref requiredHelpers)})")) { writer.WriteLine("base.runtextpos = pos + 1;"); writer.WriteLine("return true;"); } } } } // Emits a search for a literal following a leading atomic single-character loop. void EmitLiteralAfterAtomicLoop() { Debug.Assert(regexTree.FindOptimizations.LiteralAfterLoop is not null); (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = regexTree.FindOptimizations.LiteralAfterLoop.Value; Debug.Assert(target.LoopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(target.LoopNode.N == int.MaxValue); using (EmitBlock(writer, "while (true)")) { writer.WriteLine($"global::System.ReadOnlySpan<char> slice = inputSpan.Slice(pos);"); writer.WriteLine(); // Find the literal. If we can't find it, we're done searching. writer.Write("int i = global::System.MemoryExtensions."); writer.WriteLine( target.Literal.String is string literalString ? $"IndexOf(slice, {Literal(literalString)});" : target.Literal.Chars is not char[] literalChars ? $"IndexOf(slice, {Literal(target.Literal.Char)});" : literalChars.Length switch { 2 => $"IndexOfAny(slice, {Literal(literalChars[0])}, {Literal(literalChars[1])});", 3 => $"IndexOfAny(slice, {Literal(literalChars[0])}, {Literal(literalChars[1])}, {Literal(literalChars[2])});", _ => $"IndexOfAny(slice, {Literal(new string(literalChars))});", }); using (EmitBlock(writer, $"if (i < 0)")) { writer.WriteLine("break;"); } writer.WriteLine(); // We found the literal. Walk backwards from it finding as many matches as we can against the loop. writer.WriteLine("int prev = i;"); writer.WriteLine($"while ((uint)--prev < (uint)slice.Length && {MatchCharacterClass(hasTextInfo, options, "slice[prev]", target.LoopNode.Str!, caseInsensitive: false, negate: false, additionalDeclarations, ref requiredHelpers)});"); if (target.LoopNode.M > 0) { // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. writer.WriteLine($"if ((i - prev - 1) < {target.LoopNode.M})"); writer.WriteLine("{"); writer.WriteLine(" pos += i + 1;"); writer.WriteLine(" continue;"); writer.WriteLine("}"); } writer.WriteLine(); // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate i as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. writer.WriteLine("base.runtextpos = pos + prev + 1;"); writer.WriteLine("return true;"); } } // If a TextInfo is needed to perform ToLower operations, emits a local initialized to the TextInfo to use. static void EmitTextInfo(IndentedTextWriter writer, ref bool hasTextInfo, RegexMethod rm) { // Emit local to store current culture if needed if ((rm.Options & RegexOptions.CultureInvariant) == 0) { bool needsCulture = rm.Tree.FindOptimizations.FindMode switch { FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive => true, _ when rm.Tree.FindOptimizations.FixedDistanceSets is List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets => sets.Exists(set => set.CaseInsensitive), _ => false, }; if (needsCulture) { hasTextInfo = true; writer.WriteLine("global::System.Globalization.TextInfo textInfo = global::System.Globalization.CultureInfo.CurrentCulture.TextInfo;"); } } } } /// <summary>Emits the body of the TryMatchAtCurrentPosition.</summary> private static RequiredHelperFunctions EmitTryMatchAtCurrentPosition(IndentedTextWriter writer, RegexMethod rm, string id, AnalysisResults analysis) { // In .NET Framework and up through .NET Core 3.1, the code generated for RegexOptions.Compiled was effectively an unrolled // version of what RegexInterpreter would process. The RegexNode tree would be turned into a series of opcodes via // RegexWriter; the interpreter would then sit in a loop processing those opcodes, and the RegexCompiler iterated through the // opcodes generating code for each equivalent to what the interpreter would do albeit with some decisions made at compile-time // rather than at run-time. This approach, however, lead to complicated code that wasn't pay-for-play (e.g. a big backtracking // jump table that all compilations went through even if there was no backtracking), that didn't factor in the shape of the // tree (e.g. it's difficult to add optimizations based on interactions between nodes in the graph), and that didn't read well // when decompiled from IL to C# or when directly emitted as C# as part of a source generator. // // This implementation is instead based on directly walking the RegexNode tree and outputting code for each node in the graph. // A dedicated for each kind of RegexNode emits the code necessary to handle that node's processing, including recursively // calling the relevant function for any of its children nodes. Backtracking is handled not via a giant jump table, but instead // by emitting direct jumps to each backtracking construct. This is achieved by having all match failures jump to a "done" // label that can be changed by a previous emitter, e.g. before EmitLoop returns, it ensures that "doneLabel" is set to the // label that code should jump back to when backtracking. That way, a subsequent EmitXx function doesn't need to know exactly // where to jump: it simply always jumps to "doneLabel" on match failure, and "doneLabel" is always configured to point to // the right location. In an expression without backtracking, or before any backtracking constructs have been encountered, // "doneLabel" is simply the final return location from the TryMatchAtCurrentPosition method that will undo any captures and exit, signaling to // the calling scan loop that nothing was matched. // Arbitrary limit for unrolling vs creating a loop. We want to balance size in the generated // code with other costs, like the (small) overhead of slicing to create the temp span to iterate. const int MaxUnrollSize = 16; RegexOptions options = (RegexOptions)rm.Options; RegexTree regexTree = rm.Tree; RequiredHelperFunctions requiredHelpers = RequiredHelperFunctions.None; // Helper to define names. Names start unadorned, but as soon as there's repetition, // they begin to have a numbered suffix. var usedNames = new Dictionary<string, int>(); // Every RegexTree is rooted in the implicit Capture for the whole expression. // Skip the Capture node. We handle the implicit root capture specially. RegexNode node = regexTree.Root; Debug.Assert(node.Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); Debug.Assert(node.ChildCount() == 1, "Capture nodes should have one child"); node = node.Child(0); // In some limited cases, TryFindNextPossibleStartingPosition will only return true if it successfully matched the whole expression. // We can special case these to do essentially nothing in TryMatchAtCurrentPosition other than emit the capture. switch (node.Kind) { case RegexNodeKind.Multi or RegexNodeKind.Notone or RegexNodeKind.One or RegexNodeKind.Set when !IsCaseInsensitive(node): // This is the case for single and multiple characters, though the whole thing is only guaranteed // to have been validated in TryFindNextPossibleStartingPosition when doing case-sensitive comparison. writer.WriteLine($"int start = base.runtextpos;"); writer.WriteLine($"int end = start {((node.Options & RegexOptions.RightToLeft) == 0 ? "+" : "-")} {(node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1)};"); writer.WriteLine("base.Capture(0, start, end);"); writer.WriteLine("base.runtextpos = end;"); writer.WriteLine("return true;"); return requiredHelpers; case RegexNodeKind.Empty: // This case isn't common in production, but it's very common when first getting started with the // source generator and seeing what happens as you add more to expressions. When approaching // it from a learning perspective, this is very common, as it's the empty string you start with. writer.WriteLine("base.Capture(0, base.runtextpos, base.runtextpos);"); writer.WriteLine("return true;"); return requiredHelpers; } // In some cases, we need to emit declarations at the beginning of the method, but we only discover we need them later. // To handle that, we build up a collection of all the declarations to include, track where they should be inserted, // and then insert them at that position once everything else has been output. var additionalDeclarations = new HashSet<string>(); var additionalLocalFunctions = new Dictionary<string, string[]>(); // Declare some locals. string sliceSpan = "slice"; writer.WriteLine("int pos = base.runtextpos;"); writer.WriteLine($"int original_pos = pos;"); bool hasTimeout = EmitLoopTimeoutCounterIfNeeded(writer, rm); bool hasTextInfo = EmitInitializeCultureForTryMatchAtCurrentPositionIfNecessary(writer, rm, analysis); writer.Flush(); int additionalDeclarationsPosition = ((StringWriter)writer.InnerWriter).GetStringBuilder().Length; int additionalDeclarationsIndent = writer.Indent; // The implementation tries to use const indexes into the span wherever possible, which we can do // for all fixed-length constructs. In such cases (e.g. single chars, repeaters, strings, etc.) // we know at any point in the regex exactly how far into it we are, and we can use that to index // into the span created at the beginning of the routine to begin at exactly where we're starting // in the input. When we encounter a variable-length construct, we transfer the static value to // pos, slicing the inputSpan appropriately, and then zero out the static position. int sliceStaticPos = 0; SliceInputSpan(writer, defineLocal: true); writer.WriteLine(); // doneLabel starts out as the top-level label for the whole expression failing to match. However, // it may be changed by the processing of a node to point to whereever subsequent match failures // should jump to, in support of backtracking or other constructs. For example, before emitting // the code for a branch N, an alternation will set the the doneLabel to point to the label for // processing the next branch N+1: that way, any failures in the branch N's processing will // implicitly end up jumping to the right location without needing to know in what context it's used. string doneLabel = ReserveName("NoMatch"); string topLevelDoneLabel = doneLabel; // Check whether there are captures anywhere in the expression. If there isn't, we can skip all // the boilerplate logic around uncapturing, as there won't be anything to uncapture. bool expressionHasCaptures = analysis.MayContainCapture(node); // Emit the code for all nodes in the tree. EmitNode(node); // If we fall through to this place in the code, we've successfully matched the expression. writer.WriteLine(); writer.WriteLine("// The input matched."); if (sliceStaticPos > 0) { EmitAdd(writer, "pos", sliceStaticPos); // TransferSliceStaticPosToPos would also slice, which isn't needed here } writer.WriteLine("base.runtextpos = pos;"); writer.WriteLine("base.Capture(0, original_pos, pos);"); writer.WriteLine("return true;"); // We're done with the match. // Patch up any additional declarations. ReplaceAdditionalDeclarations(writer, additionalDeclarations, additionalDeclarationsPosition, additionalDeclarationsIndent); // And emit any required helpers. if (additionalLocalFunctions.Count != 0) { foreach (KeyValuePair<string, string[]> localFunctions in additionalLocalFunctions.OrderBy(k => k.Key)) { writer.WriteLine(); foreach (string line in localFunctions.Value) { writer.WriteLine(line); } } } return requiredHelpers; // Helper to create a name guaranteed to be unique within the function. string ReserveName(string prefix) { usedNames.TryGetValue(prefix, out int count); usedNames[prefix] = count + 1; return count == 0 ? prefix : $"{prefix}{count}"; } // Helper to emit a label. As of C# 10, labels aren't statements of their own and need to adorn a following statement; // if a label appears just before a closing brace, then, it's a compilation error. To avoid issues there, this by // default implements a blank statement (a semicolon) after each label, but individual uses can opt-out of the semicolon // when it's known the label will always be followed by a statement. void MarkLabel(string label, bool emitSemicolon = true) => writer.WriteLine($"{label}:{(emitSemicolon ? ";" : "")}"); // Emits a goto to jump to the specified label. However, if the specified label is the top-level done label indicating // that the entire match has failed, we instead emit our epilogue, uncapturing if necessary and returning out of TryMatchAtCurrentPosition. void Goto(string label) { if (label == topLevelDoneLabel) { // We only get here in the code if the whole expression fails to match and jumps to // the original value of doneLabel. if (expressionHasCaptures) { EmitUncaptureUntil("0"); } writer.WriteLine("return false; // The input didn't match."); } else { writer.WriteLine($"goto {label};"); } } // Emits a case or default line followed by an indented body. void CaseGoto(string clause, string label) { writer.WriteLine(clause); writer.Indent++; Goto(label); writer.Indent--; } // Whether the node has RegexOptions.IgnoreCase set. static bool IsCaseInsensitive(RegexNode node) => (node.Options & RegexOptions.IgnoreCase) != 0; // Slices the inputSpan starting at pos until end and stores it into slice. void SliceInputSpan(IndentedTextWriter writer, bool defineLocal = false) { if (defineLocal) { writer.Write("global::System.ReadOnlySpan<char> "); } writer.WriteLine($"{sliceSpan} = inputSpan.Slice(pos);"); } // Emits the sum of a constant and a value from a local. string Sum(int constant, string? local = null) => local is null ? constant.ToString(CultureInfo.InvariantCulture) : constant == 0 ? local : $"{constant} + {local}"; // Emits a check that the span is large enough at the currently known static position to handle the required additional length. void EmitSpanLengthCheck(int requiredLength, string? dynamicRequiredLength = null) { Debug.Assert(requiredLength > 0); using (EmitBlock(writer, $"if ({SpanLengthCheck(requiredLength, dynamicRequiredLength)})")) { Goto(doneLabel); } } // Returns a length check for the current span slice. The check returns true if // the span isn't long enough for the specified length. string SpanLengthCheck(int requiredLength, string? dynamicRequiredLength = null) => dynamicRequiredLength is null && sliceStaticPos + requiredLength == 1 ? $"{sliceSpan}.IsEmpty" : $"(uint){sliceSpan}.Length < {Sum(sliceStaticPos + requiredLength, dynamicRequiredLength)}"; // Adds the value of sliceStaticPos into the pos local, slices slice by the corresponding amount, // and zeros out sliceStaticPos. void TransferSliceStaticPosToPos(bool forceSliceReload = false) { if (sliceStaticPos > 0) { EmitAdd(writer, "pos", sliceStaticPos); sliceStaticPos = 0; SliceInputSpan(writer); } else if (forceSliceReload) { SliceInputSpan(writer); } } // Emits the code for an alternation. void EmitAlternation(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Alternate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); int childCount = node.ChildCount(); Debug.Assert(childCount >= 2); string originalDoneLabel = doneLabel; // Both atomic and non-atomic are supported. While a parent RegexNode.Atomic node will itself // successfully prevent backtracking into this child node, we can emit better / cheaper code // for an Alternate when it is atomic, so we still take it into account here. Debug.Assert(node.Parent is not null); bool isAtomic = analysis.IsAtomicByAncestor(node); // If no child branch overlaps with another child branch, we can emit more streamlined code // that avoids checking unnecessary branches, e.g. with abc|def|ghi if the next character in // the input is 'a', we needn't try the def or ghi branches. A simple, relatively common case // of this is if every branch begins with a specific, unique character, in which case // the whole alternation can be treated as a simple switch, so we special-case that. However, // we can't goto _into_ switch cases, which means we can't use this approach if there's any // possibility of backtracking into the alternation. bool useSwitchedBranches = false; if ((node.Options & RegexOptions.RightToLeft) == 0) { useSwitchedBranches = isAtomic; if (!useSwitchedBranches) { useSwitchedBranches = true; for (int i = 0; i < childCount; i++) { if (analysis.MayBacktrack(node.Child(i))) { useSwitchedBranches = false; break; } } } } // Detect whether every branch begins with one or more unique characters. const int SetCharsSize = 5; // arbitrary limit (for IgnoreCase, we want this to be at least 3 to handle the vast majority of values) Span<char> setChars = stackalloc char[SetCharsSize]; if (useSwitchedBranches) { // Iterate through every branch, seeing if we can easily find a starting One, Multi, or small Set. // If we can, extract its starting char (or multiple in the case of a set), validate that all such // starting characters are unique relative to all the branches. var seenChars = new HashSet<char>(); for (int i = 0; i < childCount && useSwitchedBranches; i++) { // If it's not a One, Multi, or Set, we can't apply this optimization. // If it's IgnoreCase (and wasn't reduced to a non-IgnoreCase set), also ignore it to keep the logic simple. if (node.Child(i).FindBranchOneMultiOrSetStart() is not RegexNode oneMultiOrSet || (oneMultiOrSet.Options & RegexOptions.IgnoreCase) != 0) // TODO: https://github.com/dotnet/runtime/issues/61048 { useSwitchedBranches = false; break; } // If it's a One or a Multi, get the first character and add it to the set. // If it was already in the set, we can't apply this optimization. if (oneMultiOrSet.Kind is RegexNodeKind.One or RegexNodeKind.Multi) { if (!seenChars.Add(oneMultiOrSet.FirstCharOfOneOrMulti())) { useSwitchedBranches = false; break; } } else { // The branch begins with a set. Make sure it's a set of only a few characters // and get them. If we can't, we can't apply this optimization. Debug.Assert(oneMultiOrSet.Kind is RegexNodeKind.Set); int numChars; if (RegexCharClass.IsNegated(oneMultiOrSet.Str!) || (numChars = RegexCharClass.GetSetChars(oneMultiOrSet.Str!, setChars)) == 0) { useSwitchedBranches = false; break; } // Check to make sure each of the chars is unique relative to all other branches examined. foreach (char c in setChars.Slice(0, numChars)) { if (!seenChars.Add(c)) { useSwitchedBranches = false; break; } } } } } if (useSwitchedBranches) { // Note: This optimization does not exist with RegexOptions.Compiled. Here we rely on the // C# compiler to lower the C# switch statement with appropriate optimizations. In some // cases there are enough branches that the compiler will emit a jump table. In others // it'll optimize the order of checks in order to minimize the total number in the worst // case. In any case, we get easier to read and reason about C#. EmitSwitchedBranches(); } else { EmitAllBranches(); } return; // Emits the code for a switch-based alternation of non-overlapping branches. void EmitSwitchedBranches() { // We need at least 1 remaining character in the span, for the char to switch on. EmitSpanLengthCheck(1); writer.WriteLine(); // Emit a switch statement on the first char of each branch. using (EmitBlock(writer, $"switch ({sliceSpan}[{sliceStaticPos++}])")) { Span<char> setChars = stackalloc char[SetCharsSize]; // needs to be same size as detection check in caller int startingSliceStaticPos = sliceStaticPos; // Emit a case for each branch. for (int i = 0; i < childCount; i++) { sliceStaticPos = startingSliceStaticPos; RegexNode child = node.Child(i); Debug.Assert(child.Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set or RegexNodeKind.Concatenate, DescribeNode(child, analysis)); Debug.Assert(child.Kind is not RegexNodeKind.Concatenate || (child.ChildCount() >= 2 && child.Child(0).Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set)); RegexNode? childStart = child.FindBranchOneMultiOrSetStart(); Debug.Assert(childStart is not null, "Unexpectedly couldn't find the branch starting node."); Debug.Assert((childStart.Options & RegexOptions.IgnoreCase) == 0, "Expected only to find non-IgnoreCase branch starts"); if (childStart.Kind is RegexNodeKind.Set) { int numChars = RegexCharClass.GetSetChars(childStart.Str!, setChars); Debug.Assert(numChars != 0); writer.WriteLine($"case {string.Join(" or ", setChars.Slice(0, numChars).ToArray().Select(c => Literal(c)))}:"); } else { writer.WriteLine($"case {Literal(childStart.FirstCharOfOneOrMulti())}:"); } writer.Indent++; // Emit the code for the branch, without the first character that was already matched in the switch. switch (child.Kind) { case RegexNodeKind.Multi: EmitNode(CloneMultiWithoutFirstChar(child)); writer.WriteLine(); break; case RegexNodeKind.Concatenate: var newConcat = new RegexNode(RegexNodeKind.Concatenate, child.Options); if (childStart.Kind == RegexNodeKind.Multi) { newConcat.AddChild(CloneMultiWithoutFirstChar(childStart)); } int concatChildCount = child.ChildCount(); for (int j = 1; j < concatChildCount; j++) { newConcat.AddChild(child.Child(j)); } EmitNode(newConcat.Reduce()); writer.WriteLine(); break; static RegexNode CloneMultiWithoutFirstChar(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Multi); Debug.Assert(node.Str!.Length >= 2); return node.Str!.Length == 2 ? new RegexNode(RegexNodeKind.One, node.Options, node.Str![1]) : new RegexNode(RegexNodeKind.Multi, node.Options, node.Str!.Substring(1)); } } // This is only ever used for atomic alternations, so we can simply reset the doneLabel // after emitting the child, as nothing will backtrack here (and we need to reset it // so that all branches see the original). doneLabel = originalDoneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. TransferSliceStaticPosToPos(); writer.WriteLine($"break;"); writer.WriteLine(); writer.Indent--; } // Default branch if the character didn't match the start of any branches. CaseGoto("default:", doneLabel); } } void EmitAllBranches() { // Label to jump to when any branch completes successfully. string matchLabel = ReserveName("AlternationMatch"); // Save off pos. We'll need to reset this each time a branch fails. string startingPos = ReserveName("alternation_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); int startingSliceStaticPos = sliceStaticPos; // We need to be able to undo captures in two situations: // - If a branch of the alternation itself contains captures, then if that branch // fails to match, any captures from that branch until that failure point need to // be uncaptured prior to jumping to the next branch. // - If the expression after the alternation contains captures, then failures // to match in those expressions could trigger backtracking back into the // alternation, and thus we need uncapture any of them. // As such, if the alternation contains captures or if it's not atomic, we need // to grab the current crawl position so we can unwind back to it when necessary. // We can do all of the uncapturing as part of falling through to the next branch. // If we fail in a branch, then such uncapturing will unwind back to the position // at the start of the alternation. If we fail after the alternation, and the // matched branch didn't contain any backtracking, then the failure will end up // jumping to the next branch, which will unwind the captures. And if we fail after // the alternation and the matched branch did contain backtracking, that backtracking // construct is responsible for unwinding back to its starting crawl position. If // it eventually ends up failing, that failure will result in jumping to the next branch // of the alternation, which will again dutifully unwind the remaining captures until // what they were at the start of the alternation. Of course, if there are no captures // anywhere in the regex, we don't have to do any of that. string? startingCapturePos = null; if (expressionHasCaptures && (analysis.MayContainCapture(node) || !isAtomic)) { startingCapturePos = ReserveName("alternation_starting_capturepos"); writer.WriteLine($"int {startingCapturePos} = base.Crawlpos();"); } writer.WriteLine(); // After executing the alternation, subsequent matching may fail, at which point execution // will need to backtrack to the alternation. We emit a branching table at the end of the // alternation, with a label that will be left as the "doneLabel" upon exiting emitting the // alternation. The branch table is populated with an entry for each branch of the alternation, // containing either the label for the last backtracking construct in the branch if such a construct // existed (in which case the doneLabel upon emitting that node will be different from before it) // or the label for the next branch. var labelMap = new string[childCount]; string backtrackLabel = ReserveName("AlternationBacktrack"); for (int i = 0; i < childCount; i++) { // If the alternation isn't atomic, backtracking may require our jump table jumping back // into these branches, so we can't use actual scopes, as that would hide the labels. using (EmitScope(writer, $"Branch {i}", faux: !isAtomic)) { bool isLastBranch = i == childCount - 1; string? nextBranch = null; if (!isLastBranch) { // Failure to match any branch other than the last one should result // in jumping to process the next branch. nextBranch = ReserveName("AlternationBranch"); doneLabel = nextBranch; } else { // Failure to match the last branch is equivalent to failing to match // the whole alternation, which means those failures should jump to // what "doneLabel" was defined as when starting the alternation. doneLabel = originalDoneLabel; } // Emit the code for each branch. EmitNode(node.Child(i)); writer.WriteLine(); // Add this branch to the backtracking table. At this point, either the child // had backtracking constructs, in which case doneLabel points to the last one // and that's where we'll want to jump to, or it doesn't, in which case doneLabel // still points to the nextBranch, which similarly is where we'll want to jump to. if (!isAtomic) { EmitStackPush(startingCapturePos is not null ? new[] { i.ToString(), startingPos, startingCapturePos } : new[] { i.ToString(), startingPos }); } labelMap[i] = doneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. TransferSliceStaticPosToPos(); if (!isLastBranch || !isAtomic) { // If this isn't the last branch, we're about to output a reset section, // and if this isn't atomic, there will be a backtracking section before // the end of the method. In both of those cases, we've successfully // matched and need to skip over that code. If, however, this is the // last branch and this is an atomic alternation, we can just fall // through to the successfully matched location. Goto(matchLabel); } // Reset state for next branch and loop around to generate it. This includes // setting pos back to what it was at the beginning of the alternation, // updating slice to be the full length it was, and if there's a capture that // needs to be reset, uncapturing it. if (!isLastBranch) { writer.WriteLine(); MarkLabel(nextBranch!, emitSemicolon: false); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } } } writer.WriteLine(); } // We should never fall through to this location in the generated code. Either // a branch succeeded in matching and jumped to the end, or a branch failed in // matching and jumped to the next branch location. We only get to this code // if backtracking occurs and the code explicitly jumps here based on our setting // "doneLabel" to the label for this section. Thus, we only need to emit it if // something can backtrack to us, which can't happen if we're inside of an atomic // node. Thus, emit the backtracking section only if we're non-atomic. if (isAtomic) { doneLabel = originalDoneLabel; } else { doneLabel = backtrackLabel; MarkLabel(backtrackLabel, emitSemicolon: false); EmitStackPop(startingCapturePos is not null ? new[] { startingCapturePos, startingPos } : new[] { startingPos}); using (EmitBlock(writer, $"switch ({StackPop()})")) { for (int i = 0; i < labelMap.Length; i++) { CaseGoto($"case {i}:", labelMap[i]); } } writer.WriteLine(); } // Successfully completed the alternate. MarkLabel(matchLabel); Debug.Assert(sliceStaticPos == 0); } } // Emits the code to handle a backreference. void EmitBackreference(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Backreference, $"Unexpected type: {node.Kind}"); int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); if (sliceStaticPos > 0) { TransferSliceStaticPosToPos(); writer.WriteLine(); } // If the specified capture hasn't yet captured anything, fail to match... except when using RegexOptions.ECMAScript, // in which case per ECMA 262 section 21.2.2.9 the backreference should succeed. if ((node.Options & RegexOptions.ECMAScript) != 0) { writer.WriteLine($"// If the {DescribeCapture(node.M, analysis)} hasn't matched, the backreference matches with RegexOptions.ECMAScript rules."); using (EmitBlock(writer, $"if (base.IsMatched({capnum}))")) { EmitWhenHasCapture(); } } else { writer.WriteLine($"// If the {DescribeCapture(node.M, analysis)} hasn't matched, the backreference doesn't match."); using (EmitBlock(writer, $"if (!base.IsMatched({capnum}))")) { Goto(doneLabel); } writer.WriteLine(); EmitWhenHasCapture(); } void EmitWhenHasCapture() { writer.WriteLine("// Get the captured text. If it doesn't match at the current position, the backreference doesn't match."); additionalDeclarations.Add("int matchLength = 0;"); writer.WriteLine($"matchLength = base.MatchLength({capnum});"); bool caseInsensitive = IsCaseInsensitive(node); if ((node.Options & RegexOptions.RightToLeft) == 0) { if (!caseInsensitive) { // If we're case-sensitive, we can simply validate that the remaining length of the slice is sufficient // to possibly match, and then do a SequenceEqual against the matched text. writer.WriteLine($"if ({sliceSpan}.Length < matchLength || "); using (EmitBlock(writer, $" !global::System.MemoryExtensions.SequenceEqual(inputSpan.Slice(base.MatchIndex({capnum}), matchLength), {sliceSpan}.Slice(0, matchLength)))")) { Goto(doneLabel); } } else { // For case-insensitive, we have to walk each character individually. using (EmitBlock(writer, $"if ({sliceSpan}.Length < matchLength)")) { Goto(doneLabel); } writer.WriteLine(); additionalDeclarations.Add("int matchIndex = 0;"); writer.WriteLine($"matchIndex = base.MatchIndex({capnum});"); using (EmitBlock(writer, $"for (int i = 0; i < matchLength; i++)")) { using (EmitBlock(writer, $"if ({ToLower(hasTextInfo, options, $"inputSpan[matchIndex + i]")} != {ToLower(hasTextInfo, options, $"{sliceSpan}[i]")})")) { Goto(doneLabel); } } } writer.WriteLine(); writer.WriteLine($"pos += matchLength;"); SliceInputSpan(writer); } else { using (EmitBlock(writer, $"if (pos < matchLength)")) { Goto(doneLabel); } writer.WriteLine(); additionalDeclarations.Add("int matchIndex = 0;"); writer.WriteLine($"matchIndex = base.MatchIndex({capnum});"); using (EmitBlock(writer, $"for (int i = 0; i < matchLength; i++)")) { using (EmitBlock(writer, $"if ({ToLowerIfNeeded(hasTextInfo, options, $"inputSpan[matchIndex + i]", caseInsensitive)} != {ToLowerIfNeeded(hasTextInfo, options, $"inputSpan[pos - matchLength + i]", caseInsensitive)})")) { Goto(doneLabel); } } writer.WriteLine(); writer.WriteLine($"pos -= matchLength;"); } } } // Emits the code for an if(backreference)-then-else conditional. void EmitBackreferenceConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.BackreferenceConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 2, $"Expected 2 children, found {node.ChildCount()}"); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // Get the capture number to test. int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(0); RegexNode? noBranch = node.Child(1) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; string originalDoneLabel = doneLabel; // If the child branches might backtrack, we can't emit the branches inside constructs that // require braces, e.g. if/else, even though that would yield more idiomatic output. // But if we know for certain they won't backtrack, we can output the nicer code. if (analysis.IsAtomicByAncestor(node) || (!analysis.MayBacktrack(yesBranch) && (noBranch is null || !analysis.MayBacktrack(noBranch)))) { using (EmitBlock(writer, $"if (base.IsMatched({capnum}))")) { writer.WriteLine($"// The {DescribeCapture(node.M, analysis)} captured a value. Match the first branch."); EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch } if (noBranch is not null) { using (EmitBlock(writer, $"else")) { writer.WriteLine($"// Otherwise, match the second branch."); EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch } } doneLabel = originalDoneLabel; // atomicity return; } string refNotMatched = ReserveName("ConditionalBackreferenceNotMatched"); string endConditional = ReserveName("ConditionalBackreferenceEnd"); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the conditional needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. string resumeAt = ReserveName("conditionalbackreference_branch"); writer.WriteLine($"int {resumeAt} = 0;"); // While it would be nicely readable to use an if/else block, if the branches contain // anything that triggers backtracking, labels will end up being defined, and if they're // inside the scope block for the if or else, that will prevent jumping to them from // elsewhere. So we implement the if/else with labels and gotos manually. // Check to see if the specified capture number was captured. using (EmitBlock(writer, $"if (!base.IsMatched({capnum}))")) { Goto(refNotMatched); } writer.WriteLine(); // The specified capture was captured. Run the "yes" branch. // If it successfully matches, jump to the end. EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch string postYesDoneLabel = doneLabel; if (postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 0;"); } bool needsEndConditional = postYesDoneLabel != originalDoneLabel || noBranch is not null; if (needsEndConditional) { Goto(endConditional); writer.WriteLine(); } MarkLabel(refNotMatched); string postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (postNoDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 1;"); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 2;"); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. bool hasBacktracking = postYesDoneLabel != originalDoneLabel || postNoDoneLabel != originalDoneLabel; if (hasBacktracking) { // Skip the backtracking section. Goto(endConditional); writer.WriteLine(); // Backtrack section string backtrack = ReserveName("ConditionalBackreferenceBacktrack"); doneLabel = backtrack; MarkLabel(backtrack); // Pop from the stack the branch that was used and jump back to its backtracking location. EmitStackPop(resumeAt); using (EmitBlock(writer, $"switch ({resumeAt})")) { if (postYesDoneLabel != originalDoneLabel) { CaseGoto("case 0:", postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { CaseGoto("case 1:", postNoDoneLabel); } CaseGoto("default:", originalDoneLabel); } } if (needsEndConditional) { MarkLabel(endConditional); } if (hasBacktracking) { // We're not atomic and at least one of the yes or no branches contained backtracking constructs, // so finish outputting our backtracking logic, which involves pushing onto the stack which // branch to backtrack into. EmitStackPush(resumeAt); } } // Emits the code for an if(expression)-then-else conditional. void EmitExpressionConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.ExpressionConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 3, $"Expected 3 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // The first child node is the condition expression. If this matches, then we branch to the "yes" branch. // If it doesn't match, then we branch to the optional "no" branch if it exists, or simply skip the "yes" // branch, otherwise. The condition is treated as a positive lookaround. RegexNode condition = node.Child(0); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(1); RegexNode? noBranch = node.Child(2) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; string originalDoneLabel = doneLabel; string expressionNotMatched = ReserveName("ConditionalExpressionNotMatched"); string endConditional = ReserveName("ConditionalExpressionEnd"); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the condition needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. string resumeAt = ReserveName("conditionalexpression_branch"); if (!isAtomic) { writer.WriteLine($"int {resumeAt} = 0;"); } // If the condition expression has captures, we'll need to uncapture them in the case of no match. string? startingCapturePos = null; if (analysis.MayContainCapture(condition)) { startingCapturePos = ReserveName("conditionalexpression_starting_capturepos"); writer.WriteLine($"int {startingCapturePos} = base.Crawlpos();"); } // Emit the condition expression. Route any failures to after the yes branch. This code is almost // the same as for a positive lookaround; however, a positive lookaround only needs to reset the position // on a successful match, as a failed match fails the whole expression; here, we need to reset the // position on completion, regardless of whether the match is successful or not. doneLabel = expressionNotMatched; // Save off pos. We'll need to reset this upon successful completion of the lookaround. string startingPos = ReserveName("conditionalexpression_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); int startingSliceStaticPos = sliceStaticPos; // Emit the child. The condition expression is a zero-width assertion, which is atomic, // so prevent backtracking into it. writer.WriteLine("// Condition:"); EmitNode(condition); writer.WriteLine(); doneLabel = originalDoneLabel; // After the condition completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. writer.WriteLine("// Condition matched:"); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; writer.WriteLine(); // The expression matched. Run the "yes" branch. If it successfully matches, jump to the end. EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch string postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 0;"); } Goto(endConditional); writer.WriteLine(); // After the condition completes unsuccessfully, reset the text positions // _and_ reset captures, which should not persist when the whole expression failed. writer.WriteLine("// Condition did not match:"); MarkLabel(expressionNotMatched, emitSemicolon: false); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } writer.WriteLine(); string postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 1;"); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 2;"); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { doneLabel = originalDoneLabel; MarkLabel(endConditional); } else { // Skip the backtracking section. Goto(endConditional); writer.WriteLine(); string backtrack = ReserveName("ConditionalExpressionBacktrack"); doneLabel = backtrack; MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(resumeAt); using (EmitBlock(writer, $"switch ({resumeAt})")) { if (postYesDoneLabel != originalDoneLabel) { CaseGoto("case 0:", postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { CaseGoto("case 1:", postNoDoneLabel); } CaseGoto("default:", originalDoneLabel); } MarkLabel(endConditional, emitSemicolon: false); EmitStackPush(resumeAt); } } // Emits the code for a Capture node. void EmitCapture(RegexNode node, RegexNode? subsequent = null) { Debug.Assert(node.Kind is RegexNodeKind.Capture, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); int uncapnum = RegexParser.MapCaptureNumber(node.N, rm.Tree.CaptureNumberSparseMapping); bool isAtomic = analysis.IsAtomicByAncestor(node); TransferSliceStaticPosToPos(); string startingPos = ReserveName("capture_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); RegexNode child = node.Child(0); if (uncapnum != -1) { using (EmitBlock(writer, $"if (!base.IsMatched({uncapnum}))")) { Goto(doneLabel); } writer.WriteLine(); } // Emit child node. string originalDoneLabel = doneLabel; EmitNode(child, subsequent); bool childBacktracks = doneLabel != originalDoneLabel; writer.WriteLine(); TransferSliceStaticPosToPos(); if (uncapnum == -1) { writer.WriteLine($"base.Capture({capnum}, {startingPos}, pos);"); } else { writer.WriteLine($"base.TransferCapture({capnum}, {uncapnum}, {startingPos}, pos);"); } if (isAtomic || !childBacktracks) { // If the capture is atomic and nothing can backtrack into it, we're done. // Similarly, even if the capture isn't atomic, if the captured expression // doesn't do any backtracking, we're done. doneLabel = originalDoneLabel; } else { // We're not atomic and the child node backtracks. When it does, we need // to ensure that the starting position for the capture is appropriately // reset to what it was initially (it could have changed as part of being // in a loop or similar). So, we emit a backtracking section that // pushes/pops the starting position before falling through. writer.WriteLine(); EmitStackPush(startingPos); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label string backtrack = ReserveName($"CaptureBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(startingPos); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } // Emits the code to handle a positive lookaround assertion. This is a positive lookahead // for left-to-right and a positive lookbehind for right-to-left. void EmitPositiveLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.PositiveLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } // Save off pos. We'll need to reset this upon successful completion of the lookaround. string startingPos = ReserveName("positivelookaround_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); int startingSliceStaticPos = sliceStaticPos; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // After the child completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. writer.WriteLine(); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; } // Emits the code to handle a negative lookaround assertion. This is a negative lookahead // for left-to-right and a negative lookbehind for right-to-left. void EmitNegativeLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } string originalDoneLabel = doneLabel; // Save off pos. We'll need to reset this upon successful completion of the lookaround. string startingPos = ReserveName("negativelookaround_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); int startingSliceStaticPos = sliceStaticPos; string negativeLookaroundDoneLabel = ReserveName("NegativeLookaroundMatch"); doneLabel = negativeLookaroundDoneLabel; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // If the generated code ends up here, it matched the lookaround, which actually // means failure for a _negative_ lookaround, so we need to jump to the original done. writer.WriteLine(); Goto(originalDoneLabel); writer.WriteLine(); // Failures (success for a negative lookaround) jump here. MarkLabel(negativeLookaroundDoneLabel, emitSemicolon: false); // After the child completes in failure (success for negative lookaround), reset the text positions. writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; doneLabel = originalDoneLabel; } // Emits the code for the node. void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(EmitNode, node, subsequent, emitLengthChecksIfRequired); return; } if ((node.Options & RegexOptions.RightToLeft) != 0) { // RightToLeft doesn't take advantage of static positions. While RightToLeft won't update static // positions, a previous operation may have left us with a non-zero one. Make sure it's zero'd out // such that pos and slice are up-to-date. Note that RightToLeft also shouldn't use the slice span, // as it's not kept up-to-date; any RightToLeft implementation that wants to use it must first update // it from pos. TransferSliceStaticPosToPos(); } // Separate out several node types that, for conciseness, don't need a header and scope written into the source. switch (node.Kind) { // Nothing is written for an empty case RegexNodeKind.Empty: return; // A match failure doesn't need a scope. case RegexNodeKind.Nothing: Goto(doneLabel); return; // Skip atomic nodes that wrap non-backtracking children; in such a case there's nothing to be made atomic. case RegexNodeKind.Atomic when !analysis.MayBacktrack(node.Child(0)): EmitNode(node.Child(0)); return; // Concatenate is a simplification in the node tree so that a series of children can be represented as one. // We don't need its presence visible in the source. case RegexNodeKind.Concatenate: EmitConcatenation(node, subsequent, emitLengthChecksIfRequired); return; } // Put the node's code into its own scope. If the node contains labels that may need to // be visible outside of its scope, the scope is still emitted for clarity but is commented out. using (EmitScope(writer, DescribeNode(node, analysis), faux: analysis.MayBacktrack(node))) { switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: case RegexNodeKind.Bol: case RegexNodeKind.Eol: case RegexNodeKind.End: case RegexNodeKind.EndZ: EmitAnchors(node); break; case RegexNodeKind.Boundary: case RegexNodeKind.NonBoundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.NonECMABoundary: EmitBoundary(node); break; case RegexNodeKind.Multi: EmitMultiChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: EmitSingleChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: EmitSingleCharLoop(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: EmitSingleCharLazy(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: EmitSingleCharAtomicLoop(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Loop: EmitLoop(node); break; case RegexNodeKind.Lazyloop: EmitLazy(node); break; case RegexNodeKind.Alternate: EmitAlternation(node); break; case RegexNodeKind.Backreference: EmitBackreference(node); break; case RegexNodeKind.BackreferenceConditional: EmitBackreferenceConditional(node); break; case RegexNodeKind.ExpressionConditional: EmitExpressionConditional(node); break; case RegexNodeKind.Atomic: Debug.Assert(analysis.MayBacktrack(node.Child(0))); EmitAtomic(node, subsequent); return; case RegexNodeKind.Capture: EmitCapture(node, subsequent); break; case RegexNodeKind.PositiveLookaround: EmitPositiveLookaroundAssertion(node); break; case RegexNodeKind.NegativeLookaround: EmitNegativeLookaroundAssertion(node); break; case RegexNodeKind.UpdateBumpalong: EmitUpdateBumpalong(node); break; default: Debug.Fail($"Unexpected node type: {node.Kind}"); break; } } } // Emits the node for an atomic. void EmitAtomic(RegexNode node, RegexNode? subsequent) { Debug.Assert(node.Kind is RegexNodeKind.Atomic or RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(analysis.MayBacktrack(node.Child(0)), "Expected child to potentially backtrack"); // Grab the current done label and the current backtracking position. The purpose of the atomic node // is to ensure that nodes after it that might backtrack skip over the atomic, which means after // rendering the atomic's child, we need to reset the label so that subsequent backtracking doesn't // see any label left set by the atomic's child. We also need to reset the backtracking stack position // so that the state on the stack remains consistent. string originalDoneLabel = doneLabel; additionalDeclarations.Add("int stackpos = 0;"); string startingStackpos = ReserveName("atomic_stackpos"); writer.WriteLine($"int {startingStackpos} = stackpos;"); writer.WriteLine(); // Emit the child. EmitNode(node.Child(0), subsequent); writer.WriteLine(); // Reset the stack position and done label. writer.WriteLine($"stackpos = {startingStackpos};"); doneLabel = originalDoneLabel; } // Emits the code to handle updating base.runtextpos to pos in response to // an UpdateBumpalong node. This is used when we want to inform the scan loop that // it should bump from this location rather than from the original location. void EmitUpdateBumpalong(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.UpdateBumpalong, $"Unexpected type: {node.Kind}"); TransferSliceStaticPosToPos(); using (EmitBlock(writer, "if (base.runtextpos < pos)")) { writer.WriteLine("base.runtextpos = pos;"); } } // Emits code for a concatenation void EmitConcatenation(RegexNode node, RegexNode? subsequent, bool emitLengthChecksIfRequired) { Debug.Assert(node.Kind is RegexNodeKind.Concatenate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); // Emit the code for each child one after the other. string? prevDescription = null; int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { // If we can find a subsequence of fixed-length children, we can emit a length check once for that sequence // and then skip the individual length checks for each. We also want to minimize the repetition of if blocks, // and so we try to emit a series of clauses all part of the same if block rather than one if block per child. if ((node.Options & RegexOptions.RightToLeft) == 0 && emitLengthChecksIfRequired && node.TryGetJoinableLengthCheckChildRange(i, out int requiredLength, out int exclusiveEnd)) { bool wroteClauses = true; writer.Write($"if ({SpanLengthCheck(requiredLength)}"); while (i < exclusiveEnd) { for (; i < exclusiveEnd; i++) { void WriteSingleCharChild(RegexNode child, bool includeDescription = true) { if (wroteClauses) { writer.WriteLine(prevDescription is not null ? $" || // {prevDescription}" : " ||"); writer.Write(" "); } else { writer.Write("if ("); } EmitSingleChar(child, emitLengthCheck: false, clauseOnly: true); prevDescription = includeDescription ? DescribeNode(child, analysis) : null; wroteClauses = true; } RegexNode child = node.Child(i); if (child.Kind is RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set) { WriteSingleCharChild(child); } else if (child.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Onelazy or RegexNodeKind.Oneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloopatomic && child.M == child.N && child.M <= MaxUnrollSize) { for (int c = 0; c < child.M; c++) { WriteSingleCharChild(child, includeDescription: c == 0); } } else { break; } } if (wroteClauses) { writer.WriteLine(prevDescription is not null ? $") // {prevDescription}" : ")"); using (EmitBlock(writer, null)) { Goto(doneLabel); } if (i < childCount) { writer.WriteLine(); } wroteClauses = false; prevDescription = null; } if (i < exclusiveEnd) { EmitNode(node.Child(i), GetSubsequentOrDefault(i, node, subsequent), emitLengthChecksIfRequired: false); if (i < childCount - 1) { writer.WriteLine(); } i++; } } i--; continue; } EmitNode(node.Child(i), GetSubsequentOrDefault(i, node, subsequent), emitLengthChecksIfRequired: emitLengthChecksIfRequired); if (i < childCount - 1) { writer.WriteLine(); } } // Gets the node to treat as the subsequent one to node.Child(index) static RegexNode? GetSubsequentOrDefault(int index, RegexNode node, RegexNode? defaultNode) { int childCount = node.ChildCount(); for (int i = index + 1; i < childCount; i++) { RegexNode next = node.Child(i); if (next.Kind is not RegexNodeKind.UpdateBumpalong) // skip node types that don't have a semantic impact { return next; } } return defaultNode; } } // Emits the code to handle a single-character match. void EmitSingleChar(RegexNode node, bool emitLengthCheck = true, string? offset = null, bool clauseOnly = false) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; Debug.Assert(!rtl || offset is null); Debug.Assert(!rtl || !clauseOnly); string expr = !rtl ? $"{sliceSpan}[{Sum(sliceStaticPos, offset)}]" : "inputSpan[pos - 1]"; if (node.IsSetFamily) { expr = $"{MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: true, additionalDeclarations, ref requiredHelpers)}"; } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "!=" : "==")} {Literal(node.Ch)}"; } if (clauseOnly) { writer.Write(expr); } else { string clause = !emitLengthCheck ? $"if ({expr})" : !rtl ? $"if ({SpanLengthCheck(1, offset)} || {expr})" : $"if ((uint)(pos - 1) >= inputSpan.Length || {expr})"; using (EmitBlock(writer, clause)) { Goto(doneLabel); } } if (!rtl) { sliceStaticPos++; } else { writer.WriteLine("pos--;"); } } // Emits the code to handle a boundary check on a character. void EmitBoundary(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Boundary or RegexNodeKind.NonBoundary or RegexNodeKind.ECMABoundary or RegexNodeKind.NonECMABoundary, $"Unexpected type: {node.Kind}"); string call = node.Kind switch { RegexNodeKind.Boundary => "!IsBoundary", RegexNodeKind.NonBoundary => "IsBoundary", RegexNodeKind.ECMABoundary => "!IsECMABoundary", _ => "IsECMABoundary", }; RequiredHelperFunctions boundaryFunctionRequired = node.Kind switch { RegexNodeKind.Boundary or RegexNodeKind.NonBoundary => RequiredHelperFunctions.IsBoundary | RequiredHelperFunctions.IsWordChar, // IsBoundary internally uses IsWordChar _ => RequiredHelperFunctions.IsECMABoundary }; requiredHelpers |= boundaryFunctionRequired; using (EmitBlock(writer, $"if ({call}(inputSpan, pos{(sliceStaticPos > 0 ? $" + {sliceStaticPos}" : "")}))")) { Goto(doneLabel); } } // Emits the code to handle various anchors. void EmitAnchors(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.Bol or RegexNodeKind.End or RegexNodeKind.EndZ or RegexNodeKind.Eol, $"Unexpected type: {node.Kind}"); Debug.Assert((node.Options & RegexOptions.RightToLeft) == 0 || sliceStaticPos == 0); Debug.Assert(sliceStaticPos >= 0); switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: if (sliceStaticPos > 0) { // If we statically know we've already matched part of the regex, there's no way we're at the // beginning or start, as we've already progressed past it. Goto(doneLabel); } else { using (EmitBlock(writer, node.Kind == RegexNodeKind.Beginning ? "if (pos != 0)" : "if (pos != base.runtextstart)")) { Goto(doneLabel); } } break; case RegexNodeKind.Bol: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceSpan}[{sliceStaticPos - 1}] != '\\n')" : $"if (pos > 0 && inputSpan[pos - 1] != '\\n')")) { Goto(doneLabel); } break; case RegexNodeKind.End: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceStaticPos} < {sliceSpan}.Length)" : "if ((uint)pos < (uint)inputSpan.Length)")) { Goto(doneLabel); } break; case RegexNodeKind.EndZ: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceStaticPos + 1} < {sliceSpan}.Length || ({sliceStaticPos} < {sliceSpan}.Length && {sliceSpan}[{sliceStaticPos}] != '\\n'))" : "if (pos < inputSpan.Length - 1 || ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\\n'))")) { Goto(doneLabel); } break; case RegexNodeKind.Eol: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceStaticPos} < {sliceSpan}.Length && {sliceSpan}[{sliceStaticPos}] != '\\n')" : "if ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\\n')")) { Goto(doneLabel); } break; } } // Emits the code to handle a multiple-character match. void EmitMultiChar(RegexNode node, bool emitLengthCheck) { Debug.Assert(node.Kind is RegexNodeKind.Multi, $"Unexpected type: {node.Kind}"); Debug.Assert(node.Str is not null); EmitMultiCharString(node.Str, IsCaseInsensitive(node), emitLengthCheck, (node.Options & RegexOptions.RightToLeft) != 0); } void EmitMultiCharString(string str, bool caseInsensitive, bool emitLengthCheck, bool rightToLeft) { Debug.Assert(str.Length >= 2); if (rightToLeft) { Debug.Assert(emitLengthCheck); using (EmitBlock(writer, $"if ((uint)(pos - {str.Length}) >= inputSpan.Length)")) { Goto(doneLabel); } writer.WriteLine(); using (EmitBlock(writer, $"for (int i = 0; i < {str.Length}; i++)")) { using (EmitBlock(writer, $"if ({ToLowerIfNeeded(hasTextInfo, options, "inputSpan[--pos]", caseInsensitive)} != {Literal(str)}[{str.Length - 1} - i])")) { Goto(doneLabel); } } return; } if (caseInsensitive) // StartsWith(..., XxIgnoreCase) won't necessarily be the same as char-by-char comparison { // This case should be relatively rare. It will only occur with IgnoreCase and a series of non-ASCII characters. if (emitLengthCheck) { EmitSpanLengthCheck(str.Length); } using (EmitBlock(writer, $"for (int i = 0; i < {Literal(str)}.Length; i++)")) { string textSpanIndex = sliceStaticPos > 0 ? $"i + {sliceStaticPos}" : "i"; using (EmitBlock(writer, $"if ({ToLower(hasTextInfo, options, $"{sliceSpan}[{textSpanIndex}]")} != {Literal(str)}[i])")) { Goto(doneLabel); } } } else { string sourceSpan = sliceStaticPos > 0 ? $"{sliceSpan}.Slice({sliceStaticPos})" : sliceSpan; using (EmitBlock(writer, $"if (!global::System.MemoryExtensions.StartsWith({sourceSpan}, {Literal(str)}))")) { Goto(doneLabel); } } sliceStaticPos += str.Length; } void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop, $"Unexpected type: {node.Kind}"); // If this is actually atomic based on its parent, emit it as atomic instead; no backtracking necessary. if (analysis.IsAtomicByAncestor(node)) { EmitSingleCharAtomicLoop(node); return; } // If this is actually a repeater, emit that instead; no backtracking necessary. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // Emit backtracking around an atomic single char loop. We can then implement the backtracking // as an afterthought, since we know exactly how many characters are accepted by each iteration // of the wrapped loop (1) and that there's nothing captured by the loop. Debug.Assert(node.M < node.N); string backtrackingLabel = ReserveName("CharLoopBacktrack"); string endLoop = ReserveName("CharLoopEnd"); string startingPos = ReserveName("charloop_starting_pos"); string endingPos = ReserveName("charloop_ending_pos"); additionalDeclarations.Add($"int {startingPos} = 0, {endingPos} = 0;"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // Grab the current position, then emit the loop as atomic, and then // grab the current position again. Even though we emit the loop without // knowledge of backtracking, we can layer it on top by just walking back // through the individual characters (a benefit of the loop matching exactly // one character per iteration, no possible captures within the loop, etc.) writer.WriteLine($"{startingPos} = pos;"); writer.WriteLine(); EmitSingleCharAtomicLoop(node); writer.WriteLine(); TransferSliceStaticPosToPos(); writer.WriteLine($"{endingPos} = pos;"); EmitAdd(writer, startingPos, !rtl ? node.M : -node.M); Goto(endLoop); writer.WriteLine(); // Backtracking section. Subsequent failures will jump to here, at which // point we decrement the matched count as long as it's above the minimum // required, and try again by flowing to everything that comes after this. MarkLabel(backtrackingLabel, emitSemicolon: false); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } EmitStackPop(endingPos, startingPos); writer.WriteLine(); if (!rtl && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal) { writer.WriteLine($"if ({startingPos} >= {endingPos} ||"); using (EmitBlock(writer, literal.Item2 is not null ? $" ({endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, global::System.Math.Min(inputSpan.Length, {endingPos} + {literal.Item2.Length - 1}) - {startingPos}), {Literal(literal.Item2)})) < 0)" : literal.Item3 is null ? $" ({endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item1)})) < 0)" : literal.Item3.Length switch { 2 => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])})) < 0)", 3 => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])}, {Literal(literal.Item3[2])})) < 0)", _ => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3)})) < 0)", })) { Goto(doneLabel); } writer.WriteLine($"{endingPos} += {startingPos};"); writer.WriteLine($"pos = {endingPos};"); } else { using (EmitBlock(writer, $"if ({startingPos} {(!rtl ? ">=" : "<=")} {endingPos})")) { Goto(doneLabel); } writer.WriteLine(!rtl ? $"pos = --{endingPos};" : $"pos = ++{endingPos};"); } if (!rtl) { SliceInputSpan(writer); } writer.WriteLine(); MarkLabel(endLoop, emitSemicolon: false); EmitStackPush(expressionHasCaptures ? new[] { startingPos, endingPos, "base.Crawlpos()" } : new[] { startingPos, endingPos }); doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes } void EmitSingleCharLazy(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy, $"Unexpected type: {node.Kind}"); // Emit the min iterations as a repeater. Any failures here don't necessitate backtracking, // as the lazy itself failed to match, and there's no backtracking possible by the individual // characters/iterations themselves. if (node.M > 0) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); } // If the whole thing was actually that repeater, we're done. Similarly, if this is actually an atomic // lazy loop, nothing will ever backtrack into this node, so we never need to iterate more than the minimum. if (node.M == node.N || analysis.IsAtomicByAncestor(node)) { return; } if (node.M > 0) { // We emitted a repeater to handle the required iterations; add a newline after it. writer.WriteLine(); } Debug.Assert(node.M < node.N); // We now need to match one character at a time, each time allowing the remainder of the expression // to try to match, and only matching another character if the subsequent expression fails to match. // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // If the loop isn't unbounded, track the number of iterations and the max number to allow. string? iterationCount = null; string? maxIterations = null; if (node.N != int.MaxValue) { maxIterations = $"{node.N - node.M}"; iterationCount = ReserveName("lazyloop_iteration"); writer.WriteLine($"int {iterationCount} = 0;"); } // Track the current crawl position. Upon backtracking, we'll unwind any captures beyond this point. string? capturePos = null; if (expressionHasCaptures) { capturePos = ReserveName("lazyloop_capturepos"); additionalDeclarations.Add($"int {capturePos} = 0;"); } // Track the current pos. Each time we backtrack, we'll reset to the stored position, which // is also incremented each time we match another character in the loop. string startingPos = ReserveName("lazyloop_pos"); additionalDeclarations.Add($"int {startingPos} = 0;"); writer.WriteLine($"{startingPos} = pos;"); // Skip the backtracking section for the initial subsequent matching. We've already matched the // minimum number of iterations, which means we can successfully match with zero additional iterations. string endLoopLabel = ReserveName("LazyLoopEnd"); Goto(endLoopLabel); writer.WriteLine(); // Backtracking section. Subsequent failures will jump to here. string backtrackingLabel = ReserveName("LazyLoopBacktrack"); MarkLabel(backtrackingLabel, emitSemicolon: false); // Uncapture any captures if the expression has any. It's possible the captures it has // are before this node, in which case this is wasted effort, but still functionally correct. if (capturePos is not null) { EmitUncaptureUntil(capturePos); } // If there's a max number of iterations, see if we've exceeded the maximum number of characters // to match. If we haven't, increment the iteration count. if (maxIterations is not null) { using (EmitBlock(writer, $"if ({iterationCount} >= {maxIterations})")) { Goto(doneLabel); } writer.WriteLine($"{iterationCount}++;"); } // Now match the next item in the lazy loop. We need to reset the pos to the position // just after the last character in this loop was matched, and we need to store the resulting position // for the next time we backtrack. writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); EmitSingleChar(node); TransferSliceStaticPosToPos(); // Now that we've appropriately advanced by one character and are set for what comes after the loop, // see if we can skip ahead more iterations by doing a search for a following literal. if ((node.Options & RegexOptions.RightToLeft) == 0) { if (iterationCount is null && node.Kind is RegexNodeKind.Notonelazy && !IsCaseInsensitive(node) && subsequent?.FindStartingLiteral(4) is ValueTuple<char, string?, string?> literal && // 5 == max optimized by IndexOfAny, and we need to reserve 1 for node.Ch (literal.Item3 is not null ? !literal.Item3.Contains(node.Ch) : (literal.Item2?[0] ?? literal.Item1) != node.Ch)) // no overlap between node.Ch and the start of the literal { // e.g. "<[^>]*?>" // This lazy loop will consume all characters other than node.Ch until the subsequent literal. // We can implement it to search for either that char or the literal, whichever comes first. // If it ends up being that node.Ch, the loop fails (we're only here if we're backtracking). writer.WriteLine( literal.Item2 is not null ? $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item2[0])});" : literal.Item3 is null ? $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item1)});" : literal.Item3.Length switch { 2 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])});", _ => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch + literal.Item3)});", }); using (EmitBlock(writer, $"if ((uint){startingPos} >= (uint){sliceSpan}.Length || {sliceSpan}[{startingPos}] == {Literal(node.Ch)})")) { Goto(doneLabel); } writer.WriteLine($"pos += {startingPos};"); SliceInputSpan(writer); } else if (iterationCount is null && node.Kind is RegexNodeKind.Setlazy && node.Str == RegexCharClass.AnyClass && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal2) { // e.g. ".*?string" with RegexOptions.Singleline // This lazy loop will consume all characters until the subsequent literal. If the subsequent literal // isn't found, the loop fails. We can implement it to just search for that literal. writer.WriteLine( literal2.Item2 is not null ? $"{startingPos} = global::System.MemoryExtensions.IndexOf({sliceSpan}, {Literal(literal2.Item2)});" : literal2.Item3 is null ? $"{startingPos} = global::System.MemoryExtensions.IndexOf({sliceSpan}, {Literal(literal2.Item1)});" : literal2.Item3.Length switch { 2 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3[0])}, {Literal(literal2.Item3[1])});", 3 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3[0])}, {Literal(literal2.Item3[1])}, {Literal(literal2.Item3[2])});", _ => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3)});", }); using (EmitBlock(writer, $"if ({startingPos} < 0)")) { Goto(doneLabel); } writer.WriteLine($"pos += {startingPos};"); SliceInputSpan(writer); } } // Store the position we've left off at in case we need to iterate again. writer.WriteLine($"{startingPos} = pos;"); // Update the done label for everything that comes after this node. This is done after we emit the single char // matching, as that failing indicates the loop itself has failed to match. string originalDoneLabel = doneLabel; doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes writer.WriteLine(); MarkLabel(endLoopLabel); if (capturePos is not null) { writer.WriteLine($"{capturePos} = base.Crawlpos();"); } if (node.IsInLoop()) { writer.WriteLine(); // Store the loop's state var toPushPop = new List<string>(3) { startingPos }; if (capturePos is not null) { toPushPop.Add(capturePos); } if (iterationCount is not null) { toPushPop.Add(iterationCount); } string[] toPushPopArray = toPushPop.ToArray(); EmitStackPush(toPushPopArray); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label string backtrack = ReserveName("CharLazyBacktrack"); MarkLabel(backtrack, emitSemicolon: false); Array.Reverse(toPushPopArray); EmitStackPop(toPushPopArray); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } void EmitLazy(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; string originalDoneLabel = doneLabel; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually an atomic lazy loop, we need to output just the minimum number of iterations, // as nothing will backtrack into the lazy loop to get it progress further. if (isAtomic) { switch (minIterations) { case 0: // Atomic lazy with a min count of 0: nop. return; case 1: // Atomic lazy with a min count of 1: just output the child, no looping required. EmitNode(node.Child(0)); return; } writer.WriteLine(); } // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); string startingPos = ReserveName("lazyloop_starting_pos"); string iterationCount = ReserveName("lazyloop_iteration"); string sawEmpty = ReserveName("lazyLoopEmptySeen"); string body = ReserveName("LazyLoopBody"); string endLoop = ReserveName("LazyLoopEnd"); writer.WriteLine($"int {iterationCount} = 0, {startingPos} = pos, {sawEmpty} = 0;"); // If the min count is 0, start out by jumping right to what's after the loop. Backtracking // will then bring us back in to do further iterations. if (minIterations == 0) { Goto(endLoop); } writer.WriteLine(); // Iteration body MarkLabel(body, emitSemicolon: false); EmitTimeoutCheck(writer, hasTimeout); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackPush(expressionHasCaptures ? new[] { "base.Crawlpos()", startingPos, "pos", sawEmpty } : new[] { startingPos, "pos", sawEmpty }); writer.WriteLine(); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. writer.WriteLine($"{startingPos} = pos;"); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. writer.WriteLine($"{iterationCount}++;"); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. string iterationFailedLabel = ReserveName("LazyLoopIterationNoMatch"); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); writer.WriteLine(); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 if (doneLabel == iterationFailedLabel) { doneLabel = originalDoneLabel; } // Loop condition. Continue iterating if we've not yet reached the minimum. if (minIterations > 0) { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, minIterations)})")) { Goto(body); } } // If the last iteration was empty, we need to prevent further iteration from this point // unless we backtrack out of this iteration. We can do that easily just by pretending // we reached the max iteration count. using (EmitBlock(writer, $"if (pos == {startingPos})")) { writer.WriteLine($"{sawEmpty} = 1;"); } // We matched the next iteration. Jump to the subsequent code. Goto(endLoop); writer.WriteLine(); // Now handle what happens when an iteration fails. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel, emitSemicolon: false); writer.WriteLine($"{iterationCount}--;"); using (EmitBlock(writer, $"if ({iterationCount} < 0)")) { Goto(originalDoneLabel); } EmitStackPop(sawEmpty, "pos", startingPos); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } SliceInputSpan(writer); if (doneLabel == originalDoneLabel) { Goto(originalDoneLabel); } else { using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } Goto(doneLabel); } writer.WriteLine(); MarkLabel(endLoop); if (!isAtomic) { // Store the capture's state and skip the backtracking section EmitStackPush(startingPos, iterationCount, sawEmpty); string skipBacktrack = ReserveName("SkipBacktrack"); Goto(skipBacktrack); writer.WriteLine(); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label string backtrack = ReserveName($"LazyLoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(sawEmpty, iterationCount, startingPos); if (maxIterations == int.MaxValue) { using (EmitBlock(writer, $"if ({sawEmpty} == 0)")) { Goto(body); } } else { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, maxIterations)} && {sawEmpty} == 0)")) { Goto(body); } } Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(skipBacktrack); } } // Emits the code to handle a loop (repeater) with a fixed number of iterations. // RegexNode.M is used for the number of iterations (RegexNode.N is ignored), as this // might be used to implement the required iterations of other kinds of loops. void EmitSingleCharRepeater(RegexNode node, bool emitLengthCheck = true) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); int iterations = node.M; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; switch (iterations) { case 0: // No iterations, nothing to do. return; case 1: // Just match the individual item EmitSingleChar(node, emitLengthCheck); return; case <= RegexNode.MultiVsRepeaterLimit when node.IsOneFamily && !IsCaseInsensitive(node): // This is a repeated case-sensitive character; emit it as a multi in order to get all the optimizations // afforded to a multi, e.g. unrolling the loop with multi-char reads/comparisons at a time. EmitMultiCharString(new string(node.Ch, iterations), caseInsensitive: false, emitLengthCheck, rtl); return; } if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position with rtl using (EmitBlock(writer, $"for (int i = 0; i < {iterations}; i++)")) { EmitTimeoutCheck(writer, hasTimeout); EmitSingleChar(node); } } else if (iterations <= MaxUnrollSize) { // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length || // slice[sliceStaticPos] != c1 || // slice[sliceStaticPos + 1] != c2 || // ...) // { // goto doneLabel; // } writer.Write($"if ("); if (emitLengthCheck) { writer.WriteLine($"{SpanLengthCheck(iterations)} ||"); writer.Write(" "); } EmitSingleChar(node, emitLengthCheck: false, clauseOnly: true); for (int i = 1; i < iterations; i++) { writer.WriteLine(" ||"); writer.Write(" "); EmitSingleChar(node, emitLengthCheck: false, clauseOnly: true); } writer.WriteLine(")"); using (EmitBlock(writer, null)) { Goto(doneLabel); } } else { // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length) goto doneLabel; if (emitLengthCheck) { EmitSpanLengthCheck(iterations); } string repeaterSpan = "repeaterSlice"; // As this repeater doesn't wrap arbitrary node emits, this shouldn't conflict with anything writer.WriteLine($"global::System.ReadOnlySpan<char> {repeaterSpan} = {sliceSpan}.Slice({sliceStaticPos}, {iterations});"); using (EmitBlock(writer, $"for (int i = 0; i < {repeaterSpan}.Length; i++)")) { EmitTimeoutCheck(writer, hasTimeout); string tmpTextSpanLocal = sliceSpan; // we want EmitSingleChar to refer to this temporary int tmpSliceStaticPos = sliceStaticPos; sliceSpan = repeaterSpan; sliceStaticPos = 0; EmitSingleChar(node, emitLengthCheck: false, offset: "i"); sliceSpan = tmpTextSpanLocal; sliceStaticPos = tmpSliceStaticPos; } sliceStaticPos += iterations; } } // Emits the code to handle a non-backtracking, variable-length loop around a single character comparison. void EmitSingleCharAtomicLoop(RegexNode node, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); // If this is actually a repeater, emit that instead. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // If this is actually an optional single char, emit that instead. if (node.M == 0 && node.N == 1) { EmitAtomicSingleCharZeroOrOne(node); return; } Debug.Assert(node.N > node.M); int minIterations = node.M; int maxIterations = node.N; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; Span<char> setChars = stackalloc char[5]; // 5 is max optimized by IndexOfAny today int numSetChars = 0; string iterationLocal = ReserveName("iteration"); if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position for rtl string expr = $"inputSpan[pos - {iterationLocal} - 1]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } writer.WriteLine($"int {iterationLocal} = 0;"); string maxClause = maxIterations != int.MaxValue ? $"{CountIsLessThan(iterationLocal, maxIterations)} && " : ""; using (EmitBlock(writer, $"while ({maxClause}pos > {iterationLocal} && {expr})")) { EmitTimeoutCheck(writer, hasTimeout); writer.WriteLine($"{iterationLocal}++;"); } writer.WriteLine(); } else if (node.IsNotoneFamily && maxIterations == int.MaxValue && (!IsCaseInsensitive(node))) { // For Notone, we're looking for a specific character, as everything until we find // it is consumed by the loop. If we're unbounded, such as with ".*" and if we're case-sensitive, // we can use the vectorized IndexOf to do the search, rather than open-coding it. The unbounded // restriction is purely for simplicity; it could be removed in the future with additional code to // handle the unbounded case. writer.Write($"int {iterationLocal} = global::System.MemoryExtensions.IndexOf({sliceSpan}"); if (sliceStaticPos > 0) { writer.Write($".Slice({sliceStaticPos})"); } writer.WriteLine($", {Literal(node.Ch)});"); using (EmitBlock(writer, $"if ({iterationLocal} < 0)")) { writer.WriteLine(sliceStaticPos > 0 ? $"{iterationLocal} = {sliceSpan}.Length - {sliceStaticPos};" : $"{iterationLocal} = {sliceSpan}.Length;"); } writer.WriteLine(); } else if (node.IsSetFamily && maxIterations == int.MaxValue && !IsCaseInsensitive(node) && (numSetChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0 && RegexCharClass.IsNegated(node.Str!)) { // If the set is negated and contains only a few characters (if it contained 1 and was negated, it should // have been reduced to a Notone), we can use an IndexOfAny to find any of the target characters. // As with the notoneloopatomic above, the unbounded constraint is purely for simplicity. Debug.Assert(numSetChars > 1); writer.Write($"int {iterationLocal} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}"); if (sliceStaticPos != 0) { writer.Write($".Slice({sliceStaticPos})"); } writer.WriteLine(numSetChars switch { 2 => $", {Literal(setChars[0])}, {Literal(setChars[1])});", 3 => $", {Literal(setChars[0])}, {Literal(setChars[1])}, {Literal(setChars[2])});", _ => $", {Literal(setChars.Slice(0, numSetChars).ToString())});", }); using (EmitBlock(writer, $"if ({iterationLocal} < 0)")) { writer.WriteLine(sliceStaticPos > 0 ? $"{iterationLocal} = {sliceSpan}.Length - {sliceStaticPos};" : $"{iterationLocal} = {sliceSpan}.Length;"); } writer.WriteLine(); } else if (node.IsSetFamily && maxIterations == int.MaxValue && node.Str == RegexCharClass.AnyClass) { // .* was used with RegexOptions.Singleline, which means it'll consume everything. Just jump to the end. // The unbounded constraint is the same as in the Notone case above, done purely for simplicity. TransferSliceStaticPosToPos(); writer.WriteLine($"int {iterationLocal} = inputSpan.Length - pos;"); } else { // For everything else, do a normal loop. string expr = $"{sliceSpan}[{iterationLocal}]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } if (minIterations != 0 || maxIterations != int.MaxValue) { // For any loops other than * loops, transfer text pos to pos in // order to zero it out to be able to use the single iteration variable // for both iteration count and indexer. TransferSliceStaticPosToPos(); } writer.WriteLine($"int {iterationLocal} = {sliceStaticPos};"); sliceStaticPos = 0; string maxClause = maxIterations != int.MaxValue ? $"{CountIsLessThan(iterationLocal, maxIterations)} && " : ""; using (EmitBlock(writer, $"while ({maxClause}(uint){iterationLocal} < (uint){sliceSpan}.Length && {expr})")) { EmitTimeoutCheck(writer, hasTimeout); writer.WriteLine($"{iterationLocal}++;"); } writer.WriteLine(); } // Check to ensure we've found at least min iterations. if (minIterations > 0) { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationLocal, minIterations)})")) { Goto(doneLabel); } writer.WriteLine(); } // Now that we've completed our optional iterations, advance the text span // and pos by the number of iterations completed. if (!rtl) { writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice({iterationLocal});"); writer.WriteLine($"pos += {iterationLocal};"); } else { writer.WriteLine($"pos -= {iterationLocal};"); } } // Emits the code to handle a non-backtracking optional zero-or-one loop. void EmitAtomicSingleCharZeroOrOne(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M == 0 && node.N == 1); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; if (rtl) { TransferSliceStaticPosToPos(); // we don't use static pos for rtl } string expr = !rtl ? $"{sliceSpan}[{sliceStaticPos}]" : "inputSpan[pos - 1]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } string spaceAvailable = rtl ? "pos > 0" : sliceStaticPos != 0 ? $"(uint){sliceSpan}.Length > (uint){sliceStaticPos}" : $"!{sliceSpan}.IsEmpty"; using (EmitBlock(writer, $"if ({spaceAvailable} && {expr})")) { if (!rtl) { writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice(1);"); writer.WriteLine($"pos++;"); } else { writer.WriteLine($"pos--;"); } } } void EmitNonBacktrackingRepeater(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.M == node.N, $"Unexpected M={node.M} == N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(!analysis.MayBacktrack(node.Child(0)), $"Expected non-backtracking node {node.Kind}"); // Ensure every iteration of the loop sees a consistent value. TransferSliceStaticPosToPos(); // Loop M==N times to match the child exactly that numbers of times. string i = ReserveName("loop_iteration"); using (EmitBlock(writer, $"for (int {i} = 0; {i} < {node.M}; {i}++)")) { EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // make sure static the static position remains at 0 for subsequent constructs } } void EmitLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); string originalDoneLabel = doneLabel; string startingPos = ReserveName("loop_starting_pos"); string iterationCount = ReserveName("loop_iteration"); string body = ReserveName("LoopBody"); string endLoop = ReserveName("LoopEnd"); additionalDeclarations.Add($"int {iterationCount} = 0, {startingPos} = 0;"); writer.WriteLine($"{iterationCount} = 0;"); writer.WriteLine($"{startingPos} = pos;"); writer.WriteLine(); // Iteration body MarkLabel(body, emitSemicolon: false); EmitTimeoutCheck(writer, hasTimeout); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackPush(expressionHasCaptures ? new[] { "base.Crawlpos()", startingPos, "pos" } : new[] { startingPos, "pos" }); writer.WriteLine(); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. writer.WriteLine($"{startingPos} = pos;"); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. writer.WriteLine($"{iterationCount}++;"); writer.WriteLine(); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. string iterationFailedLabel = ReserveName("LoopIterationNoMatch"); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); writer.WriteLine(); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 bool childBacktracks = doneLabel != iterationFailedLabel; // Loop condition. Continue iterating greedily if we've not yet reached the maximum. We also need to stop // iterating if the iteration matched empty and we already hit the minimum number of iterations. using (EmitBlock(writer, (minIterations > 0, maxIterations == int.MaxValue) switch { (true, true) => $"if (pos != {startingPos} || {CountIsLessThan(iterationCount, minIterations)})", (true, false) => $"if ((pos != {startingPos} || {CountIsLessThan(iterationCount, minIterations)}) && {CountIsLessThan(iterationCount, maxIterations)})", (false, true) => $"if (pos != {startingPos})", (false, false) => $"if (pos != {startingPos} && {CountIsLessThan(iterationCount, maxIterations)})", })) { Goto(body); } // We've matched as many iterations as we can with this configuration. Jump to what comes after the loop. Goto(endLoop); writer.WriteLine(); // Now handle what happens when an iteration fails, which could be an initial failure or it // could be while backtracking. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel, emitSemicolon: false); writer.WriteLine($"{iterationCount}--;"); using (EmitBlock(writer, $"if ({iterationCount} < 0)")) { Goto(originalDoneLabel); } EmitStackPop("pos", startingPos); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } SliceInputSpan(writer); if (minIterations > 0) { using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, minIterations)})")) { Goto(childBacktracks ? doneLabel : originalDoneLabel); } } if (isAtomic) { doneLabel = originalDoneLabel; MarkLabel(endLoop); } else { if (childBacktracks) { Goto(endLoop); writer.WriteLine(); string backtrack = ReserveName("LoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } Goto(doneLabel); doneLabel = backtrack; } MarkLabel(endLoop); if (node.IsInLoop()) { writer.WriteLine(); // Store the loop's state EmitStackPush(startingPos, iterationCount); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label string backtrack = ReserveName("LoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(iterationCount, startingPos); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } } // Gets a comparison for whether the value is less than the upper bound. static string CountIsLessThan(string value, int exclusiveUpper) => exclusiveUpper == 1 ? $"{value} == 0" : $"{value} < {exclusiveUpper}"; // Emits code to unwind the capture stack until the crawl position specified in the provided local. void EmitUncaptureUntil(string capturepos) { string name = "UncaptureUntil"; if (!additionalLocalFunctions.ContainsKey(name)) { var lines = new string[9]; lines[0] = "// <summary>Undo captures until we reach the specified capture position.</summary>"; lines[1] = "[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"void {name}(int capturepos)"; lines[3] = "{"; lines[4] = " while (base.Crawlpos() > capturepos)"; lines[5] = " {"; lines[6] = " base.Uncapture();"; lines[7] = " }"; lines[8] = "}"; additionalLocalFunctions.Add(name, lines); } writer.WriteLine($"{name}({capturepos});"); } /// <summary>Pushes values on to the backtracking stack.</summary> void EmitStackPush(params string[] args) { Debug.Assert(args.Length is >= 1); string function = $"StackPush{args.Length}"; additionalDeclarations.Add("int stackpos = 0;"); if (!additionalLocalFunctions.ContainsKey(function)) { var lines = new string[24 + args.Length]; lines[0] = $"// <summary>Push {args.Length} value{(args.Length == 1 ? "" : "s")} onto the backtracking stack.</summary>"; lines[1] = $"[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"static void {function}(ref int[] stack, ref int pos{FormatN(", int arg{0}", args.Length)})"; lines[3] = $"{{"; lines[4] = $" // If there's space available for {(args.Length > 1 ? $"all {args.Length} values, store them" : "the value, store it")}."; lines[5] = $" int[] s = stack;"; lines[6] = $" int p = pos;"; lines[7] = $" if ((uint){(args.Length > 1 ? $"(p + {args.Length - 1})" : "p")} < (uint)s.Length)"; lines[8] = $" {{"; for (int i = 0; i < args.Length; i++) { lines[9 + i] = $" s[p{(i == 0 ? "" : $" + {i}")}] = arg{i};"; } lines[9 + args.Length] = args.Length > 1 ? $" pos += {args.Length};" : " pos++;"; lines[10 + args.Length] = $" return;"; lines[11 + args.Length] = $" }}"; lines[12 + args.Length] = $""; lines[13 + args.Length] = $" // Otherwise, resize the stack to make room and try again."; lines[14 + args.Length] = $" WithResize(ref stack, ref pos{FormatN(", arg{0}", args.Length)});"; lines[15 + args.Length] = $""; lines[16 + args.Length] = $" // <summary>Resize the backtracking stack array and push {args.Length} value{(args.Length == 1 ? "" : "s")} onto the stack.</summary>"; lines[17 + args.Length] = $" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]"; lines[18 + args.Length] = $" static void WithResize(ref int[] stack, ref int pos{FormatN(", int arg{0}", args.Length)})"; lines[19 + args.Length] = $" {{"; lines[20 + args.Length] = $" global::System.Array.Resize(ref stack, (pos + {args.Length - 1}) * 2);"; lines[21 + args.Length] = $" {function}(ref stack, ref pos{FormatN(", arg{0}", args.Length)});"; lines[22 + args.Length] = $" }}"; lines[23 + args.Length] = $"}}"; additionalLocalFunctions.Add(function, lines); } writer.WriteLine($"{function}(ref base.runstack!, ref stackpos, {string.Join(", ", args)});"); } /// <summary>Pops values from the backtracking stack into the specified locations.</summary> void EmitStackPop(params string[] args) { Debug.Assert(args.Length is >= 1); if (args.Length == 1) { writer.WriteLine($"{args[0]} = {StackPop()};"); return; } string function = $"StackPop{args.Length}"; if (!additionalLocalFunctions.ContainsKey(function)) { var lines = new string[5 + args.Length]; lines[0] = $"// <summary>Pop {args.Length} value{(args.Length == 1 ? "" : "s")} from the backtracking stack.</summary>"; lines[1] = $"[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"static void {function}(int[] stack, ref int pos{FormatN(", out int arg{0}", args.Length)})"; lines[3] = $"{{"; for (int i = 0; i < args.Length; i++) { lines[4 + i] = $" arg{i} = stack[--pos];"; } lines[4 + args.Length] = $"}}"; additionalLocalFunctions.Add(function, lines); } writer.WriteLine($"{function}(base.runstack, ref stackpos, out {string.Join(", out ", args)});"); } /// <summary>Expression for popping the next item from the backtracking stack.</summary> string StackPop() => "base.runstack![--stackpos]"; /// <summary>Concatenates the strings resulting from formatting the format string with the values [0, count).</summary> static string FormatN(string format, int count) => string.Concat(from i in Enumerable.Range(0, count) select string.Format(format, i)); } private static bool EmitLoopTimeoutCounterIfNeeded(IndentedTextWriter writer, RegexMethod rm) { if (rm.MatchTimeout != Timeout.Infinite) { writer.WriteLine("int loopTimeoutCounter = 0;"); return true; } return false; } /// <summary>Emits a timeout check.</summary> private static void EmitTimeoutCheck(IndentedTextWriter writer, bool hasTimeout) { const int LoopTimeoutCheckCount = 2048; // A conservative value to guarantee the correct timeout handling. if (hasTimeout) { // Increment counter for each loop iteration. // Emit code to check the timeout every 2048th iteration. using (EmitBlock(writer, $"if (++loopTimeoutCounter == {LoopTimeoutCheckCount})")) { writer.WriteLine("loopTimeoutCounter = 0;"); writer.WriteLine("base.CheckTimeout();"); } writer.WriteLine(); } } private static bool EmitInitializeCultureForTryMatchAtCurrentPositionIfNecessary(IndentedTextWriter writer, RegexMethod rm, AnalysisResults analysis) { if (analysis.HasIgnoreCase && ((RegexOptions)rm.Options & RegexOptions.CultureInvariant) == 0) { writer.WriteLine("global::System.Globalization.TextInfo textInfo = global::System.Globalization.CultureInfo.CurrentCulture.TextInfo;"); return true; } return false; } private static bool UseToLowerInvariant(bool hasTextInfo, RegexOptions options) => !hasTextInfo || (options & RegexOptions.CultureInvariant) != 0; private static string ToLower(bool hasTextInfo, RegexOptions options, string expression) => UseToLowerInvariant(hasTextInfo, options) ? $"char.ToLowerInvariant({expression})" : $"textInfo.ToLower({expression})"; private static string ToLowerIfNeeded(bool hasTextInfo, RegexOptions options, string expression, bool toLower) => toLower ? ToLower(hasTextInfo, options, expression) : expression; private static string MatchCharacterClass(bool hasTextInfo, RegexOptions options, string chExpr, string charClass, bool caseInsensitive, bool negate, HashSet<string> additionalDeclarations, ref RequiredHelperFunctions requiredHelpers) { // We need to perform the equivalent of calling RegexRunner.CharInClass(ch, charClass), // but that call is relatively expensive. Before we fall back to it, we try to optimize // some common cases for which we can do much better, such as known character classes // for which we can call a dedicated method, or a fast-path for ASCII using a lookup table. // First, see if the char class is a built-in one for which there's a better function // we can just call directly. Everything in this section must work correctly for both // case-sensitive and case-insensitive modes, regardless of culture. switch (charClass) { case RegexCharClass.AnyClass: // ideally this could just be "return true;", but we need to evaluate the expression for its side effects return $"({chExpr} {(negate ? "<" : ">=")} 0)"; // a char is unsigned and thus won't ever be negative case RegexCharClass.DigitClass: case RegexCharClass.NotDigitClass: negate ^= charClass == RegexCharClass.NotDigitClass; return $"{(negate ? "!" : "")}char.IsDigit({chExpr})"; case RegexCharClass.SpaceClass: case RegexCharClass.NotSpaceClass: negate ^= charClass == RegexCharClass.NotSpaceClass; return $"{(negate ? "!" : "")}char.IsWhiteSpace({chExpr})"; case RegexCharClass.WordClass: case RegexCharClass.NotWordClass: requiredHelpers |= RequiredHelperFunctions.IsWordChar; negate ^= charClass == RegexCharClass.NotWordClass; return $"{(negate ? "!" : "")}IsWordChar({chExpr})"; } // If we're meant to be doing a case-insensitive lookup, and if we're not using the invariant culture, // lowercase the input. If we're using the invariant culture, we may still end up calling ToLower later // on, but we may also be able to avoid it, in particular in the case of our lookup table, where we can // generate the lookup table already factoring in the invariant case sensitivity. There are multiple // special-code paths between here and the lookup table, but we only take those if invariant is false; // if it were true, they'd need to use CallToLower(). bool invariant = false; if (caseInsensitive) { invariant = UseToLowerInvariant(hasTextInfo, options); if (!invariant) { chExpr = ToLower(hasTextInfo, options, chExpr); } } // Next, handle simple sets of one range, e.g. [A-Z], [0-9], etc. This includes some built-in classes, like ECMADigitClass. if (!invariant && RegexCharClass.TryGetSingleRange(charClass, out char lowInclusive, out char highInclusive)) { negate ^= RegexCharClass.IsNegated(charClass); return lowInclusive == highInclusive ? $"({chExpr} {(negate ? "!=" : "==")} {Literal(lowInclusive)})" : $"(((uint){chExpr}) - {Literal(lowInclusive)} {(negate ? ">" : "<=")} (uint)({Literal(highInclusive)} - {Literal(lowInclusive)}))"; } // Next if the character class contains nothing but a single Unicode category, we can calle char.GetUnicodeCategory and // compare against it. It has a fast-lookup path for ASCII, so is as good or better than any lookup we'd generate (plus // we get smaller code), and it's what we'd do for the fallback (which we get to avoid generating) as part of CharInClass. if (!invariant && RegexCharClass.TryGetSingleUnicodeCategory(charClass, out UnicodeCategory category, out bool negated)) { negate ^= negated; return $"(char.GetUnicodeCategory({chExpr}) {(negate ? "!=" : "==")} global::System.Globalization.UnicodeCategory.{category})"; } // Next, if there's only 2 or 3 chars in the set (fairly common due to the sets we create for prefixes), // it may be cheaper and smaller to compare against each than it is to use a lookup table. We can also special-case // the very common case with case insensitivity of two characters next to each other being the upper and lowercase // ASCII variants of each other, in which case we can use bit manipulation to avoid a comparison. if (!invariant && !RegexCharClass.IsNegated(charClass)) { Span<char> setChars = stackalloc char[3]; int mask; switch (RegexCharClass.GetSetChars(charClass, setChars)) { case 2: if (RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out mask)) { return $"(({chExpr} | 0x{mask:X}) {(negate ? "!=" : "==")} {Literal((char)(setChars[1] | mask))})"; } additionalDeclarations.Add("char ch;"); return negate ? $"(((ch = {chExpr}) != {Literal(setChars[0])}) & (ch != {Literal(setChars[1])}))" : $"(((ch = {chExpr}) == {Literal(setChars[0])}) | (ch == {Literal(setChars[1])}))"; case 3: additionalDeclarations.Add("char ch;"); return (negate, RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out mask)) switch { (false, false) => $"(((ch = {chExpr}) == {Literal(setChars[0])}) | (ch == {Literal(setChars[1])}) | (ch == {Literal(setChars[2])}))", (true, false) => $"(((ch = {chExpr}) != {Literal(setChars[0])}) & (ch != {Literal(setChars[1])}) & (ch != {Literal(setChars[2])}))", (false, true) => $"((((ch = {chExpr}) | 0x{mask:X}) == {Literal((char)(setChars[1] | mask))}) | (ch == {Literal(setChars[2])}))", (true, true) => $"((((ch = {chExpr}) | 0x{mask:X}) != {Literal((char)(setChars[1] | mask))}) & (ch != {Literal(setChars[2])}))", }; } } // All options after this point require a ch local. additionalDeclarations.Add("char ch;"); // Analyze the character set more to determine what code to generate. RegexCharClass.CharClassAnalysisResults analysis = RegexCharClass.Analyze(charClass); if (!invariant) // if we're being asked to do a case insensitive, invariant comparison, use the lookup table { if (analysis.ContainsNoAscii) { // We determined that the character class contains only non-ASCII, // for example if the class were [\p{IsGreek}\p{IsGreekExtended}], which is // the same as [\u0370-\u03FF\u1F00-1FFF]. (In the future, we could possibly // extend the analysis to produce a known lower-bound and compare against // that rather than always using 128 as the pivot point.) return negate ? $"((ch = {chExpr}) < 128 || !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))" : $"((ch = {chExpr}) >= 128 && global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))"; } if (analysis.AllAsciiContained) { // We determined that every ASCII character is in the class, for example // if the class were the negated example from case 1 above: // [^\p{IsGreek}\p{IsGreekExtended}]. return negate ? $"((ch = {chExpr}) >= 128 && !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))" : $"((ch = {chExpr}) < 128 || global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))"; } } // Now, our big hammer is to generate a lookup table that lets us quickly index by character into a yes/no // answer as to whether the character is in the target character class. However, we don't want to store // a lookup table for every possible character for every character class in the regular expression; at one // bit for each of 65K characters, that would be an 8K bitmap per character class. Instead, we handle the // common case of ASCII input via such a lookup table, which at one bit for each of 128 characters is only // 16 bytes per character class. We of course still need to be able to handle inputs that aren't ASCII, so // we check the input against 128, and have a fallback if the input is >= to it. Determining the right // fallback could itself be expensive. For example, if it's possible that a value >= 128 could match the // character class, we output a call to RegexRunner.CharInClass, but we don't want to have to enumerate the // entire character class evaluating every character against it, just to determine whether it's a match. // Instead, we employ some quick heuristics that will always ensure we provide a correct answer even if // we could have sometimes generated better code to give that answer. // Generate the lookup table to store 128 answers as bits. We use a const string instead of a byte[] / static // data property because it lets IL emit handle all the details for us. string bitVectorString = StringExtensions.Create(8, (charClass, invariant), static (dest, state) => // String length is 8 chars == 16 bytes == 128 bits. { for (int i = 0; i < 128; i++) { char c = (char)i; bool isSet = state.invariant ? RegexCharClass.CharInClass(char.ToLowerInvariant(c), state.charClass) : RegexCharClass.CharInClass(c, state.charClass); if (isSet) { dest[i >> 4] |= (char)(1 << (i & 0xF)); } } }); // We determined that the character class may contain ASCII, so we // output the lookup against the lookup table. if (analysis.ContainsOnlyAscii) { // We know that all inputs that could match are ASCII, for example if the // character class were [A-Za-z0-9], so since the ch is now known to be >= 128, we // can just fail the comparison. return negate ? $"((ch = {chExpr}) >= 128 || ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0)" : $"((ch = {chExpr}) < 128 && ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0)"; } if (analysis.AllNonAsciiContained) { // We know that all non-ASCII inputs match, for example if the character // class were [^\r\n], so since we just determined the ch to be >= 128, we can just // give back success. return negate ? $"((ch = {chExpr}) < 128 && ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0)" : $"((ch = {chExpr}) >= 128 || ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0)"; } // We know that the whole class wasn't ASCII, and we don't know anything about the non-ASCII // characters other than that some might be included, for example if the character class // were [\w\d], so since ch >= 128, we need to fall back to calling CharInClass. return (negate, invariant) switch { (false, false) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0 : global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))", (true, false) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0 : !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))", (false, true) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0 : global::System.Text.RegularExpressions.RegexRunner.CharInClass(char.ToLowerInvariant((char)ch), {Literal(charClass)}))", (true, true) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0 : !global::System.Text.RegularExpressions.RegexRunner.CharInClass(char.ToLowerInvariant((char)ch), {Literal(charClass)}))", }; } /// <summary> /// Replaces <see cref="AdditionalDeclarationsPlaceholder"/> in <paramref name="writer"/> with /// all of the variable declarations in <paramref name="declarations"/>. /// </summary> /// <param name="writer">The writer around a StringWriter to have additional declarations inserted into.</param> /// <param name="declarations">The additional declarations to insert.</param> /// <param name="position">The position into the writer at which to insert the additional declarations.</param> /// <param name="indent">The indentation to use for the additional declarations.</param> private static void ReplaceAdditionalDeclarations(IndentedTextWriter writer, HashSet<string> declarations, int position, int indent) { if (declarations.Count != 0) { var tmp = new StringBuilder(); foreach (string decl in declarations.OrderBy(s => s)) { for (int i = 0; i < indent; i++) { tmp.Append(IndentedTextWriter.DefaultTabString); } tmp.AppendLine(decl); } ((StringWriter)writer.InnerWriter).GetStringBuilder().Insert(position, tmp.ToString()); } } /// <summary>Formats the character as valid C#.</summary> private static string Literal(char c) => SymbolDisplay.FormatLiteral(c, quote: true); /// <summary>Formats the string as valid C#.</summary> private static string Literal(string s) => SymbolDisplay.FormatLiteral(s, quote: true); private static string Literal(RegexOptions options) { string s = options.ToString(); if (int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out _)) { // The options were formatted as an int, which means the runtime couldn't // produce a textual representation. So just output casting the value as an int. Debug.Fail("This shouldn't happen, as we should only get to the point of emitting code if RegexOptions was valid."); return $"(global::System.Text.RegularExpressions.RegexOptions)({(int)options})"; } // Parse the runtime-generated "Option1, Option2" into each piece and then concat // them back together. string[] parts = s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < parts.Length; i++) { parts[i] = "global::System.Text.RegularExpressions.RegexOptions." + parts[i].Trim(); } return string.Join(" | ", parts); } /// <summary>Gets a textual description of the node fit for rendering in a comment in source.</summary> private static string DescribeNode(RegexNode node, AnalysisResults analysis) { bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; return node.Kind switch { RegexNodeKind.Alternate => $"Match with {node.ChildCount()} alternative expressions{(analysis.IsAtomicByAncestor(node) ? ", atomically" : "")}.", RegexNodeKind.Atomic => $"Atomic group.", RegexNodeKind.Beginning => "Match if at the beginning of the string.", RegexNodeKind.Bol => "Match if at the beginning of a line.", RegexNodeKind.Boundary => $"Match if at a word boundary.", RegexNodeKind.Capture when node.M == -1 && node.N != -1 => $"Non-capturing balancing group. Uncaptures the {DescribeCapture(node.N, analysis)}.", RegexNodeKind.Capture when node.N != -1 => $"Balancing group. Captures the {DescribeCapture(node.M, analysis)} and uncaptures the {DescribeCapture(node.N, analysis)}.", RegexNodeKind.Capture when node.N == -1 => $"{DescribeCapture(node.M, analysis)}.", RegexNodeKind.Concatenate => "Match a sequence of expressions.", RegexNodeKind.ECMABoundary => $"Match if at a word boundary (according to ECMAScript rules).", RegexNodeKind.Empty => $"Match an empty string.", RegexNodeKind.End => "Match if at the end of the string.", RegexNodeKind.EndZ => "Match if at the end of the string or if before an ending newline.", RegexNodeKind.Eol => "Match if at the end of a line.", RegexNodeKind.Loop or RegexNodeKind.Lazyloop => node.M == 0 && node.N == 1 ? $"Optional ({(node.Kind is RegexNodeKind.Loop ? "greedy" : "lazy")})." : $"Loop {DescribeLoop(node, analysis)}.", RegexNodeKind.Multi => $"Match the string {Literal(node.Str!)}{(rtl ? " backwards" : "")}.", RegexNodeKind.NonBoundary => $"Match if at anything other than a word boundary.", RegexNodeKind.NonECMABoundary => $"Match if at anything other than a word boundary (according to ECMAScript rules).", RegexNodeKind.Nothing => $"Fail to match.", RegexNodeKind.Notone => $"Match any character other than {Literal(node.Ch)}{(rtl ? " backwards" : "")}.", RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy => $"Match a character other than {Literal(node.Ch)} {DescribeLoop(node, analysis)}.", RegexNodeKind.One => $"Match {Literal(node.Ch)}{(rtl ? " backwards" : "")}.", RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy => $"Match {Literal(node.Ch)} {DescribeLoop(node, analysis)}.", RegexNodeKind.NegativeLookaround => $"Zero-width negative {(rtl ? "lookbehind" : "lookahead")}.", RegexNodeKind.Backreference => $"Match the same text as matched by the {DescribeCapture(node.M, analysis)}.", RegexNodeKind.PositiveLookaround => $"Zero-width positive {(rtl ? "lookbehind" : "lookahead")}.", RegexNodeKind.Set => $"Match {DescribeSet(node.Str!)}{(rtl ? " backwards" : "")}.", RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy => $"Match {DescribeSet(node.Str!)} {DescribeLoop(node, analysis)}.", RegexNodeKind.Start => "Match if at the start position.", RegexNodeKind.ExpressionConditional => $"Conditionally match one of two expressions depending on whether an initial expression matches.", RegexNodeKind.BackreferenceConditional => $"Conditionally match one of two expressions depending on whether the {DescribeCapture(node.M, analysis)} matched.", RegexNodeKind.UpdateBumpalong => $"Advance the next matching position.", _ => $"Unknown node type {node.Kind}", }; } /// <summary>Gets an identifer to describe a capture group.</summary> private static string DescribeCapture(int capNum, AnalysisResults analysis) { // If we can get a capture name from the captures collection and it's not just a numerical representation of the group, use it. string name = RegexParser.GroupNameFromNumber(analysis.RegexTree.CaptureNumberSparseMapping, analysis.RegexTree.CaptureNames, analysis.RegexTree.CaptureCount, capNum); if (!string.IsNullOrEmpty(name) && (!int.TryParse(name, out int id) || id != capNum)) { name = Literal(name); } else { // Otherwise, create a numerical description of the capture group. int tens = capNum % 10; name = tens is >= 1 and <= 3 && capNum % 100 is < 10 or > 20 ? // Ends in 1, 2, 3 but not 11, 12, or 13 tens switch { 1 => $"{capNum}st", 2 => $"{capNum}nd", _ => $"{capNum}rd", } : $"{capNum}th"; } return $"{name} capture group"; } /// <summary>Gets a textual description of what characters match a set.</summary> private static string DescribeSet(string charClass) => charClass switch { RegexCharClass.AnyClass => "any character", RegexCharClass.DigitClass => "a Unicode digit", RegexCharClass.ECMADigitClass => "'0' through '9'", RegexCharClass.ECMASpaceClass => "a whitespace character (ECMA)", RegexCharClass.ECMAWordClass => "a word character (ECMA)", RegexCharClass.NotDigitClass => "any character other than a Unicode digit", RegexCharClass.NotECMADigitClass => "any character other than '0' through '9'", RegexCharClass.NotECMASpaceClass => "any character other than a space character (ECMA)", RegexCharClass.NotECMAWordClass => "any character other than a word character (ECMA)", RegexCharClass.NotSpaceClass => "any character other than a space character", RegexCharClass.NotWordClass => "any character other than a word character", RegexCharClass.SpaceClass => "a whitespace character", RegexCharClass.WordClass => "a word character", _ => $"a character in the set {RegexCharClass.DescribeSet(charClass)}", }; /// <summary>Writes a textual description of the node tree fit for rending in source.</summary> /// <param name="writer">The writer to which the description should be written.</param> /// <param name="node">The node being written.</param> /// <param name="prefix">The prefix to write at the beginning of every line, including a "//" for a comment.</param> /// <param name="analyses">Analysis of the tree</param> /// <param name="depth">The depth of the current node.</param> private static void DescribeExpression(TextWriter writer, RegexNode node, string prefix, AnalysisResults analysis, int depth = 0) { bool skip = node.Kind switch { // For concatenations, flatten the contents into the parent, but only if the parent isn't a form of alternation, // where each branch is considered to be independent rather than a concatenation. RegexNodeKind.Concatenate when node.Parent is not { Kind: RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional } => true, // For atomic, skip the node if we'll instead render the atomic label as part of rendering the child. RegexNodeKind.Atomic when node.Child(0).Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop or RegexNodeKind.Alternate => true, // Don't skip anything else. _ => false, }; if (!skip) { string tag = node.Parent?.Kind switch { RegexNodeKind.ExpressionConditional when node.Parent.Child(0) == node => "Condition: ", RegexNodeKind.ExpressionConditional when node.Parent.Child(1) == node => "Matched: ", RegexNodeKind.ExpressionConditional when node.Parent.Child(2) == node => "Not Matched: ", RegexNodeKind.BackreferenceConditional when node.Parent.Child(0) == node => "Matched: ", RegexNodeKind.BackreferenceConditional when node.Parent.Child(1) == node => "Not Matched: ", _ => "", }; // Write out the line for the node. const char BulletPoint = '\u25CB'; writer.WriteLine($"{prefix}{new string(' ', depth * 4)}{BulletPoint} {tag}{DescribeNode(node, analysis)}"); } // Recur into each of its children. int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { int childDepth = skip ? depth : depth + 1; DescribeExpression(writer, node.Child(i), prefix, analysis, childDepth); } } /// <summary>Gets a textual description of a loop's style and bounds.</summary> private static string DescribeLoop(RegexNode node, AnalysisResults analysis) { string style = node.Kind switch { _ when node.M == node.N => "exactly", RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloopatomic => "atomically", RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop => "greedily", RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy => "lazily", RegexNodeKind.Loop => analysis.IsAtomicByAncestor(node) ? "greedily and atomically" : "greedily", _ /* RegexNodeKind.Lazyloop */ => analysis.IsAtomicByAncestor(node) ? "lazily and atomically" : "lazily", }; string bounds = node.M == node.N ? $" {node.M} times" : (node.M, node.N) switch { (0, int.MaxValue) => " any number of times", (1, int.MaxValue) => " at least once", (2, int.MaxValue) => " at least twice", (_, int.MaxValue) => $" at least {node.M} times", (0, 1) => ", optionally", (0, _) => $" at most {node.N} times", _ => $" at least {node.M} and at most {node.N} times" }; return style + bounds; } private static FinishEmitScope EmitScope(IndentedTextWriter writer, string title, bool faux = false) => EmitBlock(writer, $"// {title}", faux: faux); private static FinishEmitScope EmitBlock(IndentedTextWriter writer, string? clause, bool faux = false) { if (clause is not null) { writer.WriteLine(clause); } writer.WriteLine(faux ? "//{" : "{"); writer.Indent++; return new FinishEmitScope(writer, faux); } private static void EmitAdd(IndentedTextWriter writer, string variable, int value) { if (value == 0) { return; } writer.WriteLine( value == 1 ? $"{variable}++;" : value == -1 ? $"{variable}--;" : value > 0 ? $"{variable} += {value};" : value < 0 && value > int.MinValue ? $"{variable} -= {-value};" : $"{variable} += {value.ToString(CultureInfo.InvariantCulture)};"); } private readonly struct FinishEmitScope : IDisposable { private readonly IndentedTextWriter _writer; private readonly bool _faux; public FinishEmitScope(IndentedTextWriter writer, bool faux) { _writer = writer; _faux = faux; } public void Dispose() { if (_writer is not null) { _writer.Indent--; _writer.WriteLine(_faux ? "//}" : "}"); } } } /// <summary>Bit flags indicating which additional helpers should be emitted into the regex class.</summary> [Flags] private enum RequiredHelperFunctions { /// <summary>No additional functions are required.</summary> None = 0b0, /// <summary>The IsWordChar helper is required.</summary> IsWordChar = 0b1, /// <summary>The IsBoundary helper is required.</summary> IsBoundary = 0b10, /// <summary>The IsECMABoundary helper is required.</summary> IsECMABoundary = 0b100 } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; // NOTE: The logic in this file is largely a copy of logic in RegexCompiler, emitting C# instead of MSIL. // Most changes made to this file should be kept in sync, so far as bug fixes and relevant optimizations // are concerned. namespace System.Text.RegularExpressions.Generator { public partial class RegexGenerator { /// <summary>Code for a [GeneratedCode] attribute to put on the top-level generated members.</summary> private static readonly string s_generatedCodeAttribute = $"[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{typeof(RegexGenerator).Assembly.GetName().Name}\", \"{typeof(RegexGenerator).Assembly.GetName().Version}\")]"; /// <summary>Header comments and usings to include at the top of every generated file.</summary> private static readonly string[] s_headers = new string[] { "// <auto-generated/>", "#nullable enable", "#pragma warning disable CS0162 // Unreachable code", "#pragma warning disable CS0164 // Unreferenced label", "#pragma warning disable CS0219 // Variable assigned but never used", "", }; /// <summary>Generates the code for one regular expression class.</summary> private static (string, ImmutableArray<Diagnostic>) EmitRegexType(RegexType regexClass, bool allowUnsafe) { var sb = new StringBuilder(1024); var writer = new IndentedTextWriter(new StringWriter(sb)); // Emit the namespace if (!string.IsNullOrWhiteSpace(regexClass.Namespace)) { writer.WriteLine($"namespace {regexClass.Namespace}"); writer.WriteLine("{"); writer.Indent++; } // Emit containing types RegexType? parent = regexClass.ParentClass; var parentClasses = new Stack<string>(); while (parent is not null) { parentClasses.Push($"partial {parent.Keyword} {parent.Name}"); parent = parent.ParentClass; } while (parentClasses.Count != 0) { writer.WriteLine($"{parentClasses.Pop()}"); writer.WriteLine("{"); writer.Indent++; } // Emit the direct parent type writer.WriteLine($"partial {regexClass.Keyword} {regexClass.Name}"); writer.WriteLine("{"); writer.Indent++; // Generate a name to describe the regex instance. This includes the method name // the user provided and a non-randomized (for determinism) hash of it to try to make // the name that much harder to predict. Debug.Assert(regexClass.Method is not null); string generatedName = $"GeneratedRegex_{regexClass.Method.MethodName}_"; generatedName += ComputeStringHash(generatedName).ToString("X"); // Generate the regex type ImmutableArray<Diagnostic> diagnostics = EmitRegexMethod(writer, regexClass.Method, generatedName, allowUnsafe); while (writer.Indent != 0) { writer.Indent--; writer.WriteLine("}"); } writer.Flush(); return (sb.ToString(), diagnostics); // FNV-1a hash function. The actual algorithm used doesn't matter; just something simple // to create a deterministic, pseudo-random value that's based on input text. static uint ComputeStringHash(string s) { uint hashCode = 2166136261; foreach (char c in s) { hashCode = (c ^ hashCode) * 16777619; } return hashCode; } } /// <summary>Generates the code for a regular expression method.</summary> private static ImmutableArray<Diagnostic> EmitRegexMethod(IndentedTextWriter writer, RegexMethod rm, string id, bool allowUnsafe) { string patternExpression = Literal(rm.Pattern); string optionsExpression = Literal(rm.Options); string timeoutExpression = rm.MatchTimeout == Timeout.Infinite ? "global::System.Threading.Timeout.InfiniteTimeSpan" : $"global::System.TimeSpan.FromMilliseconds({rm.MatchTimeout.ToString(CultureInfo.InvariantCulture)})"; writer.WriteLine(s_generatedCodeAttribute); writer.WriteLine($"{rm.Modifiers} global::System.Text.RegularExpressions.Regex {rm.MethodName}() => {id}.Instance;"); writer.WriteLine(); writer.WriteLine(s_generatedCodeAttribute); writer.WriteLine("[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]"); writer.WriteLine($"{(writer.Indent != 0 ? "private" : "internal")} sealed class {id} : global::System.Text.RegularExpressions.Regex"); writer.WriteLine("{"); writer.Write(" public static global::System.Text.RegularExpressions.Regex Instance { get; } = "); // If we can't support custom generation for this regex, spit out a Regex constructor call. if (!rm.Tree.Root.SupportsCompilation(out string? reason)) { writer.WriteLine(); writer.WriteLine($" // Cannot generate Regex-derived implementation because {reason}."); writer.WriteLine($" new global::System.Text.RegularExpressions.Regex({patternExpression}, {optionsExpression}, {timeoutExpression});"); writer.WriteLine("}"); return ImmutableArray.Create(Diagnostic.Create(DiagnosticDescriptors.LimitedSourceGeneration, rm.MethodSyntax.GetLocation())); } AnalysisResults analysis = RegexTreeAnalyzer.Analyze(rm.Tree); writer.WriteLine($"new {id}();"); writer.WriteLine(); writer.WriteLine($" private {id}()"); writer.WriteLine($" {{"); writer.WriteLine($" base.pattern = {patternExpression};"); writer.WriteLine($" base.roptions = {optionsExpression};"); writer.WriteLine($" base.internalMatchTimeout = {timeoutExpression};"); writer.WriteLine($" base.factory = new RunnerFactory();"); if (rm.Tree.CaptureNumberSparseMapping is not null) { writer.Write(" base.Caps = new global::System.Collections.Hashtable {"); AppendHashtableContents(writer, rm.Tree.CaptureNumberSparseMapping); writer.WriteLine(" };"); } if (rm.Tree.CaptureNameToNumberMapping is not null) { writer.Write(" base.CapNames = new global::System.Collections.Hashtable {"); AppendHashtableContents(writer, rm.Tree.CaptureNameToNumberMapping); writer.WriteLine(" };"); } if (rm.Tree.CaptureNames is not null) { writer.Write(" base.capslist = new string[] {"); string separator = ""; foreach (string s in rm.Tree.CaptureNames) { writer.Write(separator); writer.Write(Literal(s)); separator = ", "; } writer.WriteLine(" };"); } writer.WriteLine($" base.capsize = {rm.Tree.CaptureCount};"); writer.WriteLine($" }}"); writer.WriteLine(" "); writer.WriteLine($" private sealed class RunnerFactory : global::System.Text.RegularExpressions.RegexRunnerFactory"); writer.WriteLine($" {{"); writer.WriteLine($" protected override global::System.Text.RegularExpressions.RegexRunner CreateInstance() => new Runner();"); writer.WriteLine(); writer.WriteLine($" private sealed class Runner : global::System.Text.RegularExpressions.RegexRunner"); writer.WriteLine($" {{"); // Main implementation methods writer.WriteLine(" // Description:"); DescribeExpression(writer, rm.Tree.Root.Child(0), " // ", analysis); // skip implicit root capture writer.WriteLine(); writer.WriteLine($" protected override void Scan(global::System.ReadOnlySpan<char> text)"); writer.WriteLine($" {{"); writer.Indent += 4; EmitScan(writer, rm, id); writer.Indent -= 4; writer.WriteLine($" }}"); writer.WriteLine(); writer.WriteLine($" private bool TryFindNextPossibleStartingPosition(global::System.ReadOnlySpan<char> inputSpan)"); writer.WriteLine($" {{"); writer.Indent += 4; RequiredHelperFunctions requiredHelpers = EmitTryFindNextPossibleStartingPosition(writer, rm, id); writer.Indent -= 4; writer.WriteLine($" }}"); writer.WriteLine(); if (allowUnsafe) { writer.WriteLine($" [global::System.Runtime.CompilerServices.SkipLocalsInit]"); } writer.WriteLine($" private bool TryMatchAtCurrentPosition(global::System.ReadOnlySpan<char> inputSpan)"); writer.WriteLine($" {{"); writer.Indent += 4; requiredHelpers |= EmitTryMatchAtCurrentPosition(writer, rm, id, analysis); writer.Indent -= 4; writer.WriteLine($" }}"); if ((requiredHelpers & RequiredHelperFunctions.IsWordChar) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character is part of the [\\w] set.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsWordChar(char ch)"); writer.WriteLine($" {{"); writer.WriteLine($" global::System.ReadOnlySpan<byte> ascii = new byte[]"); writer.WriteLine($" {{"); writer.WriteLine($" 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03,"); writer.WriteLine($" 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07"); writer.WriteLine($" }};"); writer.WriteLine(); writer.WriteLine($" int chDiv8 = ch >> 3;"); writer.WriteLine($" return (uint)chDiv8 < (uint)ascii.Length ?"); writer.WriteLine($" (ascii[chDiv8] & (1 << (ch & 0x7))) != 0 :"); writer.WriteLine($" global::System.Globalization.CharUnicodeInfo.GetUnicodeCategory(ch) switch"); writer.WriteLine($" {{"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.UppercaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.LowercaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.TitlecaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.ModifierLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.OtherLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.NonSpacingMark or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.DecimalDigitNumber or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.ConnectorPunctuation => true,"); writer.WriteLine($" _ => false,"); writer.WriteLine($" }};"); writer.WriteLine($" }}"); } if ((requiredHelpers & RequiredHelperFunctions.IsBoundary) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character at the specified index is a boundary.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsBoundary(global::System.ReadOnlySpan<char> inputSpan, int index)"); writer.WriteLine($" {{"); writer.WriteLine($" int indexM1 = index - 1;"); writer.WriteLine($" return ((uint)indexM1 < (uint)inputSpan.Length && IsBoundaryWordChar(inputSpan[indexM1])) !="); writer.WriteLine($" ((uint)index < (uint)inputSpan.Length && IsBoundaryWordChar(inputSpan[index]));"); writer.WriteLine(); writer.WriteLine($" static bool IsBoundaryWordChar(char ch) =>"); writer.WriteLine($" IsWordChar(ch) || (ch == '\\u200C' | ch == '\\u200D');"); writer.WriteLine($" }}"); } if ((requiredHelpers & RequiredHelperFunctions.IsECMABoundary) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character at the specified index is a boundary.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsECMABoundary(global::System.ReadOnlySpan<char> inputSpan, int index)"); writer.WriteLine($" {{"); writer.WriteLine($" int indexM1 = index - 1;"); writer.WriteLine($" return ((uint)indexM1 < (uint)inputSpan.Length && IsECMAWordChar(inputSpan[indexM1])) !="); writer.WriteLine($" ((uint)index < (uint)inputSpan.Length && IsECMAWordChar(inputSpan[index]));"); writer.WriteLine(); writer.WriteLine($" static bool IsECMAWordChar(char ch) =>"); writer.WriteLine($" ((((uint)ch - 'A') & ~0x20) < 26) || // ASCII letter"); writer.WriteLine($" (((uint)ch - '0') < 10) || // digit"); writer.WriteLine($" ch == '_' || // underscore"); writer.WriteLine($" ch == '\\u0130'; // latin capital letter I with dot above"); writer.WriteLine($" }}"); } writer.WriteLine($" }}"); writer.WriteLine($" }}"); writer.WriteLine("}"); return ImmutableArray<Diagnostic>.Empty; static void AppendHashtableContents(IndentedTextWriter writer, Hashtable ht) { IDictionaryEnumerator en = ht.GetEnumerator(); string separator = ""; while (en.MoveNext()) { writer.Write(separator); separator = ", "; writer.Write(" { "); if (en.Key is int key) { writer.Write(key); } else { writer.Write($"\"{en.Key}\""); } writer.Write($", {en.Value} }} "); } } } /// <summary>Emits the body of the Scan method override.</summary> private static void EmitScan(IndentedTextWriter writer, RegexMethod rm, string id) { bool rtl = (rm.Options & RegexOptions.RightToLeft) != 0; using (EmitBlock(writer, "while (TryFindNextPossibleStartingPosition(text))")) { if (rm.MatchTimeout != Timeout.Infinite) { writer.WriteLine("base.CheckTimeout();"); writer.WriteLine(); } writer.WriteLine("// If we find a match on the current position, or we have reached the end of the input, we are done."); using (EmitBlock(writer, $"if (TryMatchAtCurrentPosition(text) || base.runtextpos == {(!rtl ? "text.Length" : "0")})")) { writer.WriteLine("return;"); } writer.WriteLine(); writer.WriteLine($"base.runtextpos{(!rtl ? "++" : "--")};"); } } /// <summary>Emits the body of the TryFindNextPossibleStartingPosition.</summary> private static RequiredHelperFunctions EmitTryFindNextPossibleStartingPosition(IndentedTextWriter writer, RegexMethod rm, string id) { RegexOptions options = (RegexOptions)rm.Options; RegexTree regexTree = rm.Tree; bool hasTextInfo = false; RequiredHelperFunctions requiredHelpers = RequiredHelperFunctions.None; bool rtl = (options & RegexOptions.RightToLeft) != 0; // In some cases, we need to emit declarations at the beginning of the method, but we only discover we need them later. // To handle that, we build up a collection of all the declarations to include, track where they should be inserted, // and then insert them at that position once everything else has been output. var additionalDeclarations = new HashSet<string>(); // Emit locals initialization writer.WriteLine("int pos = base.runtextpos;"); writer.Flush(); int additionalDeclarationsPosition = ((StringWriter)writer.InnerWriter).GetStringBuilder().Length; int additionalDeclarationsIndent = writer.Indent; writer.WriteLine(); // Generate length check. If the input isn't long enough to possibly match, fail quickly. // It's rare for min required length to be 0, so we don't bother special-casing the check, // especially since we want the "return false" code regardless. int minRequiredLength = rm.Tree.FindOptimizations.MinRequiredLength; Debug.Assert(minRequiredLength >= 0); string clause = (minRequiredLength, rtl) switch { (0, false) => "if (pos <= inputSpan.Length)", (1, false) => "if (pos < inputSpan.Length)", (_, false) => $"if (pos <= inputSpan.Length - {minRequiredLength})", (0, true) => "if (pos >= 0)", (1, true) => "if (pos > 0)", (_, true) => $"if (pos >= {minRequiredLength})", }; using (EmitBlock(writer, clause)) { // Emit any anchors. if (!EmitAnchors()) { // Either anchors weren't specified, or they don't completely root all matches to a specific location. // If whatever search operation we need to perform entails case-insensitive operations // that weren't already handled via creation of sets, we need to get an store the // TextInfo object to use (unless RegexOptions.CultureInvariant was specified). EmitTextInfo(writer, ref hasTextInfo, rm); // Emit the code for whatever find mode has been determined. switch (regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_LeftToRight(regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_RightToLeft(regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: Debug.Assert(regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_LeftToRight(); break; case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive: Debug.Assert(regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_RightToLeft(); break; case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: Debug.Assert(regexTree.FindOptimizations.LiteralAfterLoop is not null); EmitLiteralAfterAtomicLoop(); break; default: Debug.Fail($"Unexpected mode: {regexTree.FindOptimizations.FindMode}"); goto case FindNextStartingPositionMode.NoSearch; case FindNextStartingPositionMode.NoSearch: writer.WriteLine("return true;"); break; } } } writer.WriteLine(); const string NoStartingPositionFound = "NoStartingPositionFound"; writer.WriteLine("// No starting position found"); writer.WriteLine($"{NoStartingPositionFound}:"); writer.WriteLine($"base.runtextpos = {(!rtl ? "inputSpan.Length" : "0")};"); writer.WriteLine("return false;"); // We're done. Patch up any additional declarations. ReplaceAdditionalDeclarations(writer, additionalDeclarations, additionalDeclarationsPosition, additionalDeclarationsIndent); return requiredHelpers; // Emit a goto for the specified label. void Goto(string label) => writer.WriteLine($"goto {label};"); // Emits any anchors. Returns true if the anchor roots any match to a specific location and thus no further // searching is required; otherwise, false. bool EmitAnchors() { // Anchors that fully implement TryFindNextPossibleStartingPosition, with a check that leads to immediate success or failure determination. switch (regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: writer.WriteLine("// Beginning \\A anchor"); using (EmitBlock(writer, "if (pos != 0)")) { // If we're not currently at the beginning, we'll never be, so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start: writer.WriteLine("// Start \\G anchor"); using (EmitBlock(writer, "if (pos != base.runtextstart)")) { // For both left-to-right and right-to-left, if we're not currently at the starting (because // we've already moved beyond it), then we'll never be, so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: writer.WriteLine("// Leading end \\Z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length - 1)")) { // If we're not currently at the end (or a newline just before it), skip ahead // since nothing until then can possibly match. writer.WriteLine("base.runtextpos = inputSpan.Length - 1;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: writer.WriteLine("// Leading end \\z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length)")) { // If we're not currently at the end (or a newline just before it), skip ahead // since nothing until then can possibly match. writer.WriteLine("base.runtextpos = inputSpan.Length;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning: writer.WriteLine("// Beginning \\A anchor"); using (EmitBlock(writer, "if (pos != 0)")) { // If we're not currently at the beginning, skip ahead (or, rather, backwards) // since nothing until then can possibly match. (We're iterating from the end // to the beginning in RightToLeft mode.) writer.WriteLine("base.runtextpos = 0;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ: writer.WriteLine("// Leading end \\Z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length - 1 || ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\\n'))")) { // If we're not currently at the end, we'll never be (we're iterating from end to beginning), // so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End: writer.WriteLine("// Leading end \\z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length)")) { // If we're not currently at the end, we'll never be (we're iterating from end to beginning), // so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: // Jump to the end, minus the min required length, which in this case is actually the fixed length, minus 1 (for a possible ending \n). writer.WriteLine("// Trailing end \\Z anchor with fixed-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength + 1})")) { writer.WriteLine($"base.runtextpos = inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength + 1};"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: // Jump to the end, minus the min required length, which in this case is actually the fixed length. writer.WriteLine("// Trailing end \\z anchor with fixed-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength})")) { writer.WriteLine($"base.runtextpos = inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength};"); } writer.WriteLine("return true;"); return true; } // Now handle anchors that boost the position but may not determine immediate success or failure. switch (regexTree.FindOptimizations.LeadingAnchor) { case RegexNodeKind.Bol: // Optimize the handling of a Beginning-Of-Line (BOL) anchor. BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any searches. writer.WriteLine("// Beginning-of-line anchor"); using (EmitBlock(writer, "if (pos > 0 && inputSpan[pos - 1] != '\\n')")) { writer.WriteLine("int newlinePos = global::System.MemoryExtensions.IndexOf(inputSpan.Slice(pos), '\\n');"); using (EmitBlock(writer, "if ((uint)newlinePos > inputSpan.Length - pos - 1)")) { Goto(NoStartingPositionFound); } writer.WriteLine("pos = newlinePos + pos + 1;"); // We've updated the position. Make sure there's still enough room in the input for a possible match. using (EmitBlock(writer, minRequiredLength switch { 0 => "if (pos > inputSpan.Length)", 1 => "if (pos >= inputSpan.Length)", _ => $"if (pos > inputSpan.Length - {minRequiredLength})" })) { Goto(NoStartingPositionFound); } } writer.WriteLine(); break; } switch (regexTree.FindOptimizations.TrailingAnchor) { case RegexNodeKind.End when regexTree.FindOptimizations.MaxPossibleLength is int maxLength: writer.WriteLine("// End \\z anchor with maximum-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {maxLength})")) { writer.WriteLine($"pos = inputSpan.Length - {maxLength};"); } writer.WriteLine(); break; case RegexNodeKind.EndZ when regexTree.FindOptimizations.MaxPossibleLength is int maxLength: writer.WriteLine("// End \\Z anchor with maximum-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {maxLength + 1})")) { writer.WriteLine($"pos = inputSpan.Length - {maxLength + 1};"); } writer.WriteLine(); break; } return false; } // Emits a case-sensitive prefix search for a string at the beginning of the pattern. void EmitIndexOf_LeftToRight(string prefix) { writer.WriteLine($"int i = global::System.MemoryExtensions.IndexOf(inputSpan.Slice(pos), {Literal(prefix)});"); writer.WriteLine("if (i >= 0)"); writer.WriteLine("{"); writer.WriteLine(" base.runtextpos = pos + i;"); writer.WriteLine(" return true;"); writer.WriteLine("}"); } // Emits a case-sensitive right-to-left prefix search for a string at the beginning of the pattern. void EmitIndexOf_RightToLeft(string prefix) { writer.WriteLine($"pos = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice(0, pos), {Literal(prefix)});"); writer.WriteLine("if (pos >= 0)"); writer.WriteLine("{"); writer.WriteLine($" base.runtextpos = pos + {prefix.Length};"); writer.WriteLine(" return true;"); writer.WriteLine("}"); } // Emits a search for a set at a fixed position from the start of the pattern, // and potentially other sets at other fixed positions in the pattern. void EmitFixedSet_LeftToRight() { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? sets = regexTree.FindOptimizations.FixedDistanceSets; (char[]? Chars, string Set, int Distance, bool CaseInsensitive) primarySet = sets![0]; const int MaxSets = 4; int setsToUse = Math.Min(sets.Count, MaxSets); // If we can use IndexOf{Any}, try to accelerate the skip loop via vectorization to match the first prefix. // We can use it if this is a case-sensitive class with a small number of characters in the class. int setIndex = 0; bool canUseIndexOf = !primarySet.CaseInsensitive && primarySet.Chars is not null; bool needLoop = !canUseIndexOf || setsToUse > 1; FinishEmitScope loopBlock = default; if (needLoop) { writer.WriteLine("global::System.ReadOnlySpan<char> span = inputSpan.Slice(pos);"); string upperBound = "span.Length" + (setsToUse > 1 || primarySet.Distance != 0 ? $" - {minRequiredLength - 1}" : ""); loopBlock = EmitBlock(writer, $"for (int i = 0; i < {upperBound}; i++)"); } if (canUseIndexOf) { string span = needLoop ? "span" : "inputSpan.Slice(pos)"; span = (needLoop, primarySet.Distance) switch { (false, 0) => span, (true, 0) => $"{span}.Slice(i)", (false, _) => $"{span}.Slice({primarySet.Distance})", (true, _) => $"{span}.Slice(i + {primarySet.Distance})", }; string indexOf = primarySet.Chars!.Length switch { 1 => $"global::System.MemoryExtensions.IndexOf({span}, {Literal(primarySet.Chars[0])})", 2 => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(primarySet.Chars[0])}, {Literal(primarySet.Chars[1])})", 3 => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(primarySet.Chars[0])}, {Literal(primarySet.Chars[1])}, {Literal(primarySet.Chars[2])})", _ => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(new string(primarySet.Chars))})", }; if (needLoop) { writer.WriteLine($"int indexOfPos = {indexOf};"); using (EmitBlock(writer, "if (indexOfPos < 0)")) { Goto(NoStartingPositionFound); } writer.WriteLine("i += indexOfPos;"); writer.WriteLine(); if (setsToUse > 1) { using (EmitBlock(writer, $"if (i >= span.Length - {minRequiredLength - 1})")) { Goto(NoStartingPositionFound); } writer.WriteLine(); } } else { writer.WriteLine($"int i = {indexOf};"); using (EmitBlock(writer, "if (i >= 0)")) { writer.WriteLine("base.runtextpos = pos + i;"); writer.WriteLine("return true;"); } } setIndex = 1; } if (needLoop) { Debug.Assert(setIndex == 0 || setIndex == 1); bool hasCharClassConditions = false; if (setIndex < setsToUse) { // if (CharInClass(textSpan[i + charClassIndex], prefix[0], "...") && // ...) Debug.Assert(needLoop); int start = setIndex; for (; setIndex < setsToUse; setIndex++) { string spanIndex = $"span[i{(sets[setIndex].Distance > 0 ? $" + {sets[setIndex].Distance}" : "")}]"; string charInClassExpr = MatchCharacterClass(hasTextInfo, options, spanIndex, sets[setIndex].Set, sets[setIndex].CaseInsensitive, negate: false, additionalDeclarations, ref requiredHelpers); if (setIndex == start) { writer.Write($"if ({charInClassExpr}"); } else { writer.WriteLine(" &&"); writer.Write($" {charInClassExpr}"); } } writer.WriteLine(")"); hasCharClassConditions = true; } using (hasCharClassConditions ? EmitBlock(writer, null) : default) { writer.WriteLine("base.runtextpos = pos + i;"); writer.WriteLine("return true;"); } } loopBlock.Dispose(); } // Emits a right-to-left search for a set at a fixed position from the start of the pattern. // (Currently that position will always be a distance of 0, meaning the start of the pattern itself.) void EmitFixedSet_RightToLeft() { (char[]? Chars, string Set, int Distance, bool CaseInsensitive) set = regexTree.FindOptimizations.FixedDistanceSets![0]; Debug.Assert(set.Distance == 0); if (set.Chars is { Length: 1 } && !set.CaseInsensitive) { writer.WriteLine($"pos = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice(0, pos), {Literal(set.Chars[0])});"); writer.WriteLine("if (pos >= 0)"); writer.WriteLine("{"); writer.WriteLine(" base.runtextpos = pos + 1;"); writer.WriteLine(" return true;"); writer.WriteLine("}"); } else { using (EmitBlock(writer, "while ((uint)--pos < (uint)inputSpan.Length)")) { using (EmitBlock(writer, $"if ({MatchCharacterClass(hasTextInfo, options, "inputSpan[pos]", set.Set, set.CaseInsensitive, negate: false, additionalDeclarations, ref requiredHelpers)})")) { writer.WriteLine("base.runtextpos = pos + 1;"); writer.WriteLine("return true;"); } } } } // Emits a search for a literal following a leading atomic single-character loop. void EmitLiteralAfterAtomicLoop() { Debug.Assert(regexTree.FindOptimizations.LiteralAfterLoop is not null); (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = regexTree.FindOptimizations.LiteralAfterLoop.Value; Debug.Assert(target.LoopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(target.LoopNode.N == int.MaxValue); using (EmitBlock(writer, "while (true)")) { writer.WriteLine($"global::System.ReadOnlySpan<char> slice = inputSpan.Slice(pos);"); writer.WriteLine(); // Find the literal. If we can't find it, we're done searching. writer.Write("int i = global::System.MemoryExtensions."); writer.WriteLine( target.Literal.String is string literalString ? $"IndexOf(slice, {Literal(literalString)});" : target.Literal.Chars is not char[] literalChars ? $"IndexOf(slice, {Literal(target.Literal.Char)});" : literalChars.Length switch { 2 => $"IndexOfAny(slice, {Literal(literalChars[0])}, {Literal(literalChars[1])});", 3 => $"IndexOfAny(slice, {Literal(literalChars[0])}, {Literal(literalChars[1])}, {Literal(literalChars[2])});", _ => $"IndexOfAny(slice, {Literal(new string(literalChars))});", }); using (EmitBlock(writer, $"if (i < 0)")) { writer.WriteLine("break;"); } writer.WriteLine(); // We found the literal. Walk backwards from it finding as many matches as we can against the loop. writer.WriteLine("int prev = i;"); writer.WriteLine($"while ((uint)--prev < (uint)slice.Length && {MatchCharacterClass(hasTextInfo, options, "slice[prev]", target.LoopNode.Str!, caseInsensitive: false, negate: false, additionalDeclarations, ref requiredHelpers)});"); if (target.LoopNode.M > 0) { // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. writer.WriteLine($"if ((i - prev - 1) < {target.LoopNode.M})"); writer.WriteLine("{"); writer.WriteLine(" pos += i + 1;"); writer.WriteLine(" continue;"); writer.WriteLine("}"); } writer.WriteLine(); // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate i as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. writer.WriteLine("base.runtextpos = pos + prev + 1;"); writer.WriteLine("return true;"); } } // If a TextInfo is needed to perform ToLower operations, emits a local initialized to the TextInfo to use. static void EmitTextInfo(IndentedTextWriter writer, ref bool hasTextInfo, RegexMethod rm) { // Emit local to store current culture if needed if ((rm.Options & RegexOptions.CultureInvariant) == 0) { bool needsCulture = rm.Tree.FindOptimizations.FindMode switch { FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive => true, _ when rm.Tree.FindOptimizations.FixedDistanceSets is List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets => sets.Exists(set => set.CaseInsensitive), _ => false, }; if (needsCulture) { hasTextInfo = true; writer.WriteLine("global::System.Globalization.TextInfo textInfo = global::System.Globalization.CultureInfo.CurrentCulture.TextInfo;"); } } } } /// <summary>Emits the body of the TryMatchAtCurrentPosition.</summary> private static RequiredHelperFunctions EmitTryMatchAtCurrentPosition(IndentedTextWriter writer, RegexMethod rm, string id, AnalysisResults analysis) { // In .NET Framework and up through .NET Core 3.1, the code generated for RegexOptions.Compiled was effectively an unrolled // version of what RegexInterpreter would process. The RegexNode tree would be turned into a series of opcodes via // RegexWriter; the interpreter would then sit in a loop processing those opcodes, and the RegexCompiler iterated through the // opcodes generating code for each equivalent to what the interpreter would do albeit with some decisions made at compile-time // rather than at run-time. This approach, however, lead to complicated code that wasn't pay-for-play (e.g. a big backtracking // jump table that all compilations went through even if there was no backtracking), that didn't factor in the shape of the // tree (e.g. it's difficult to add optimizations based on interactions between nodes in the graph), and that didn't read well // when decompiled from IL to C# or when directly emitted as C# as part of a source generator. // // This implementation is instead based on directly walking the RegexNode tree and outputting code for each node in the graph. // A dedicated for each kind of RegexNode emits the code necessary to handle that node's processing, including recursively // calling the relevant function for any of its children nodes. Backtracking is handled not via a giant jump table, but instead // by emitting direct jumps to each backtracking construct. This is achieved by having all match failures jump to a "done" // label that can be changed by a previous emitter, e.g. before EmitLoop returns, it ensures that "doneLabel" is set to the // label that code should jump back to when backtracking. That way, a subsequent EmitXx function doesn't need to know exactly // where to jump: it simply always jumps to "doneLabel" on match failure, and "doneLabel" is always configured to point to // the right location. In an expression without backtracking, or before any backtracking constructs have been encountered, // "doneLabel" is simply the final return location from the TryMatchAtCurrentPosition method that will undo any captures and exit, signaling to // the calling scan loop that nothing was matched. // Arbitrary limit for unrolling vs creating a loop. We want to balance size in the generated // code with other costs, like the (small) overhead of slicing to create the temp span to iterate. const int MaxUnrollSize = 16; RegexOptions options = (RegexOptions)rm.Options; RegexTree regexTree = rm.Tree; RequiredHelperFunctions requiredHelpers = RequiredHelperFunctions.None; // Helper to define names. Names start unadorned, but as soon as there's repetition, // they begin to have a numbered suffix. var usedNames = new Dictionary<string, int>(); // Every RegexTree is rooted in the implicit Capture for the whole expression. // Skip the Capture node. We handle the implicit root capture specially. RegexNode node = regexTree.Root; Debug.Assert(node.Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); Debug.Assert(node.ChildCount() == 1, "Capture nodes should have one child"); node = node.Child(0); // In some limited cases, TryFindNextPossibleStartingPosition will only return true if it successfully matched the whole expression. // We can special case these to do essentially nothing in TryMatchAtCurrentPosition other than emit the capture. switch (node.Kind) { case RegexNodeKind.Multi or RegexNodeKind.Notone or RegexNodeKind.One or RegexNodeKind.Set when !IsCaseInsensitive(node): // This is the case for single and multiple characters, though the whole thing is only guaranteed // to have been validated in TryFindNextPossibleStartingPosition when doing case-sensitive comparison. writer.WriteLine($"int start = base.runtextpos;"); writer.WriteLine($"int end = start {((node.Options & RegexOptions.RightToLeft) == 0 ? "+" : "-")} {(node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1)};"); writer.WriteLine("base.Capture(0, start, end);"); writer.WriteLine("base.runtextpos = end;"); writer.WriteLine("return true;"); return requiredHelpers; case RegexNodeKind.Empty: // This case isn't common in production, but it's very common when first getting started with the // source generator and seeing what happens as you add more to expressions. When approaching // it from a learning perspective, this is very common, as it's the empty string you start with. writer.WriteLine("base.Capture(0, base.runtextpos, base.runtextpos);"); writer.WriteLine("return true;"); return requiredHelpers; } // In some cases, we need to emit declarations at the beginning of the method, but we only discover we need them later. // To handle that, we build up a collection of all the declarations to include, track where they should be inserted, // and then insert them at that position once everything else has been output. var additionalDeclarations = new HashSet<string>(); var additionalLocalFunctions = new Dictionary<string, string[]>(); // Declare some locals. string sliceSpan = "slice"; writer.WriteLine("int pos = base.runtextpos;"); writer.WriteLine($"int original_pos = pos;"); bool hasTimeout = EmitLoopTimeoutCounterIfNeeded(writer, rm); bool hasTextInfo = EmitInitializeCultureForTryMatchAtCurrentPositionIfNecessary(writer, rm, analysis); writer.Flush(); int additionalDeclarationsPosition = ((StringWriter)writer.InnerWriter).GetStringBuilder().Length; int additionalDeclarationsIndent = writer.Indent; // The implementation tries to use const indexes into the span wherever possible, which we can do // for all fixed-length constructs. In such cases (e.g. single chars, repeaters, strings, etc.) // we know at any point in the regex exactly how far into it we are, and we can use that to index // into the span created at the beginning of the routine to begin at exactly where we're starting // in the input. When we encounter a variable-length construct, we transfer the static value to // pos, slicing the inputSpan appropriately, and then zero out the static position. int sliceStaticPos = 0; SliceInputSpan(writer, defineLocal: true); writer.WriteLine(); // doneLabel starts out as the top-level label for the whole expression failing to match. However, // it may be changed by the processing of a node to point to whereever subsequent match failures // should jump to, in support of backtracking or other constructs. For example, before emitting // the code for a branch N, an alternation will set the the doneLabel to point to the label for // processing the next branch N+1: that way, any failures in the branch N's processing will // implicitly end up jumping to the right location without needing to know in what context it's used. string doneLabel = ReserveName("NoMatch"); string topLevelDoneLabel = doneLabel; // Check whether there are captures anywhere in the expression. If there isn't, we can skip all // the boilerplate logic around uncapturing, as there won't be anything to uncapture. bool expressionHasCaptures = analysis.MayContainCapture(node); // Emit the code for all nodes in the tree. EmitNode(node); // If we fall through to this place in the code, we've successfully matched the expression. writer.WriteLine(); writer.WriteLine("// The input matched."); if (sliceStaticPos > 0) { EmitAdd(writer, "pos", sliceStaticPos); // TransferSliceStaticPosToPos would also slice, which isn't needed here } writer.WriteLine("base.runtextpos = pos;"); writer.WriteLine("base.Capture(0, original_pos, pos);"); writer.WriteLine("return true;"); // We're done with the match. // Patch up any additional declarations. ReplaceAdditionalDeclarations(writer, additionalDeclarations, additionalDeclarationsPosition, additionalDeclarationsIndent); // And emit any required helpers. if (additionalLocalFunctions.Count != 0) { foreach (KeyValuePair<string, string[]> localFunctions in additionalLocalFunctions.OrderBy(k => k.Key)) { writer.WriteLine(); foreach (string line in localFunctions.Value) { writer.WriteLine(line); } } } return requiredHelpers; // Helper to create a name guaranteed to be unique within the function. string ReserveName(string prefix) { usedNames.TryGetValue(prefix, out int count); usedNames[prefix] = count + 1; return count == 0 ? prefix : $"{prefix}{count}"; } // Helper to emit a label. As of C# 10, labels aren't statements of their own and need to adorn a following statement; // if a label appears just before a closing brace, then, it's a compilation error. To avoid issues there, this by // default implements a blank statement (a semicolon) after each label, but individual uses can opt-out of the semicolon // when it's known the label will always be followed by a statement. void MarkLabel(string label, bool emitSemicolon = true) => writer.WriteLine($"{label}:{(emitSemicolon ? ";" : "")}"); // Emits a goto to jump to the specified label. However, if the specified label is the top-level done label indicating // that the entire match has failed, we instead emit our epilogue, uncapturing if necessary and returning out of TryMatchAtCurrentPosition. void Goto(string label) { if (label == topLevelDoneLabel) { // We only get here in the code if the whole expression fails to match and jumps to // the original value of doneLabel. if (expressionHasCaptures) { EmitUncaptureUntil("0"); } writer.WriteLine("return false; // The input didn't match."); } else { writer.WriteLine($"goto {label};"); } } // Emits a case or default line followed by an indented body. void CaseGoto(string clause, string label) { writer.WriteLine(clause); writer.Indent++; Goto(label); writer.Indent--; } // Whether the node has RegexOptions.IgnoreCase set. // TODO: https://github.com/dotnet/runtime/issues/61048. We should be able to delete this and all usage sites once // IgnoreCase is erradicated from the tree. The only place it should possibly be left after that work is in a Backreference, // and that can do this check directly as needed. static bool IsCaseInsensitive(RegexNode node) => (node.Options & RegexOptions.IgnoreCase) != 0; // Slices the inputSpan starting at pos until end and stores it into slice. void SliceInputSpan(IndentedTextWriter writer, bool defineLocal = false) { if (defineLocal) { writer.Write("global::System.ReadOnlySpan<char> "); } writer.WriteLine($"{sliceSpan} = inputSpan.Slice(pos);"); } // Emits the sum of a constant and a value from a local. string Sum(int constant, string? local = null) => local is null ? constant.ToString(CultureInfo.InvariantCulture) : constant == 0 ? local : $"{constant} + {local}"; // Emits a check that the span is large enough at the currently known static position to handle the required additional length. void EmitSpanLengthCheck(int requiredLength, string? dynamicRequiredLength = null) { Debug.Assert(requiredLength > 0); using (EmitBlock(writer, $"if ({SpanLengthCheck(requiredLength, dynamicRequiredLength)})")) { Goto(doneLabel); } } // Returns a length check for the current span slice. The check returns true if // the span isn't long enough for the specified length. string SpanLengthCheck(int requiredLength, string? dynamicRequiredLength = null) => dynamicRequiredLength is null && sliceStaticPos + requiredLength == 1 ? $"{sliceSpan}.IsEmpty" : $"(uint){sliceSpan}.Length < {Sum(sliceStaticPos + requiredLength, dynamicRequiredLength)}"; // Adds the value of sliceStaticPos into the pos local, slices slice by the corresponding amount, // and zeros out sliceStaticPos. void TransferSliceStaticPosToPos(bool forceSliceReload = false) { if (sliceStaticPos > 0) { EmitAdd(writer, "pos", sliceStaticPos); sliceStaticPos = 0; SliceInputSpan(writer); } else if (forceSliceReload) { SliceInputSpan(writer); } } // Emits the code for an alternation. void EmitAlternation(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Alternate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); int childCount = node.ChildCount(); Debug.Assert(childCount >= 2); string originalDoneLabel = doneLabel; // Both atomic and non-atomic are supported. While a parent RegexNode.Atomic node will itself // successfully prevent backtracking into this child node, we can emit better / cheaper code // for an Alternate when it is atomic, so we still take it into account here. Debug.Assert(node.Parent is not null); bool isAtomic = analysis.IsAtomicByAncestor(node); // If no child branch overlaps with another child branch, we can emit more streamlined code // that avoids checking unnecessary branches, e.g. with abc|def|ghi if the next character in // the input is 'a', we needn't try the def or ghi branches. A simple, relatively common case // of this is if every branch begins with a specific, unique character, in which case // the whole alternation can be treated as a simple switch, so we special-case that. However, // we can't goto _into_ switch cases, which means we can't use this approach if there's any // possibility of backtracking into the alternation. bool useSwitchedBranches = false; if ((node.Options & RegexOptions.RightToLeft) == 0) { useSwitchedBranches = isAtomic; if (!useSwitchedBranches) { useSwitchedBranches = true; for (int i = 0; i < childCount; i++) { if (analysis.MayBacktrack(node.Child(i))) { useSwitchedBranches = false; break; } } } } // Detect whether every branch begins with one or more unique characters. const int SetCharsSize = 5; // arbitrary limit (for IgnoreCase, we want this to be at least 3 to handle the vast majority of values) Span<char> setChars = stackalloc char[SetCharsSize]; if (useSwitchedBranches) { // Iterate through every branch, seeing if we can easily find a starting One, Multi, or small Set. // If we can, extract its starting char (or multiple in the case of a set), validate that all such // starting characters are unique relative to all the branches. var seenChars = new HashSet<char>(); for (int i = 0; i < childCount && useSwitchedBranches; i++) { // If it's not a One, Multi, or Set, we can't apply this optimization. // If it's IgnoreCase (and wasn't reduced to a non-IgnoreCase set), also ignore it to keep the logic simple. if (node.Child(i).FindBranchOneMultiOrSetStart() is not RegexNode oneMultiOrSet || IsCaseInsensitive(oneMultiOrSet)) { useSwitchedBranches = false; break; } // If it's a One or a Multi, get the first character and add it to the set. // If it was already in the set, we can't apply this optimization. if (oneMultiOrSet.Kind is RegexNodeKind.One or RegexNodeKind.Multi) { if (!seenChars.Add(oneMultiOrSet.FirstCharOfOneOrMulti())) { useSwitchedBranches = false; break; } } else { // The branch begins with a set. Make sure it's a set of only a few characters // and get them. If we can't, we can't apply this optimization. Debug.Assert(oneMultiOrSet.Kind is RegexNodeKind.Set); int numChars; if (RegexCharClass.IsNegated(oneMultiOrSet.Str!) || (numChars = RegexCharClass.GetSetChars(oneMultiOrSet.Str!, setChars)) == 0) { useSwitchedBranches = false; break; } // Check to make sure each of the chars is unique relative to all other branches examined. foreach (char c in setChars.Slice(0, numChars)) { if (!seenChars.Add(c)) { useSwitchedBranches = false; break; } } } } } if (useSwitchedBranches) { // Note: This optimization does not exist with RegexOptions.Compiled. Here we rely on the // C# compiler to lower the C# switch statement with appropriate optimizations. In some // cases there are enough branches that the compiler will emit a jump table. In others // it'll optimize the order of checks in order to minimize the total number in the worst // case. In any case, we get easier to read and reason about C#. EmitSwitchedBranches(); } else { EmitAllBranches(); } return; // Emits the code for a switch-based alternation of non-overlapping branches. void EmitSwitchedBranches() { // We need at least 1 remaining character in the span, for the char to switch on. EmitSpanLengthCheck(1); writer.WriteLine(); // Emit a switch statement on the first char of each branch. using (EmitBlock(writer, $"switch ({sliceSpan}[{sliceStaticPos++}])")) { Span<char> setChars = stackalloc char[SetCharsSize]; // needs to be same size as detection check in caller int startingSliceStaticPos = sliceStaticPos; // Emit a case for each branch. for (int i = 0; i < childCount; i++) { sliceStaticPos = startingSliceStaticPos; RegexNode child = node.Child(i); Debug.Assert(child.Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set or RegexNodeKind.Concatenate, DescribeNode(child, analysis)); Debug.Assert(child.Kind is not RegexNodeKind.Concatenate || (child.ChildCount() >= 2 && child.Child(0).Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set)); RegexNode? childStart = child.FindBranchOneMultiOrSetStart(); Debug.Assert(childStart is not null, "Unexpectedly couldn't find the branch starting node."); Debug.Assert(!IsCaseInsensitive(childStart), "Expected only to find non-IgnoreCase branch starts"); if (childStart.Kind is RegexNodeKind.Set) { int numChars = RegexCharClass.GetSetChars(childStart.Str!, setChars); Debug.Assert(numChars != 0); writer.WriteLine($"case {string.Join(" or ", setChars.Slice(0, numChars).ToArray().Select(c => Literal(c)))}:"); } else { writer.WriteLine($"case {Literal(childStart.FirstCharOfOneOrMulti())}:"); } writer.Indent++; // Emit the code for the branch, without the first character that was already matched in the switch. switch (child.Kind) { case RegexNodeKind.Multi: EmitNode(CloneMultiWithoutFirstChar(child)); writer.WriteLine(); break; case RegexNodeKind.Concatenate: var newConcat = new RegexNode(RegexNodeKind.Concatenate, child.Options); if (childStart.Kind == RegexNodeKind.Multi) { newConcat.AddChild(CloneMultiWithoutFirstChar(childStart)); } int concatChildCount = child.ChildCount(); for (int j = 1; j < concatChildCount; j++) { newConcat.AddChild(child.Child(j)); } EmitNode(newConcat.Reduce()); writer.WriteLine(); break; static RegexNode CloneMultiWithoutFirstChar(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Multi); Debug.Assert(node.Str!.Length >= 2); return node.Str!.Length == 2 ? new RegexNode(RegexNodeKind.One, node.Options, node.Str![1]) : new RegexNode(RegexNodeKind.Multi, node.Options, node.Str!.Substring(1)); } } // This is only ever used for atomic alternations, so we can simply reset the doneLabel // after emitting the child, as nothing will backtrack here (and we need to reset it // so that all branches see the original). doneLabel = originalDoneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. TransferSliceStaticPosToPos(); writer.WriteLine($"break;"); writer.WriteLine(); writer.Indent--; } // Default branch if the character didn't match the start of any branches. CaseGoto("default:", doneLabel); } } void EmitAllBranches() { // Label to jump to when any branch completes successfully. string matchLabel = ReserveName("AlternationMatch"); // Save off pos. We'll need to reset this each time a branch fails. string startingPos = ReserveName("alternation_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); int startingSliceStaticPos = sliceStaticPos; // We need to be able to undo captures in two situations: // - If a branch of the alternation itself contains captures, then if that branch // fails to match, any captures from that branch until that failure point need to // be uncaptured prior to jumping to the next branch. // - If the expression after the alternation contains captures, then failures // to match in those expressions could trigger backtracking back into the // alternation, and thus we need uncapture any of them. // As such, if the alternation contains captures or if it's not atomic, we need // to grab the current crawl position so we can unwind back to it when necessary. // We can do all of the uncapturing as part of falling through to the next branch. // If we fail in a branch, then such uncapturing will unwind back to the position // at the start of the alternation. If we fail after the alternation, and the // matched branch didn't contain any backtracking, then the failure will end up // jumping to the next branch, which will unwind the captures. And if we fail after // the alternation and the matched branch did contain backtracking, that backtracking // construct is responsible for unwinding back to its starting crawl position. If // it eventually ends up failing, that failure will result in jumping to the next branch // of the alternation, which will again dutifully unwind the remaining captures until // what they were at the start of the alternation. Of course, if there are no captures // anywhere in the regex, we don't have to do any of that. string? startingCapturePos = null; if (expressionHasCaptures && (analysis.MayContainCapture(node) || !isAtomic)) { startingCapturePos = ReserveName("alternation_starting_capturepos"); writer.WriteLine($"int {startingCapturePos} = base.Crawlpos();"); } writer.WriteLine(); // After executing the alternation, subsequent matching may fail, at which point execution // will need to backtrack to the alternation. We emit a branching table at the end of the // alternation, with a label that will be left as the "doneLabel" upon exiting emitting the // alternation. The branch table is populated with an entry for each branch of the alternation, // containing either the label for the last backtracking construct in the branch if such a construct // existed (in which case the doneLabel upon emitting that node will be different from before it) // or the label for the next branch. var labelMap = new string[childCount]; string backtrackLabel = ReserveName("AlternationBacktrack"); for (int i = 0; i < childCount; i++) { // If the alternation isn't atomic, backtracking may require our jump table jumping back // into these branches, so we can't use actual scopes, as that would hide the labels. using (EmitScope(writer, $"Branch {i}", faux: !isAtomic)) { bool isLastBranch = i == childCount - 1; string? nextBranch = null; if (!isLastBranch) { // Failure to match any branch other than the last one should result // in jumping to process the next branch. nextBranch = ReserveName("AlternationBranch"); doneLabel = nextBranch; } else { // Failure to match the last branch is equivalent to failing to match // the whole alternation, which means those failures should jump to // what "doneLabel" was defined as when starting the alternation. doneLabel = originalDoneLabel; } // Emit the code for each branch. EmitNode(node.Child(i)); writer.WriteLine(); // Add this branch to the backtracking table. At this point, either the child // had backtracking constructs, in which case doneLabel points to the last one // and that's where we'll want to jump to, or it doesn't, in which case doneLabel // still points to the nextBranch, which similarly is where we'll want to jump to. if (!isAtomic) { EmitStackPush(startingCapturePos is not null ? new[] { i.ToString(), startingPos, startingCapturePos } : new[] { i.ToString(), startingPos }); } labelMap[i] = doneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. TransferSliceStaticPosToPos(); if (!isLastBranch || !isAtomic) { // If this isn't the last branch, we're about to output a reset section, // and if this isn't atomic, there will be a backtracking section before // the end of the method. In both of those cases, we've successfully // matched and need to skip over that code. If, however, this is the // last branch and this is an atomic alternation, we can just fall // through to the successfully matched location. Goto(matchLabel); } // Reset state for next branch and loop around to generate it. This includes // setting pos back to what it was at the beginning of the alternation, // updating slice to be the full length it was, and if there's a capture that // needs to be reset, uncapturing it. if (!isLastBranch) { writer.WriteLine(); MarkLabel(nextBranch!, emitSemicolon: false); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } } } writer.WriteLine(); } // We should never fall through to this location in the generated code. Either // a branch succeeded in matching and jumped to the end, or a branch failed in // matching and jumped to the next branch location. We only get to this code // if backtracking occurs and the code explicitly jumps here based on our setting // "doneLabel" to the label for this section. Thus, we only need to emit it if // something can backtrack to us, which can't happen if we're inside of an atomic // node. Thus, emit the backtracking section only if we're non-atomic. if (isAtomic) { doneLabel = originalDoneLabel; } else { doneLabel = backtrackLabel; MarkLabel(backtrackLabel, emitSemicolon: false); EmitStackPop(startingCapturePos is not null ? new[] { startingCapturePos, startingPos } : new[] { startingPos}); using (EmitBlock(writer, $"switch ({StackPop()})")) { for (int i = 0; i < labelMap.Length; i++) { CaseGoto($"case {i}:", labelMap[i]); } } writer.WriteLine(); } // Successfully completed the alternate. MarkLabel(matchLabel); Debug.Assert(sliceStaticPos == 0); } } // Emits the code to handle a backreference. void EmitBackreference(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Backreference, $"Unexpected type: {node.Kind}"); int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); if (sliceStaticPos > 0) { TransferSliceStaticPosToPos(); writer.WriteLine(); } // If the specified capture hasn't yet captured anything, fail to match... except when using RegexOptions.ECMAScript, // in which case per ECMA 262 section 21.2.2.9 the backreference should succeed. if ((node.Options & RegexOptions.ECMAScript) != 0) { writer.WriteLine($"// If the {DescribeCapture(node.M, analysis)} hasn't matched, the backreference matches with RegexOptions.ECMAScript rules."); using (EmitBlock(writer, $"if (base.IsMatched({capnum}))")) { EmitWhenHasCapture(); } } else { writer.WriteLine($"// If the {DescribeCapture(node.M, analysis)} hasn't matched, the backreference doesn't match."); using (EmitBlock(writer, $"if (!base.IsMatched({capnum}))")) { Goto(doneLabel); } writer.WriteLine(); EmitWhenHasCapture(); } void EmitWhenHasCapture() { writer.WriteLine("// Get the captured text. If it doesn't match at the current position, the backreference doesn't match."); additionalDeclarations.Add("int matchLength = 0;"); writer.WriteLine($"matchLength = base.MatchLength({capnum});"); bool caseInsensitive = IsCaseInsensitive(node); if ((node.Options & RegexOptions.RightToLeft) == 0) { if (!caseInsensitive) { // If we're case-sensitive, we can simply validate that the remaining length of the slice is sufficient // to possibly match, and then do a SequenceEqual against the matched text. writer.WriteLine($"if ({sliceSpan}.Length < matchLength || "); using (EmitBlock(writer, $" !global::System.MemoryExtensions.SequenceEqual(inputSpan.Slice(base.MatchIndex({capnum}), matchLength), {sliceSpan}.Slice(0, matchLength)))")) { Goto(doneLabel); } } else { // For case-insensitive, we have to walk each character individually. using (EmitBlock(writer, $"if ({sliceSpan}.Length < matchLength)")) { Goto(doneLabel); } writer.WriteLine(); additionalDeclarations.Add("int matchIndex = 0;"); writer.WriteLine($"matchIndex = base.MatchIndex({capnum});"); using (EmitBlock(writer, $"for (int i = 0; i < matchLength; i++)")) { using (EmitBlock(writer, $"if ({ToLower(hasTextInfo, options, $"inputSpan[matchIndex + i]")} != {ToLower(hasTextInfo, options, $"{sliceSpan}[i]")})")) { Goto(doneLabel); } } } writer.WriteLine(); writer.WriteLine($"pos += matchLength;"); SliceInputSpan(writer); } else { using (EmitBlock(writer, $"if (pos < matchLength)")) { Goto(doneLabel); } writer.WriteLine(); additionalDeclarations.Add("int matchIndex = 0;"); writer.WriteLine($"matchIndex = base.MatchIndex({capnum});"); using (EmitBlock(writer, $"for (int i = 0; i < matchLength; i++)")) { using (EmitBlock(writer, $"if ({ToLowerIfNeeded(hasTextInfo, options, $"inputSpan[matchIndex + i]", caseInsensitive)} != {ToLowerIfNeeded(hasTextInfo, options, $"inputSpan[pos - matchLength + i]", caseInsensitive)})")) { Goto(doneLabel); } } writer.WriteLine(); writer.WriteLine($"pos -= matchLength;"); } } } // Emits the code for an if(backreference)-then-else conditional. void EmitBackreferenceConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.BackreferenceConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 2, $"Expected 2 children, found {node.ChildCount()}"); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // Get the capture number to test. int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(0); RegexNode? noBranch = node.Child(1) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; string originalDoneLabel = doneLabel; // If the child branches might backtrack, we can't emit the branches inside constructs that // require braces, e.g. if/else, even though that would yield more idiomatic output. // But if we know for certain they won't backtrack, we can output the nicer code. if (analysis.IsAtomicByAncestor(node) || (!analysis.MayBacktrack(yesBranch) && (noBranch is null || !analysis.MayBacktrack(noBranch)))) { using (EmitBlock(writer, $"if (base.IsMatched({capnum}))")) { writer.WriteLine($"// The {DescribeCapture(node.M, analysis)} captured a value. Match the first branch."); EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch } if (noBranch is not null) { using (EmitBlock(writer, $"else")) { writer.WriteLine($"// Otherwise, match the second branch."); EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch } } doneLabel = originalDoneLabel; // atomicity return; } string refNotMatched = ReserveName("ConditionalBackreferenceNotMatched"); string endConditional = ReserveName("ConditionalBackreferenceEnd"); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the conditional needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. string resumeAt = ReserveName("conditionalbackreference_branch"); writer.WriteLine($"int {resumeAt} = 0;"); // While it would be nicely readable to use an if/else block, if the branches contain // anything that triggers backtracking, labels will end up being defined, and if they're // inside the scope block for the if or else, that will prevent jumping to them from // elsewhere. So we implement the if/else with labels and gotos manually. // Check to see if the specified capture number was captured. using (EmitBlock(writer, $"if (!base.IsMatched({capnum}))")) { Goto(refNotMatched); } writer.WriteLine(); // The specified capture was captured. Run the "yes" branch. // If it successfully matches, jump to the end. EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch string postYesDoneLabel = doneLabel; if (postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 0;"); } bool needsEndConditional = postYesDoneLabel != originalDoneLabel || noBranch is not null; if (needsEndConditional) { Goto(endConditional); writer.WriteLine(); } MarkLabel(refNotMatched); string postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (postNoDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 1;"); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 2;"); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. bool hasBacktracking = postYesDoneLabel != originalDoneLabel || postNoDoneLabel != originalDoneLabel; if (hasBacktracking) { // Skip the backtracking section. Goto(endConditional); writer.WriteLine(); // Backtrack section string backtrack = ReserveName("ConditionalBackreferenceBacktrack"); doneLabel = backtrack; MarkLabel(backtrack); // Pop from the stack the branch that was used and jump back to its backtracking location. EmitStackPop(resumeAt); using (EmitBlock(writer, $"switch ({resumeAt})")) { if (postYesDoneLabel != originalDoneLabel) { CaseGoto("case 0:", postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { CaseGoto("case 1:", postNoDoneLabel); } CaseGoto("default:", originalDoneLabel); } } if (needsEndConditional) { MarkLabel(endConditional); } if (hasBacktracking) { // We're not atomic and at least one of the yes or no branches contained backtracking constructs, // so finish outputting our backtracking logic, which involves pushing onto the stack which // branch to backtrack into. EmitStackPush(resumeAt); } } // Emits the code for an if(expression)-then-else conditional. void EmitExpressionConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.ExpressionConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 3, $"Expected 3 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // The first child node is the condition expression. If this matches, then we branch to the "yes" branch. // If it doesn't match, then we branch to the optional "no" branch if it exists, or simply skip the "yes" // branch, otherwise. The condition is treated as a positive lookaround. RegexNode condition = node.Child(0); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(1); RegexNode? noBranch = node.Child(2) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; string originalDoneLabel = doneLabel; string expressionNotMatched = ReserveName("ConditionalExpressionNotMatched"); string endConditional = ReserveName("ConditionalExpressionEnd"); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the condition needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. string resumeAt = ReserveName("conditionalexpression_branch"); if (!isAtomic) { writer.WriteLine($"int {resumeAt} = 0;"); } // If the condition expression has captures, we'll need to uncapture them in the case of no match. string? startingCapturePos = null; if (analysis.MayContainCapture(condition)) { startingCapturePos = ReserveName("conditionalexpression_starting_capturepos"); writer.WriteLine($"int {startingCapturePos} = base.Crawlpos();"); } // Emit the condition expression. Route any failures to after the yes branch. This code is almost // the same as for a positive lookaround; however, a positive lookaround only needs to reset the position // on a successful match, as a failed match fails the whole expression; here, we need to reset the // position on completion, regardless of whether the match is successful or not. doneLabel = expressionNotMatched; // Save off pos. We'll need to reset this upon successful completion of the lookaround. string startingPos = ReserveName("conditionalexpression_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); int startingSliceStaticPos = sliceStaticPos; // Emit the child. The condition expression is a zero-width assertion, which is atomic, // so prevent backtracking into it. writer.WriteLine("// Condition:"); EmitNode(condition); writer.WriteLine(); doneLabel = originalDoneLabel; // After the condition completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. writer.WriteLine("// Condition matched:"); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; writer.WriteLine(); // The expression matched. Run the "yes" branch. If it successfully matches, jump to the end. EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch string postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 0;"); } Goto(endConditional); writer.WriteLine(); // After the condition completes unsuccessfully, reset the text positions // _and_ reset captures, which should not persist when the whole expression failed. writer.WriteLine("// Condition did not match:"); MarkLabel(expressionNotMatched, emitSemicolon: false); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } writer.WriteLine(); string postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 1;"); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 2;"); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { doneLabel = originalDoneLabel; MarkLabel(endConditional); } else { // Skip the backtracking section. Goto(endConditional); writer.WriteLine(); string backtrack = ReserveName("ConditionalExpressionBacktrack"); doneLabel = backtrack; MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(resumeAt); using (EmitBlock(writer, $"switch ({resumeAt})")) { if (postYesDoneLabel != originalDoneLabel) { CaseGoto("case 0:", postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { CaseGoto("case 1:", postNoDoneLabel); } CaseGoto("default:", originalDoneLabel); } MarkLabel(endConditional, emitSemicolon: false); EmitStackPush(resumeAt); } } // Emits the code for a Capture node. void EmitCapture(RegexNode node, RegexNode? subsequent = null) { Debug.Assert(node.Kind is RegexNodeKind.Capture, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); int uncapnum = RegexParser.MapCaptureNumber(node.N, rm.Tree.CaptureNumberSparseMapping); bool isAtomic = analysis.IsAtomicByAncestor(node); TransferSliceStaticPosToPos(); string startingPos = ReserveName("capture_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); RegexNode child = node.Child(0); if (uncapnum != -1) { using (EmitBlock(writer, $"if (!base.IsMatched({uncapnum}))")) { Goto(doneLabel); } writer.WriteLine(); } // Emit child node. string originalDoneLabel = doneLabel; EmitNode(child, subsequent); bool childBacktracks = doneLabel != originalDoneLabel; writer.WriteLine(); TransferSliceStaticPosToPos(); if (uncapnum == -1) { writer.WriteLine($"base.Capture({capnum}, {startingPos}, pos);"); } else { writer.WriteLine($"base.TransferCapture({capnum}, {uncapnum}, {startingPos}, pos);"); } if (isAtomic || !childBacktracks) { // If the capture is atomic and nothing can backtrack into it, we're done. // Similarly, even if the capture isn't atomic, if the captured expression // doesn't do any backtracking, we're done. doneLabel = originalDoneLabel; } else { // We're not atomic and the child node backtracks. When it does, we need // to ensure that the starting position for the capture is appropriately // reset to what it was initially (it could have changed as part of being // in a loop or similar). So, we emit a backtracking section that // pushes/pops the starting position before falling through. writer.WriteLine(); EmitStackPush(startingPos); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label string backtrack = ReserveName($"CaptureBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(startingPos); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } // Emits the code to handle a positive lookaround assertion. This is a positive lookahead // for left-to-right and a positive lookbehind for right-to-left. void EmitPositiveLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.PositiveLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } // Save off pos. We'll need to reset this upon successful completion of the lookaround. string startingPos = ReserveName("positivelookaround_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); int startingSliceStaticPos = sliceStaticPos; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // After the child completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. writer.WriteLine(); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; } // Emits the code to handle a negative lookaround assertion. This is a negative lookahead // for left-to-right and a negative lookbehind for right-to-left. void EmitNegativeLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } string originalDoneLabel = doneLabel; // Save off pos. We'll need to reset this upon successful completion of the lookaround. string startingPos = ReserveName("negativelookaround_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); int startingSliceStaticPos = sliceStaticPos; string negativeLookaroundDoneLabel = ReserveName("NegativeLookaroundMatch"); doneLabel = negativeLookaroundDoneLabel; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // If the generated code ends up here, it matched the lookaround, which actually // means failure for a _negative_ lookaround, so we need to jump to the original done. writer.WriteLine(); Goto(originalDoneLabel); writer.WriteLine(); // Failures (success for a negative lookaround) jump here. MarkLabel(negativeLookaroundDoneLabel, emitSemicolon: false); // After the child completes in failure (success for negative lookaround), reset the text positions. writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; doneLabel = originalDoneLabel; } // Emits the code for the node. void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(EmitNode, node, subsequent, emitLengthChecksIfRequired); return; } if ((node.Options & RegexOptions.RightToLeft) != 0) { // RightToLeft doesn't take advantage of static positions. While RightToLeft won't update static // positions, a previous operation may have left us with a non-zero one. Make sure it's zero'd out // such that pos and slice are up-to-date. Note that RightToLeft also shouldn't use the slice span, // as it's not kept up-to-date; any RightToLeft implementation that wants to use it must first update // it from pos. TransferSliceStaticPosToPos(); } // Separate out several node types that, for conciseness, don't need a header nor scope written into the source. // Effectively these either evaporate, are completely self-explanatory, or only exist for their children to be rendered. switch (node.Kind) { // Nothing is written for an empty. case RegexNodeKind.Empty: return; // A single-line goto for a failure doesn't need a scope or comment. case RegexNodeKind.Nothing: Goto(doneLabel); return; // Skip atomic nodes that wrap non-backtracking children; in such a case there's nothing to be made atomic. case RegexNodeKind.Atomic when !analysis.MayBacktrack(node.Child(0)): EmitNode(node.Child(0)); return; // Concatenate is a simplification in the node tree so that a series of children can be represented as one. // We don't need its presence visible in the source. case RegexNodeKind.Concatenate: EmitConcatenation(node, subsequent, emitLengthChecksIfRequired); return; } // For everything else, output a comment about what the node is. writer.WriteLine($"// {DescribeNode(node, analysis)}"); // Separate out several node types that, for conciseness, don't need a scope written into the source as they're // always a single statement / block. switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: case RegexNodeKind.Bol: case RegexNodeKind.Eol: case RegexNodeKind.End: case RegexNodeKind.EndZ: EmitAnchors(node); return; case RegexNodeKind.Boundary: case RegexNodeKind.NonBoundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.NonECMABoundary: EmitBoundary(node); return; case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: EmitSingleChar(node, emitLengthChecksIfRequired); return; case RegexNodeKind.Multi when !IsCaseInsensitive(node) && (node.Options & RegexOptions.RightToLeft) == 0: EmitMultiChar(node, emitLengthChecksIfRequired); return; case RegexNodeKind.UpdateBumpalong: EmitUpdateBumpalong(node); return; } // For everything else, put the node's code into its own scope, purely for readability. If the node contains labels // that may need to be visible outside of its scope, the scope is still emitted for clarity but is commented out. using (EmitScope(writer, null, faux: analysis.MayBacktrack(node))) { switch (node.Kind) { case RegexNodeKind.Multi: EmitMultiChar(node, emitLengthChecksIfRequired); return; case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: EmitSingleCharLoop(node, subsequent, emitLengthChecksIfRequired); return; case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: EmitSingleCharLazy(node, subsequent, emitLengthChecksIfRequired); return; case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: EmitSingleCharAtomicLoop(node, emitLengthChecksIfRequired); return; case RegexNodeKind.Loop: EmitLoop(node); return; case RegexNodeKind.Lazyloop: EmitLazy(node); return; case RegexNodeKind.Alternate: EmitAlternation(node); return; case RegexNodeKind.Backreference: EmitBackreference(node); return; case RegexNodeKind.BackreferenceConditional: EmitBackreferenceConditional(node); return; case RegexNodeKind.ExpressionConditional: EmitExpressionConditional(node); return; case RegexNodeKind.Atomic: Debug.Assert(analysis.MayBacktrack(node.Child(0))); EmitAtomic(node, subsequent); return; case RegexNodeKind.Capture: EmitCapture(node, subsequent); return; case RegexNodeKind.PositiveLookaround: EmitPositiveLookaroundAssertion(node); return; case RegexNodeKind.NegativeLookaround: EmitNegativeLookaroundAssertion(node); return; } } // All nodes should have been handled. Debug.Fail($"Unexpected node type: {node.Kind}"); } // Emits the node for an atomic. void EmitAtomic(RegexNode node, RegexNode? subsequent) { Debug.Assert(node.Kind is RegexNodeKind.Atomic or RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(analysis.MayBacktrack(node.Child(0)), "Expected child to potentially backtrack"); // Grab the current done label and the current backtracking position. The purpose of the atomic node // is to ensure that nodes after it that might backtrack skip over the atomic, which means after // rendering the atomic's child, we need to reset the label so that subsequent backtracking doesn't // see any label left set by the atomic's child. We also need to reset the backtracking stack position // so that the state on the stack remains consistent. string originalDoneLabel = doneLabel; additionalDeclarations.Add("int stackpos = 0;"); string startingStackpos = ReserveName("atomic_stackpos"); writer.WriteLine($"int {startingStackpos} = stackpos;"); writer.WriteLine(); // Emit the child. EmitNode(node.Child(0), subsequent); writer.WriteLine(); // Reset the stack position and done label. writer.WriteLine($"stackpos = {startingStackpos};"); doneLabel = originalDoneLabel; } // Emits the code to handle updating base.runtextpos to pos in response to // an UpdateBumpalong node. This is used when we want to inform the scan loop that // it should bump from this location rather than from the original location. void EmitUpdateBumpalong(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.UpdateBumpalong, $"Unexpected type: {node.Kind}"); TransferSliceStaticPosToPos(); using (EmitBlock(writer, "if (base.runtextpos < pos)")) { writer.WriteLine("base.runtextpos = pos;"); } } // Emits code for a concatenation void EmitConcatenation(RegexNode node, RegexNode? subsequent, bool emitLengthChecksIfRequired) { Debug.Assert(node.Kind is RegexNodeKind.Concatenate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); // Emit the code for each child one after the other. string? prevDescription = null; int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { // If we can find a subsequence of fixed-length children, we can emit a length check once for that sequence // and then skip the individual length checks for each. We can also discover case-insensitive sequences that // can be checked efficiently with methods like StartsWith. We also want to minimize the repetition of if blocks, // and so we try to emit a series of clauses all part of the same if block rather than one if block per child. if ((node.Options & RegexOptions.RightToLeft) == 0 && emitLengthChecksIfRequired && node.TryGetJoinableLengthCheckChildRange(i, out int requiredLength, out int exclusiveEnd)) { bool wroteClauses = true; writer.Write($"if ({SpanLengthCheck(requiredLength)}"); while (i < exclusiveEnd) { for (; i < exclusiveEnd; i++) { void WritePrefix() { if (wroteClauses) { writer.WriteLine(prevDescription is not null ? $" || // {prevDescription}" : " ||"); writer.Write(" "); } else { writer.Write("if ("); } } RegexNode child = node.Child(i); if (node.TryGetOrdinalCaseInsensitiveString(i, exclusiveEnd, out int nodesConsumed, out string? caseInsensitiveString)) { WritePrefix(); string sourceSpan = sliceStaticPos > 0 ? $"{sliceSpan}.Slice({sliceStaticPos})" : sliceSpan; writer.Write($"!global::System.MemoryExtensions.StartsWith({sourceSpan}, {Literal(caseInsensitiveString)}, global::System.StringComparison.OrdinalIgnoreCase)"); prevDescription = $"Match the string {Literal(caseInsensitiveString)} (ordinal case-insensitive)"; wroteClauses = true; sliceStaticPos += caseInsensitiveString.Length; i += nodesConsumed - 1; } else if (child.Kind is RegexNodeKind.Multi && !IsCaseInsensitive(child)) { WritePrefix(); EmitMultiCharString(child.Str!, caseInsensitive: false, emitLengthCheck: false, clauseOnly: true, rightToLeft: false); prevDescription = DescribeNode(child, analysis); wroteClauses = true; } else if ((child.IsOneFamily || child.IsNotoneFamily || child.IsSetFamily) && child.M == child.N && child.M <= MaxUnrollSize) { int repeatCount = child.Kind is RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set ? 1 : child.M; for (int c = 0; c < repeatCount; c++) { WritePrefix(); EmitSingleChar(child, emitLengthCheck: false, clauseOnly: true); prevDescription = c == 0 ? DescribeNode(child, analysis) : null; wroteClauses = true; } } else break; } if (wroteClauses) { writer.WriteLine(prevDescription is not null ? $") // {prevDescription}" : ")"); using (EmitBlock(writer, null)) { Goto(doneLabel); } if (i < childCount) { writer.WriteLine(); } wroteClauses = false; prevDescription = null; } if (i < exclusiveEnd) { EmitNode(node.Child(i), GetSubsequentOrDefault(i, node, subsequent), emitLengthChecksIfRequired: false); if (i < childCount - 1) { writer.WriteLine(); } i++; } } i--; continue; } EmitNode(node.Child(i), GetSubsequentOrDefault(i, node, subsequent), emitLengthChecksIfRequired: emitLengthChecksIfRequired); if (i < childCount - 1) { writer.WriteLine(); } } // Gets the node to treat as the subsequent one to node.Child(index) static RegexNode? GetSubsequentOrDefault(int index, RegexNode node, RegexNode? defaultNode) { int childCount = node.ChildCount(); for (int i = index + 1; i < childCount; i++) { RegexNode next = node.Child(i); if (next.Kind is not RegexNodeKind.UpdateBumpalong) // skip node types that don't have a semantic impact { return next; } } return defaultNode; } } // Emits the code to handle a single-character match. void EmitSingleChar(RegexNode node, bool emitLengthCheck = true, string? offset = null, bool clauseOnly = false) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; Debug.Assert(!rtl || offset is null); Debug.Assert(!rtl || !clauseOnly); string expr = !rtl ? $"{sliceSpan}[{Sum(sliceStaticPos, offset)}]" : "inputSpan[pos - 1]"; if (node.IsSetFamily) { expr = $"{MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: true, additionalDeclarations, ref requiredHelpers)}"; } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "!=" : "==")} {Literal(node.Ch)}"; } if (clauseOnly) { writer.Write(expr); } else { string clause = !emitLengthCheck ? $"if ({expr})" : !rtl ? $"if ({SpanLengthCheck(1, offset)} || {expr})" : $"if ((uint)(pos - 1) >= inputSpan.Length || {expr})"; using (EmitBlock(writer, clause)) { Goto(doneLabel); } } if (!rtl) { sliceStaticPos++; } else { writer.WriteLine("pos--;"); } } // Emits the code to handle a boundary check on a character. void EmitBoundary(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Boundary or RegexNodeKind.NonBoundary or RegexNodeKind.ECMABoundary or RegexNodeKind.NonECMABoundary, $"Unexpected type: {node.Kind}"); string call = node.Kind switch { RegexNodeKind.Boundary => "!IsBoundary", RegexNodeKind.NonBoundary => "IsBoundary", RegexNodeKind.ECMABoundary => "!IsECMABoundary", _ => "IsECMABoundary", }; RequiredHelperFunctions boundaryFunctionRequired = node.Kind switch { RegexNodeKind.Boundary or RegexNodeKind.NonBoundary => RequiredHelperFunctions.IsBoundary | RequiredHelperFunctions.IsWordChar, // IsBoundary internally uses IsWordChar _ => RequiredHelperFunctions.IsECMABoundary }; requiredHelpers |= boundaryFunctionRequired; using (EmitBlock(writer, $"if ({call}(inputSpan, pos{(sliceStaticPos > 0 ? $" + {sliceStaticPos}" : "")}))")) { Goto(doneLabel); } } // Emits the code to handle various anchors. void EmitAnchors(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.Bol or RegexNodeKind.End or RegexNodeKind.EndZ or RegexNodeKind.Eol, $"Unexpected type: {node.Kind}"); Debug.Assert((node.Options & RegexOptions.RightToLeft) == 0 || sliceStaticPos == 0); Debug.Assert(sliceStaticPos >= 0); switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: if (sliceStaticPos > 0) { // If we statically know we've already matched part of the regex, there's no way we're at the // beginning or start, as we've already progressed past it. Goto(doneLabel); } else { using (EmitBlock(writer, node.Kind == RegexNodeKind.Beginning ? "if (pos != 0)" : "if (pos != base.runtextstart)")) { Goto(doneLabel); } } break; case RegexNodeKind.Bol: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceSpan}[{sliceStaticPos - 1}] != '\\n')" : $"if (pos > 0 && inputSpan[pos - 1] != '\\n')")) { Goto(doneLabel); } break; case RegexNodeKind.End: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceStaticPos} < {sliceSpan}.Length)" : "if ((uint)pos < (uint)inputSpan.Length)")) { Goto(doneLabel); } break; case RegexNodeKind.EndZ: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceStaticPos + 1} < {sliceSpan}.Length || ({sliceStaticPos} < {sliceSpan}.Length && {sliceSpan}[{sliceStaticPos}] != '\\n'))" : "if (pos < inputSpan.Length - 1 || ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\\n'))")) { Goto(doneLabel); } break; case RegexNodeKind.Eol: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceStaticPos} < {sliceSpan}.Length && {sliceSpan}[{sliceStaticPos}] != '\\n')" : "if ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\\n')")) { Goto(doneLabel); } break; } } // Emits the code to handle a multiple-character match. void EmitMultiChar(RegexNode node, bool emitLengthCheck) { Debug.Assert(node.Kind is RegexNodeKind.Multi, $"Unexpected type: {node.Kind}"); Debug.Assert(node.Str is not null); EmitMultiCharString(node.Str, IsCaseInsensitive(node), emitLengthCheck, clauseOnly: false, (node.Options & RegexOptions.RightToLeft) != 0); } void EmitMultiCharString(string str, bool caseInsensitive, bool emitLengthCheck, bool clauseOnly, bool rightToLeft) { Debug.Assert(str.Length >= 2); Debug.Assert(!clauseOnly || (!emitLengthCheck && !caseInsensitive && !rightToLeft)); if (rightToLeft) { Debug.Assert(emitLengthCheck); using (EmitBlock(writer, $"if ((uint)(pos - {str.Length}) >= inputSpan.Length)")) { Goto(doneLabel); } writer.WriteLine(); using (EmitBlock(writer, $"for (int i = 0; i < {str.Length}; i++)")) { using (EmitBlock(writer, $"if ({ToLowerIfNeeded(hasTextInfo, options, "inputSpan[--pos]", caseInsensitive)} != {Literal(str)}[{str.Length - 1} - i])")) { Goto(doneLabel); } } return; } if (caseInsensitive) // StartsWith(..., XxIgnoreCase) won't necessarily be the same as char-by-char comparison { // This case should be relatively rare. It will only occur with IgnoreCase and a series of non-ASCII characters. if (emitLengthCheck) { EmitSpanLengthCheck(str.Length); } using (EmitBlock(writer, $"for (int i = 0; i < {Literal(str)}.Length; i++)")) { string textSpanIndex = sliceStaticPos > 0 ? $"i + {sliceStaticPos}" : "i"; using (EmitBlock(writer, $"if ({ToLower(hasTextInfo, options, $"{sliceSpan}[{textSpanIndex}]")} != {Literal(str)}[i])")) { Goto(doneLabel); } } } else { string sourceSpan = sliceStaticPos > 0 ? $"{sliceSpan}.Slice({sliceStaticPos})" : sliceSpan; string clause = $"!global::System.MemoryExtensions.StartsWith({sourceSpan}, {Literal(str)})"; if (clauseOnly) { writer.Write(clause); } else { using (EmitBlock(writer, $"if ({clause})")) { Goto(doneLabel); } } } sliceStaticPos += str.Length; } void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop, $"Unexpected type: {node.Kind}"); // If this is actually atomic based on its parent, emit it as atomic instead; no backtracking necessary. if (analysis.IsAtomicByAncestor(node)) { EmitSingleCharAtomicLoop(node); return; } // If this is actually a repeater, emit that instead; no backtracking necessary. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // Emit backtracking around an atomic single char loop. We can then implement the backtracking // as an afterthought, since we know exactly how many characters are accepted by each iteration // of the wrapped loop (1) and that there's nothing captured by the loop. Debug.Assert(node.M < node.N); string backtrackingLabel = ReserveName("CharLoopBacktrack"); string endLoop = ReserveName("CharLoopEnd"); string startingPos = ReserveName("charloop_starting_pos"); string endingPos = ReserveName("charloop_ending_pos"); additionalDeclarations.Add($"int {startingPos} = 0, {endingPos} = 0;"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // Grab the current position, then emit the loop as atomic, and then // grab the current position again. Even though we emit the loop without // knowledge of backtracking, we can layer it on top by just walking back // through the individual characters (a benefit of the loop matching exactly // one character per iteration, no possible captures within the loop, etc.) writer.WriteLine($"{startingPos} = pos;"); writer.WriteLine(); EmitSingleCharAtomicLoop(node); writer.WriteLine(); TransferSliceStaticPosToPos(); writer.WriteLine($"{endingPos} = pos;"); EmitAdd(writer, startingPos, !rtl ? node.M : -node.M); Goto(endLoop); writer.WriteLine(); // Backtracking section. Subsequent failures will jump to here, at which // point we decrement the matched count as long as it's above the minimum // required, and try again by flowing to everything that comes after this. MarkLabel(backtrackingLabel, emitSemicolon: false); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } EmitStackPop(endingPos, startingPos); writer.WriteLine(); if (!rtl && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal) { writer.WriteLine($"if ({startingPos} >= {endingPos} ||"); using (EmitBlock(writer, literal.Item2 is not null ? $" ({endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, global::System.Math.Min(inputSpan.Length, {endingPos} + {literal.Item2.Length - 1}) - {startingPos}), {Literal(literal.Item2)})) < 0)" : literal.Item3 is null ? $" ({endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item1)})) < 0)" : literal.Item3.Length switch { 2 => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])})) < 0)", 3 => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])}, {Literal(literal.Item3[2])})) < 0)", _ => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3)})) < 0)", })) { Goto(doneLabel); } writer.WriteLine($"{endingPos} += {startingPos};"); writer.WriteLine($"pos = {endingPos};"); } else { using (EmitBlock(writer, $"if ({startingPos} {(!rtl ? ">=" : "<=")} {endingPos})")) { Goto(doneLabel); } writer.WriteLine(!rtl ? $"pos = --{endingPos};" : $"pos = ++{endingPos};"); } if (!rtl) { SliceInputSpan(writer); } writer.WriteLine(); MarkLabel(endLoop, emitSemicolon: false); EmitStackPush(expressionHasCaptures ? new[] { startingPos, endingPos, "base.Crawlpos()" } : new[] { startingPos, endingPos }); doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes } void EmitSingleCharLazy(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy, $"Unexpected type: {node.Kind}"); // Emit the min iterations as a repeater. Any failures here don't necessitate backtracking, // as the lazy itself failed to match, and there's no backtracking possible by the individual // characters/iterations themselves. if (node.M > 0) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); } // If the whole thing was actually that repeater, we're done. Similarly, if this is actually an atomic // lazy loop, nothing will ever backtrack into this node, so we never need to iterate more than the minimum. if (node.M == node.N || analysis.IsAtomicByAncestor(node)) { return; } if (node.M > 0) { // We emitted a repeater to handle the required iterations; add a newline after it. writer.WriteLine(); } Debug.Assert(node.M < node.N); // We now need to match one character at a time, each time allowing the remainder of the expression // to try to match, and only matching another character if the subsequent expression fails to match. // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // If the loop isn't unbounded, track the number of iterations and the max number to allow. string? iterationCount = null; string? maxIterations = null; if (node.N != int.MaxValue) { maxIterations = $"{node.N - node.M}"; iterationCount = ReserveName("lazyloop_iteration"); writer.WriteLine($"int {iterationCount} = 0;"); } // Track the current crawl position. Upon backtracking, we'll unwind any captures beyond this point. string? capturePos = null; if (expressionHasCaptures) { capturePos = ReserveName("lazyloop_capturepos"); additionalDeclarations.Add($"int {capturePos} = 0;"); } // Track the current pos. Each time we backtrack, we'll reset to the stored position, which // is also incremented each time we match another character in the loop. string startingPos = ReserveName("lazyloop_pos"); additionalDeclarations.Add($"int {startingPos} = 0;"); writer.WriteLine($"{startingPos} = pos;"); // Skip the backtracking section for the initial subsequent matching. We've already matched the // minimum number of iterations, which means we can successfully match with zero additional iterations. string endLoopLabel = ReserveName("LazyLoopEnd"); Goto(endLoopLabel); writer.WriteLine(); // Backtracking section. Subsequent failures will jump to here. string backtrackingLabel = ReserveName("LazyLoopBacktrack"); MarkLabel(backtrackingLabel, emitSemicolon: false); // Uncapture any captures if the expression has any. It's possible the captures it has // are before this node, in which case this is wasted effort, but still functionally correct. if (capturePos is not null) { EmitUncaptureUntil(capturePos); } // If there's a max number of iterations, see if we've exceeded the maximum number of characters // to match. If we haven't, increment the iteration count. if (maxIterations is not null) { using (EmitBlock(writer, $"if ({iterationCount} >= {maxIterations})")) { Goto(doneLabel); } writer.WriteLine($"{iterationCount}++;"); } // Now match the next item in the lazy loop. We need to reset the pos to the position // just after the last character in this loop was matched, and we need to store the resulting position // for the next time we backtrack. writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); EmitSingleChar(node); TransferSliceStaticPosToPos(); // Now that we've appropriately advanced by one character and are set for what comes after the loop, // see if we can skip ahead more iterations by doing a search for a following literal. if ((node.Options & RegexOptions.RightToLeft) == 0) { if (iterationCount is null && node.Kind is RegexNodeKind.Notonelazy && !IsCaseInsensitive(node) && subsequent?.FindStartingLiteral(4) is ValueTuple<char, string?, string?> literal && // 5 == max optimized by IndexOfAny, and we need to reserve 1 for node.Ch (literal.Item3 is not null ? !literal.Item3.Contains(node.Ch) : (literal.Item2?[0] ?? literal.Item1) != node.Ch)) // no overlap between node.Ch and the start of the literal { // e.g. "<[^>]*?>" // This lazy loop will consume all characters other than node.Ch until the subsequent literal. // We can implement it to search for either that char or the literal, whichever comes first. // If it ends up being that node.Ch, the loop fails (we're only here if we're backtracking). writer.WriteLine( literal.Item2 is not null ? $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item2[0])});" : literal.Item3 is null ? $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item1)});" : literal.Item3.Length switch { 2 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])});", _ => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch + literal.Item3)});", }); using (EmitBlock(writer, $"if ((uint){startingPos} >= (uint){sliceSpan}.Length || {sliceSpan}[{startingPos}] == {Literal(node.Ch)})")) { Goto(doneLabel); } writer.WriteLine($"pos += {startingPos};"); SliceInputSpan(writer); } else if (iterationCount is null && node.Kind is RegexNodeKind.Setlazy && node.Str == RegexCharClass.AnyClass && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal2) { // e.g. ".*?string" with RegexOptions.Singleline // This lazy loop will consume all characters until the subsequent literal. If the subsequent literal // isn't found, the loop fails. We can implement it to just search for that literal. writer.WriteLine( literal2.Item2 is not null ? $"{startingPos} = global::System.MemoryExtensions.IndexOf({sliceSpan}, {Literal(literal2.Item2)});" : literal2.Item3 is null ? $"{startingPos} = global::System.MemoryExtensions.IndexOf({sliceSpan}, {Literal(literal2.Item1)});" : literal2.Item3.Length switch { 2 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3[0])}, {Literal(literal2.Item3[1])});", 3 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3[0])}, {Literal(literal2.Item3[1])}, {Literal(literal2.Item3[2])});", _ => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3)});", }); using (EmitBlock(writer, $"if ({startingPos} < 0)")) { Goto(doneLabel); } writer.WriteLine($"pos += {startingPos};"); SliceInputSpan(writer); } } // Store the position we've left off at in case we need to iterate again. writer.WriteLine($"{startingPos} = pos;"); // Update the done label for everything that comes after this node. This is done after we emit the single char // matching, as that failing indicates the loop itself has failed to match. string originalDoneLabel = doneLabel; doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes writer.WriteLine(); MarkLabel(endLoopLabel); if (capturePos is not null) { writer.WriteLine($"{capturePos} = base.Crawlpos();"); } if (node.IsInLoop()) { writer.WriteLine(); // Store the loop's state var toPushPop = new List<string>(3) { startingPos }; if (capturePos is not null) { toPushPop.Add(capturePos); } if (iterationCount is not null) { toPushPop.Add(iterationCount); } string[] toPushPopArray = toPushPop.ToArray(); EmitStackPush(toPushPopArray); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label string backtrack = ReserveName("CharLazyBacktrack"); MarkLabel(backtrack, emitSemicolon: false); Array.Reverse(toPushPopArray); EmitStackPop(toPushPopArray); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } void EmitLazy(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; string originalDoneLabel = doneLabel; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually an atomic lazy loop, we need to output just the minimum number of iterations, // as nothing will backtrack into the lazy loop to get it progress further. if (isAtomic) { switch (minIterations) { case 0: // Atomic lazy with a min count of 0: nop. return; case 1: // Atomic lazy with a min count of 1: just output the child, no looping required. EmitNode(node.Child(0)); return; } writer.WriteLine(); } // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); string startingPos = ReserveName("lazyloop_starting_pos"); string iterationCount = ReserveName("lazyloop_iteration"); string sawEmpty = ReserveName("lazyLoopEmptySeen"); string body = ReserveName("LazyLoopBody"); string endLoop = ReserveName("LazyLoopEnd"); writer.WriteLine($"int {iterationCount} = 0, {startingPos} = pos, {sawEmpty} = 0;"); // If the min count is 0, start out by jumping right to what's after the loop. Backtracking // will then bring us back in to do further iterations. if (minIterations == 0) { Goto(endLoop); } writer.WriteLine(); // Iteration body MarkLabel(body, emitSemicolon: false); EmitTimeoutCheck(writer, hasTimeout); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackPush(expressionHasCaptures ? new[] { "base.Crawlpos()", startingPos, "pos", sawEmpty } : new[] { startingPos, "pos", sawEmpty }); writer.WriteLine(); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. writer.WriteLine($"{startingPos} = pos;"); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. writer.WriteLine($"{iterationCount}++;"); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. string iterationFailedLabel = ReserveName("LazyLoopIterationNoMatch"); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); writer.WriteLine(); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 if (doneLabel == iterationFailedLabel) { doneLabel = originalDoneLabel; } // Loop condition. Continue iterating if we've not yet reached the minimum. if (minIterations > 0) { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, minIterations)})")) { Goto(body); } } // If the last iteration was empty, we need to prevent further iteration from this point // unless we backtrack out of this iteration. We can do that easily just by pretending // we reached the max iteration count. using (EmitBlock(writer, $"if (pos == {startingPos})")) { writer.WriteLine($"{sawEmpty} = 1;"); } // We matched the next iteration. Jump to the subsequent code. Goto(endLoop); writer.WriteLine(); // Now handle what happens when an iteration fails. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel, emitSemicolon: false); writer.WriteLine($"{iterationCount}--;"); using (EmitBlock(writer, $"if ({iterationCount} < 0)")) { Goto(originalDoneLabel); } EmitStackPop(sawEmpty, "pos", startingPos); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } SliceInputSpan(writer); if (doneLabel == originalDoneLabel) { Goto(originalDoneLabel); } else { using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } Goto(doneLabel); } writer.WriteLine(); MarkLabel(endLoop); if (!isAtomic) { // Store the capture's state and skip the backtracking section EmitStackPush(startingPos, iterationCount, sawEmpty); string skipBacktrack = ReserveName("SkipBacktrack"); Goto(skipBacktrack); writer.WriteLine(); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label string backtrack = ReserveName($"LazyLoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(sawEmpty, iterationCount, startingPos); if (maxIterations == int.MaxValue) { using (EmitBlock(writer, $"if ({sawEmpty} == 0)")) { Goto(body); } } else { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, maxIterations)} && {sawEmpty} == 0)")) { Goto(body); } } Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(skipBacktrack); } } // Emits the code to handle a loop (repeater) with a fixed number of iterations. // RegexNode.M is used for the number of iterations (RegexNode.N is ignored), as this // might be used to implement the required iterations of other kinds of loops. void EmitSingleCharRepeater(RegexNode node, bool emitLengthCheck = true) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); int iterations = node.M; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; switch (iterations) { case 0: // No iterations, nothing to do. return; case 1: // Just match the individual item EmitSingleChar(node, emitLengthCheck); return; case <= RegexNode.MultiVsRepeaterLimit when node.IsOneFamily && !IsCaseInsensitive(node): // This is a repeated case-sensitive character; emit it as a multi in order to get all the optimizations // afforded to a multi, e.g. unrolling the loop with multi-char reads/comparisons at a time. EmitMultiCharString(new string(node.Ch, iterations), caseInsensitive: false, emitLengthCheck, clauseOnly: false, rtl); return; } if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position with rtl using (EmitBlock(writer, $"for (int i = 0; i < {iterations}; i++)")) { EmitTimeoutCheck(writer, hasTimeout); EmitSingleChar(node); } } else if (iterations <= MaxUnrollSize) { // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length || // slice[sliceStaticPos] != c1 || // slice[sliceStaticPos + 1] != c2 || // ...) // { // goto doneLabel; // } writer.Write($"if ("); if (emitLengthCheck) { writer.WriteLine($"{SpanLengthCheck(iterations)} ||"); writer.Write(" "); } EmitSingleChar(node, emitLengthCheck: false, clauseOnly: true); for (int i = 1; i < iterations; i++) { writer.WriteLine(" ||"); writer.Write(" "); EmitSingleChar(node, emitLengthCheck: false, clauseOnly: true); } writer.WriteLine(")"); using (EmitBlock(writer, null)) { Goto(doneLabel); } } else { // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length) goto doneLabel; if (emitLengthCheck) { EmitSpanLengthCheck(iterations); } string repeaterSpan = "repeaterSlice"; // As this repeater doesn't wrap arbitrary node emits, this shouldn't conflict with anything writer.WriteLine($"global::System.ReadOnlySpan<char> {repeaterSpan} = {sliceSpan}.Slice({sliceStaticPos}, {iterations});"); using (EmitBlock(writer, $"for (int i = 0; i < {repeaterSpan}.Length; i++)")) { EmitTimeoutCheck(writer, hasTimeout); string tmpTextSpanLocal = sliceSpan; // we want EmitSingleChar to refer to this temporary int tmpSliceStaticPos = sliceStaticPos; sliceSpan = repeaterSpan; sliceStaticPos = 0; EmitSingleChar(node, emitLengthCheck: false, offset: "i"); sliceSpan = tmpTextSpanLocal; sliceStaticPos = tmpSliceStaticPos; } sliceStaticPos += iterations; } } // Emits the code to handle a non-backtracking, variable-length loop around a single character comparison. void EmitSingleCharAtomicLoop(RegexNode node, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); // If this is actually a repeater, emit that instead. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // If this is actually an optional single char, emit that instead. if (node.M == 0 && node.N == 1) { EmitAtomicSingleCharZeroOrOne(node); return; } Debug.Assert(node.N > node.M); int minIterations = node.M; int maxIterations = node.N; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; Span<char> setChars = stackalloc char[5]; // 5 is max optimized by IndexOfAny today int numSetChars = 0; string iterationLocal = ReserveName("iteration"); if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position for rtl string expr = $"inputSpan[pos - {iterationLocal} - 1]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } writer.WriteLine($"int {iterationLocal} = 0;"); string maxClause = maxIterations != int.MaxValue ? $"{CountIsLessThan(iterationLocal, maxIterations)} && " : ""; using (EmitBlock(writer, $"while ({maxClause}pos > {iterationLocal} && {expr})")) { EmitTimeoutCheck(writer, hasTimeout); writer.WriteLine($"{iterationLocal}++;"); } writer.WriteLine(); } else if (node.IsNotoneFamily && maxIterations == int.MaxValue && (!IsCaseInsensitive(node))) { // For Notone, we're looking for a specific character, as everything until we find // it is consumed by the loop. If we're unbounded, such as with ".*" and if we're case-sensitive, // we can use the vectorized IndexOf to do the search, rather than open-coding it. The unbounded // restriction is purely for simplicity; it could be removed in the future with additional code to // handle the unbounded case. writer.Write($"int {iterationLocal} = global::System.MemoryExtensions.IndexOf({sliceSpan}"); if (sliceStaticPos > 0) { writer.Write($".Slice({sliceStaticPos})"); } writer.WriteLine($", {Literal(node.Ch)});"); using (EmitBlock(writer, $"if ({iterationLocal} < 0)")) { writer.WriteLine(sliceStaticPos > 0 ? $"{iterationLocal} = {sliceSpan}.Length - {sliceStaticPos};" : $"{iterationLocal} = {sliceSpan}.Length;"); } writer.WriteLine(); } else if (node.IsSetFamily && maxIterations == int.MaxValue && !IsCaseInsensitive(node) && (numSetChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0 && RegexCharClass.IsNegated(node.Str!)) { // If the set is negated and contains only a few characters (if it contained 1 and was negated, it should // have been reduced to a Notone), we can use an IndexOfAny to find any of the target characters. // As with the notoneloopatomic above, the unbounded constraint is purely for simplicity. Debug.Assert(numSetChars > 1); writer.Write($"int {iterationLocal} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}"); if (sliceStaticPos != 0) { writer.Write($".Slice({sliceStaticPos})"); } writer.WriteLine(numSetChars switch { 2 => $", {Literal(setChars[0])}, {Literal(setChars[1])});", 3 => $", {Literal(setChars[0])}, {Literal(setChars[1])}, {Literal(setChars[2])});", _ => $", {Literal(setChars.Slice(0, numSetChars).ToString())});", }); using (EmitBlock(writer, $"if ({iterationLocal} < 0)")) { writer.WriteLine(sliceStaticPos > 0 ? $"{iterationLocal} = {sliceSpan}.Length - {sliceStaticPos};" : $"{iterationLocal} = {sliceSpan}.Length;"); } writer.WriteLine(); } else if (node.IsSetFamily && maxIterations == int.MaxValue && node.Str == RegexCharClass.AnyClass) { // .* was used with RegexOptions.Singleline, which means it'll consume everything. Just jump to the end. // The unbounded constraint is the same as in the Notone case above, done purely for simplicity. TransferSliceStaticPosToPos(); writer.WriteLine($"int {iterationLocal} = inputSpan.Length - pos;"); } else { // For everything else, do a normal loop. string expr = $"{sliceSpan}[{iterationLocal}]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } if (minIterations != 0 || maxIterations != int.MaxValue) { // For any loops other than * loops, transfer text pos to pos in // order to zero it out to be able to use the single iteration variable // for both iteration count and indexer. TransferSliceStaticPosToPos(); } writer.WriteLine($"int {iterationLocal} = {sliceStaticPos};"); sliceStaticPos = 0; string maxClause = maxIterations != int.MaxValue ? $"{CountIsLessThan(iterationLocal, maxIterations)} && " : ""; using (EmitBlock(writer, $"while ({maxClause}(uint){iterationLocal} < (uint){sliceSpan}.Length && {expr})")) { EmitTimeoutCheck(writer, hasTimeout); writer.WriteLine($"{iterationLocal}++;"); } writer.WriteLine(); } // Check to ensure we've found at least min iterations. if (minIterations > 0) { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationLocal, minIterations)})")) { Goto(doneLabel); } writer.WriteLine(); } // Now that we've completed our optional iterations, advance the text span // and pos by the number of iterations completed. if (!rtl) { writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice({iterationLocal});"); writer.WriteLine($"pos += {iterationLocal};"); } else { writer.WriteLine($"pos -= {iterationLocal};"); } } // Emits the code to handle a non-backtracking optional zero-or-one loop. void EmitAtomicSingleCharZeroOrOne(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M == 0 && node.N == 1); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; if (rtl) { TransferSliceStaticPosToPos(); // we don't use static pos for rtl } string expr = !rtl ? $"{sliceSpan}[{sliceStaticPos}]" : "inputSpan[pos - 1]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } string spaceAvailable = rtl ? "pos > 0" : sliceStaticPos != 0 ? $"(uint){sliceSpan}.Length > (uint){sliceStaticPos}" : $"!{sliceSpan}.IsEmpty"; using (EmitBlock(writer, $"if ({spaceAvailable} && {expr})")) { if (!rtl) { writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice(1);"); writer.WriteLine($"pos++;"); } else { writer.WriteLine($"pos--;"); } } } void EmitNonBacktrackingRepeater(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.M == node.N, $"Unexpected M={node.M} == N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(!analysis.MayBacktrack(node.Child(0)), $"Expected non-backtracking node {node.Kind}"); // Ensure every iteration of the loop sees a consistent value. TransferSliceStaticPosToPos(); // Loop M==N times to match the child exactly that numbers of times. string i = ReserveName("loop_iteration"); using (EmitBlock(writer, $"for (int {i} = 0; {i} < {node.M}; {i}++)")) { EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // make sure static the static position remains at 0 for subsequent constructs } } void EmitLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); string originalDoneLabel = doneLabel; string startingPos = ReserveName("loop_starting_pos"); string iterationCount = ReserveName("loop_iteration"); string body = ReserveName("LoopBody"); string endLoop = ReserveName("LoopEnd"); additionalDeclarations.Add($"int {iterationCount} = 0, {startingPos} = 0;"); writer.WriteLine($"{iterationCount} = 0;"); writer.WriteLine($"{startingPos} = pos;"); writer.WriteLine(); // Iteration body MarkLabel(body, emitSemicolon: false); EmitTimeoutCheck(writer, hasTimeout); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackPush(expressionHasCaptures ? new[] { "base.Crawlpos()", startingPos, "pos" } : new[] { startingPos, "pos" }); writer.WriteLine(); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. writer.WriteLine($"{startingPos} = pos;"); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. writer.WriteLine($"{iterationCount}++;"); writer.WriteLine(); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. string iterationFailedLabel = ReserveName("LoopIterationNoMatch"); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); writer.WriteLine(); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 bool childBacktracks = doneLabel != iterationFailedLabel; // Loop condition. Continue iterating greedily if we've not yet reached the maximum. We also need to stop // iterating if the iteration matched empty and we already hit the minimum number of iterations. using (EmitBlock(writer, (minIterations > 0, maxIterations == int.MaxValue) switch { (true, true) => $"if (pos != {startingPos} || {CountIsLessThan(iterationCount, minIterations)})", (true, false) => $"if ((pos != {startingPos} || {CountIsLessThan(iterationCount, minIterations)}) && {CountIsLessThan(iterationCount, maxIterations)})", (false, true) => $"if (pos != {startingPos})", (false, false) => $"if (pos != {startingPos} && {CountIsLessThan(iterationCount, maxIterations)})", })) { Goto(body); } // We've matched as many iterations as we can with this configuration. Jump to what comes after the loop. Goto(endLoop); writer.WriteLine(); // Now handle what happens when an iteration fails, which could be an initial failure or it // could be while backtracking. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel, emitSemicolon: false); writer.WriteLine($"{iterationCount}--;"); using (EmitBlock(writer, $"if ({iterationCount} < 0)")) { Goto(originalDoneLabel); } EmitStackPop("pos", startingPos); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } SliceInputSpan(writer); if (minIterations > 0) { using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, minIterations)})")) { Goto(childBacktracks ? doneLabel : originalDoneLabel); } } if (isAtomic) { doneLabel = originalDoneLabel; MarkLabel(endLoop); } else { if (childBacktracks) { Goto(endLoop); writer.WriteLine(); string backtrack = ReserveName("LoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } Goto(doneLabel); doneLabel = backtrack; } MarkLabel(endLoop); if (node.IsInLoop()) { writer.WriteLine(); // Store the loop's state EmitStackPush(startingPos, iterationCount); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label string backtrack = ReserveName("LoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(iterationCount, startingPos); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } } // Gets a comparison for whether the value is less than the upper bound. static string CountIsLessThan(string value, int exclusiveUpper) => exclusiveUpper == 1 ? $"{value} == 0" : $"{value} < {exclusiveUpper}"; // Emits code to unwind the capture stack until the crawl position specified in the provided local. void EmitUncaptureUntil(string capturepos) { string name = "UncaptureUntil"; if (!additionalLocalFunctions.ContainsKey(name)) { var lines = new string[9]; lines[0] = "// <summary>Undo captures until we reach the specified capture position.</summary>"; lines[1] = "[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"void {name}(int capturepos)"; lines[3] = "{"; lines[4] = " while (base.Crawlpos() > capturepos)"; lines[5] = " {"; lines[6] = " base.Uncapture();"; lines[7] = " }"; lines[8] = "}"; additionalLocalFunctions.Add(name, lines); } writer.WriteLine($"{name}({capturepos});"); } /// <summary>Pushes values on to the backtracking stack.</summary> void EmitStackPush(params string[] args) { Debug.Assert(args.Length is >= 1); string function = $"StackPush{args.Length}"; additionalDeclarations.Add("int stackpos = 0;"); if (!additionalLocalFunctions.ContainsKey(function)) { var lines = new string[24 + args.Length]; lines[0] = $"// <summary>Push {args.Length} value{(args.Length == 1 ? "" : "s")} onto the backtracking stack.</summary>"; lines[1] = $"[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"static void {function}(ref int[] stack, ref int pos{FormatN(", int arg{0}", args.Length)})"; lines[3] = $"{{"; lines[4] = $" // If there's space available for {(args.Length > 1 ? $"all {args.Length} values, store them" : "the value, store it")}."; lines[5] = $" int[] s = stack;"; lines[6] = $" int p = pos;"; lines[7] = $" if ((uint){(args.Length > 1 ? $"(p + {args.Length - 1})" : "p")} < (uint)s.Length)"; lines[8] = $" {{"; for (int i = 0; i < args.Length; i++) { lines[9 + i] = $" s[p{(i == 0 ? "" : $" + {i}")}] = arg{i};"; } lines[9 + args.Length] = args.Length > 1 ? $" pos += {args.Length};" : " pos++;"; lines[10 + args.Length] = $" return;"; lines[11 + args.Length] = $" }}"; lines[12 + args.Length] = $""; lines[13 + args.Length] = $" // Otherwise, resize the stack to make room and try again."; lines[14 + args.Length] = $" WithResize(ref stack, ref pos{FormatN(", arg{0}", args.Length)});"; lines[15 + args.Length] = $""; lines[16 + args.Length] = $" // <summary>Resize the backtracking stack array and push {args.Length} value{(args.Length == 1 ? "" : "s")} onto the stack.</summary>"; lines[17 + args.Length] = $" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]"; lines[18 + args.Length] = $" static void WithResize(ref int[] stack, ref int pos{FormatN(", int arg{0}", args.Length)})"; lines[19 + args.Length] = $" {{"; lines[20 + args.Length] = $" global::System.Array.Resize(ref stack, (pos + {args.Length - 1}) * 2);"; lines[21 + args.Length] = $" {function}(ref stack, ref pos{FormatN(", arg{0}", args.Length)});"; lines[22 + args.Length] = $" }}"; lines[23 + args.Length] = $"}}"; additionalLocalFunctions.Add(function, lines); } writer.WriteLine($"{function}(ref base.runstack!, ref stackpos, {string.Join(", ", args)});"); } /// <summary>Pops values from the backtracking stack into the specified locations.</summary> void EmitStackPop(params string[] args) { Debug.Assert(args.Length is >= 1); if (args.Length == 1) { writer.WriteLine($"{args[0]} = {StackPop()};"); return; } string function = $"StackPop{args.Length}"; if (!additionalLocalFunctions.ContainsKey(function)) { var lines = new string[5 + args.Length]; lines[0] = $"// <summary>Pop {args.Length} value{(args.Length == 1 ? "" : "s")} from the backtracking stack.</summary>"; lines[1] = $"[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"static void {function}(int[] stack, ref int pos{FormatN(", out int arg{0}", args.Length)})"; lines[3] = $"{{"; for (int i = 0; i < args.Length; i++) { lines[4 + i] = $" arg{i} = stack[--pos];"; } lines[4 + args.Length] = $"}}"; additionalLocalFunctions.Add(function, lines); } writer.WriteLine($"{function}(base.runstack, ref stackpos, out {string.Join(", out ", args)});"); } /// <summary>Expression for popping the next item from the backtracking stack.</summary> string StackPop() => "base.runstack![--stackpos]"; /// <summary>Concatenates the strings resulting from formatting the format string with the values [0, count).</summary> static string FormatN(string format, int count) => string.Concat(from i in Enumerable.Range(0, count) select string.Format(format, i)); } private static bool EmitLoopTimeoutCounterIfNeeded(IndentedTextWriter writer, RegexMethod rm) { if (rm.MatchTimeout != Timeout.Infinite) { writer.WriteLine("int loopTimeoutCounter = 0;"); return true; } return false; } /// <summary>Emits a timeout check.</summary> private static void EmitTimeoutCheck(IndentedTextWriter writer, bool hasTimeout) { const int LoopTimeoutCheckCount = 2048; // A conservative value to guarantee the correct timeout handling. if (hasTimeout) { // Increment counter for each loop iteration. // Emit code to check the timeout every 2048th iteration. using (EmitBlock(writer, $"if (++loopTimeoutCounter == {LoopTimeoutCheckCount})")) { writer.WriteLine("loopTimeoutCounter = 0;"); writer.WriteLine("base.CheckTimeout();"); } writer.WriteLine(); } } private static bool EmitInitializeCultureForTryMatchAtCurrentPositionIfNecessary(IndentedTextWriter writer, RegexMethod rm, AnalysisResults analysis) { if (analysis.HasIgnoreCase && ((RegexOptions)rm.Options & RegexOptions.CultureInvariant) == 0) { writer.WriteLine("global::System.Globalization.TextInfo textInfo = global::System.Globalization.CultureInfo.CurrentCulture.TextInfo;"); return true; } return false; } private static bool UseToLowerInvariant(bool hasTextInfo, RegexOptions options) => !hasTextInfo || (options & RegexOptions.CultureInvariant) != 0; private static string ToLower(bool hasTextInfo, RegexOptions options, string expression) => UseToLowerInvariant(hasTextInfo, options) ? $"char.ToLowerInvariant({expression})" : $"textInfo.ToLower({expression})"; private static string ToLowerIfNeeded(bool hasTextInfo, RegexOptions options, string expression, bool toLower) => toLower ? ToLower(hasTextInfo, options, expression) : expression; private static string MatchCharacterClass(bool hasTextInfo, RegexOptions options, string chExpr, string charClass, bool caseInsensitive, bool negate, HashSet<string> additionalDeclarations, ref RequiredHelperFunctions requiredHelpers) { // We need to perform the equivalent of calling RegexRunner.CharInClass(ch, charClass), // but that call is relatively expensive. Before we fall back to it, we try to optimize // some common cases for which we can do much better, such as known character classes // for which we can call a dedicated method, or a fast-path for ASCII using a lookup table. // First, see if the char class is a built-in one for which there's a better function // we can just call directly. Everything in this section must work correctly for both // case-sensitive and case-insensitive modes, regardless of culture. switch (charClass) { case RegexCharClass.AnyClass: // ideally this could just be "return true;", but we need to evaluate the expression for its side effects return $"({chExpr} {(negate ? "<" : ">=")} 0)"; // a char is unsigned and thus won't ever be negative case RegexCharClass.DigitClass: case RegexCharClass.NotDigitClass: negate ^= charClass == RegexCharClass.NotDigitClass; return $"{(negate ? "!" : "")}char.IsDigit({chExpr})"; case RegexCharClass.SpaceClass: case RegexCharClass.NotSpaceClass: negate ^= charClass == RegexCharClass.NotSpaceClass; return $"{(negate ? "!" : "")}char.IsWhiteSpace({chExpr})"; case RegexCharClass.WordClass: case RegexCharClass.NotWordClass: requiredHelpers |= RequiredHelperFunctions.IsWordChar; negate ^= charClass == RegexCharClass.NotWordClass; return $"{(negate ? "!" : "")}IsWordChar({chExpr})"; } // If we're meant to be doing a case-insensitive lookup, and if we're not using the invariant culture, // lowercase the input. If we're using the invariant culture, we may still end up calling ToLower later // on, but we may also be able to avoid it, in particular in the case of our lookup table, where we can // generate the lookup table already factoring in the invariant case sensitivity. There are multiple // special-code paths between here and the lookup table, but we only take those if invariant is false; // if it were true, they'd need to use CallToLower(). bool invariant = false; if (caseInsensitive) { invariant = UseToLowerInvariant(hasTextInfo, options); if (!invariant) { chExpr = ToLower(hasTextInfo, options, chExpr); } } // Next, handle simple sets of one range, e.g. [A-Z], [0-9], etc. This includes some built-in classes, like ECMADigitClass. if (!invariant && RegexCharClass.TryGetSingleRange(charClass, out char lowInclusive, out char highInclusive)) { negate ^= RegexCharClass.IsNegated(charClass); return lowInclusive == highInclusive ? $"({chExpr} {(negate ? "!=" : "==")} {Literal(lowInclusive)})" : $"(((uint){chExpr}) - {Literal(lowInclusive)} {(negate ? ">" : "<=")} (uint)({Literal(highInclusive)} - {Literal(lowInclusive)}))"; } // Next if the character class contains nothing but a single Unicode category, we can calle char.GetUnicodeCategory and // compare against it. It has a fast-lookup path for ASCII, so is as good or better than any lookup we'd generate (plus // we get smaller code), and it's what we'd do for the fallback (which we get to avoid generating) as part of CharInClass. if (!invariant && RegexCharClass.TryGetSingleUnicodeCategory(charClass, out UnicodeCategory category, out bool negated)) { negate ^= negated; return $"(char.GetUnicodeCategory({chExpr}) {(negate ? "!=" : "==")} global::System.Globalization.UnicodeCategory.{category})"; } // Next, if there's only 2 or 3 chars in the set (fairly common due to the sets we create for prefixes), // it may be cheaper and smaller to compare against each than it is to use a lookup table. We can also special-case // the very common case with case insensitivity of two characters next to each other being the upper and lowercase // ASCII variants of each other, in which case we can use bit manipulation to avoid a comparison. if (!invariant && !RegexCharClass.IsNegated(charClass)) { Span<char> setChars = stackalloc char[3]; int mask; switch (RegexCharClass.GetSetChars(charClass, setChars)) { case 2: if (RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out mask)) { return $"(({chExpr} | 0x{mask:X}) {(negate ? "!=" : "==")} {Literal((char)(setChars[1] | mask))})"; } additionalDeclarations.Add("char ch;"); return negate ? $"(((ch = {chExpr}) != {Literal(setChars[0])}) & (ch != {Literal(setChars[1])}))" : $"(((ch = {chExpr}) == {Literal(setChars[0])}) | (ch == {Literal(setChars[1])}))"; case 3: additionalDeclarations.Add("char ch;"); return (negate, RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out mask)) switch { (false, false) => $"(((ch = {chExpr}) == {Literal(setChars[0])}) | (ch == {Literal(setChars[1])}) | (ch == {Literal(setChars[2])}))", (true, false) => $"(((ch = {chExpr}) != {Literal(setChars[0])}) & (ch != {Literal(setChars[1])}) & (ch != {Literal(setChars[2])}))", (false, true) => $"((((ch = {chExpr}) | 0x{mask:X}) == {Literal((char)(setChars[1] | mask))}) | (ch == {Literal(setChars[2])}))", (true, true) => $"((((ch = {chExpr}) | 0x{mask:X}) != {Literal((char)(setChars[1] | mask))}) & (ch != {Literal(setChars[2])}))", }; } } // All options after this point require a ch local. additionalDeclarations.Add("char ch;"); // Analyze the character set more to determine what code to generate. RegexCharClass.CharClassAnalysisResults analysis = RegexCharClass.Analyze(charClass); if (!invariant) // if we're being asked to do a case insensitive, invariant comparison, use the lookup table { if (analysis.ContainsNoAscii) { // We determined that the character class contains only non-ASCII, // for example if the class were [\p{IsGreek}\p{IsGreekExtended}], which is // the same as [\u0370-\u03FF\u1F00-1FFF]. (In the future, we could possibly // extend the analysis to produce a known lower-bound and compare against // that rather than always using 128 as the pivot point.) return negate ? $"((ch = {chExpr}) < 128 || !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))" : $"((ch = {chExpr}) >= 128 && global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))"; } if (analysis.AllAsciiContained) { // We determined that every ASCII character is in the class, for example // if the class were the negated example from case 1 above: // [^\p{IsGreek}\p{IsGreekExtended}]. return negate ? $"((ch = {chExpr}) >= 128 && !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))" : $"((ch = {chExpr}) < 128 || global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))"; } } // Now, our big hammer is to generate a lookup table that lets us quickly index by character into a yes/no // answer as to whether the character is in the target character class. However, we don't want to store // a lookup table for every possible character for every character class in the regular expression; at one // bit for each of 65K characters, that would be an 8K bitmap per character class. Instead, we handle the // common case of ASCII input via such a lookup table, which at one bit for each of 128 characters is only // 16 bytes per character class. We of course still need to be able to handle inputs that aren't ASCII, so // we check the input against 128, and have a fallback if the input is >= to it. Determining the right // fallback could itself be expensive. For example, if it's possible that a value >= 128 could match the // character class, we output a call to RegexRunner.CharInClass, but we don't want to have to enumerate the // entire character class evaluating every character against it, just to determine whether it's a match. // Instead, we employ some quick heuristics that will always ensure we provide a correct answer even if // we could have sometimes generated better code to give that answer. // Generate the lookup table to store 128 answers as bits. We use a const string instead of a byte[] / static // data property because it lets IL emit handle all the details for us. string bitVectorString = StringExtensions.Create(8, (charClass, invariant), static (dest, state) => // String length is 8 chars == 16 bytes == 128 bits. { for (int i = 0; i < 128; i++) { char c = (char)i; bool isSet = state.invariant ? RegexCharClass.CharInClass(char.ToLowerInvariant(c), state.charClass) : RegexCharClass.CharInClass(c, state.charClass); if (isSet) { dest[i >> 4] |= (char)(1 << (i & 0xF)); } } }); // We determined that the character class may contain ASCII, so we // output the lookup against the lookup table. if (analysis.ContainsOnlyAscii) { // We know that all inputs that could match are ASCII, for example if the // character class were [A-Za-z0-9], so since the ch is now known to be >= 128, we // can just fail the comparison. return negate ? $"((ch = {chExpr}) >= 128 || ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0)" : $"((ch = {chExpr}) < 128 && ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0)"; } if (analysis.AllNonAsciiContained) { // We know that all non-ASCII inputs match, for example if the character // class were [^\r\n], so since we just determined the ch to be >= 128, we can just // give back success. return negate ? $"((ch = {chExpr}) < 128 && ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0)" : $"((ch = {chExpr}) >= 128 || ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0)"; } // We know that the whole class wasn't ASCII, and we don't know anything about the non-ASCII // characters other than that some might be included, for example if the character class // were [\w\d], so since ch >= 128, we need to fall back to calling CharInClass. return (negate, invariant) switch { (false, false) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0 : global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))", (true, false) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0 : !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))", (false, true) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0 : global::System.Text.RegularExpressions.RegexRunner.CharInClass(char.ToLowerInvariant((char)ch), {Literal(charClass)}))", (true, true) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0 : !global::System.Text.RegularExpressions.RegexRunner.CharInClass(char.ToLowerInvariant((char)ch), {Literal(charClass)}))", }; } /// <summary> /// Replaces <see cref="AdditionalDeclarationsPlaceholder"/> in <paramref name="writer"/> with /// all of the variable declarations in <paramref name="declarations"/>. /// </summary> /// <param name="writer">The writer around a StringWriter to have additional declarations inserted into.</param> /// <param name="declarations">The additional declarations to insert.</param> /// <param name="position">The position into the writer at which to insert the additional declarations.</param> /// <param name="indent">The indentation to use for the additional declarations.</param> private static void ReplaceAdditionalDeclarations(IndentedTextWriter writer, HashSet<string> declarations, int position, int indent) { if (declarations.Count != 0) { var tmp = new StringBuilder(); foreach (string decl in declarations.OrderBy(s => s)) { for (int i = 0; i < indent; i++) { tmp.Append(IndentedTextWriter.DefaultTabString); } tmp.AppendLine(decl); } ((StringWriter)writer.InnerWriter).GetStringBuilder().Insert(position, tmp.ToString()); } } /// <summary>Formats the character as valid C#.</summary> private static string Literal(char c) => SymbolDisplay.FormatLiteral(c, quote: true); /// <summary>Formats the string as valid C#.</summary> private static string Literal(string s) => SymbolDisplay.FormatLiteral(s, quote: true); private static string Literal(RegexOptions options) { string s = options.ToString(); if (int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out _)) { // The options were formatted as an int, which means the runtime couldn't // produce a textual representation. So just output casting the value as an int. Debug.Fail("This shouldn't happen, as we should only get to the point of emitting code if RegexOptions was valid."); return $"(global::System.Text.RegularExpressions.RegexOptions)({(int)options})"; } // Parse the runtime-generated "Option1, Option2" into each piece and then concat // them back together. string[] parts = s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < parts.Length; i++) { parts[i] = "global::System.Text.RegularExpressions.RegexOptions." + parts[i].Trim(); } return string.Join(" | ", parts); } /// <summary>Gets a textual description of the node fit for rendering in a comment in source.</summary> private static string DescribeNode(RegexNode node, AnalysisResults analysis) { bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; return node.Kind switch { RegexNodeKind.Alternate => $"Match with {node.ChildCount()} alternative expressions{(analysis.IsAtomicByAncestor(node) ? ", atomically" : "")}.", RegexNodeKind.Atomic => $"Atomic group.", RegexNodeKind.Beginning => "Match if at the beginning of the string.", RegexNodeKind.Bol => "Match if at the beginning of a line.", RegexNodeKind.Boundary => $"Match if at a word boundary.", RegexNodeKind.Capture when node.M == -1 && node.N != -1 => $"Non-capturing balancing group. Uncaptures the {DescribeCapture(node.N, analysis)}.", RegexNodeKind.Capture when node.N != -1 => $"Balancing group. Captures the {DescribeCapture(node.M, analysis)} and uncaptures the {DescribeCapture(node.N, analysis)}.", RegexNodeKind.Capture when node.N == -1 => $"{DescribeCapture(node.M, analysis)}.", RegexNodeKind.Concatenate => "Match a sequence of expressions.", RegexNodeKind.ECMABoundary => $"Match if at a word boundary (according to ECMAScript rules).", RegexNodeKind.Empty => $"Match an empty string.", RegexNodeKind.End => "Match if at the end of the string.", RegexNodeKind.EndZ => "Match if at the end of the string or if before an ending newline.", RegexNodeKind.Eol => "Match if at the end of a line.", RegexNodeKind.Loop or RegexNodeKind.Lazyloop => node.M == 0 && node.N == 1 ? $"Optional ({(node.Kind is RegexNodeKind.Loop ? "greedy" : "lazy")})." : $"Loop {DescribeLoop(node, analysis)}.", RegexNodeKind.Multi => $"Match the string {Literal(node.Str!)}{(rtl ? " backwards" : "")}.", RegexNodeKind.NonBoundary => $"Match if at anything other than a word boundary.", RegexNodeKind.NonECMABoundary => $"Match if at anything other than a word boundary (according to ECMAScript rules).", RegexNodeKind.Nothing => $"Fail to match.", RegexNodeKind.Notone => $"Match any character other than {Literal(node.Ch)}{(rtl ? " backwards" : "")}.", RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy => $"Match a character other than {Literal(node.Ch)} {DescribeLoop(node, analysis)}.", RegexNodeKind.One => $"Match {Literal(node.Ch)}{(rtl ? " backwards" : "")}.", RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy => $"Match {Literal(node.Ch)} {DescribeLoop(node, analysis)}.", RegexNodeKind.NegativeLookaround => $"Zero-width negative {(rtl ? "lookbehind" : "lookahead")}.", RegexNodeKind.Backreference => $"Match the same text as matched by the {DescribeCapture(node.M, analysis)}.", RegexNodeKind.PositiveLookaround => $"Zero-width positive {(rtl ? "lookbehind" : "lookahead")}.", RegexNodeKind.Set => $"Match {DescribeSet(node.Str!)}{(rtl ? " backwards" : "")}.", RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy => $"Match {DescribeSet(node.Str!)} {DescribeLoop(node, analysis)}.", RegexNodeKind.Start => "Match if at the start position.", RegexNodeKind.ExpressionConditional => $"Conditionally match one of two expressions depending on whether an initial expression matches.", RegexNodeKind.BackreferenceConditional => $"Conditionally match one of two expressions depending on whether the {DescribeCapture(node.M, analysis)} matched.", RegexNodeKind.UpdateBumpalong => $"Advance the next matching position.", _ => $"Unknown node type {node.Kind}", }; } /// <summary>Gets an identifer to describe a capture group.</summary> private static string DescribeCapture(int capNum, AnalysisResults analysis) { // If we can get a capture name from the captures collection and it's not just a numerical representation of the group, use it. string name = RegexParser.GroupNameFromNumber(analysis.RegexTree.CaptureNumberSparseMapping, analysis.RegexTree.CaptureNames, analysis.RegexTree.CaptureCount, capNum); if (!string.IsNullOrEmpty(name) && (!int.TryParse(name, out int id) || id != capNum)) { name = Literal(name); } else { // Otherwise, create a numerical description of the capture group. int tens = capNum % 10; name = tens is >= 1 and <= 3 && capNum % 100 is < 10 or > 20 ? // Ends in 1, 2, 3 but not 11, 12, or 13 tens switch { 1 => $"{capNum}st", 2 => $"{capNum}nd", _ => $"{capNum}rd", } : $"{capNum}th"; } return $"{name} capture group"; } /// <summary>Gets a textual description of what characters match a set.</summary> private static string DescribeSet(string charClass) => charClass switch { RegexCharClass.AnyClass => "any character", RegexCharClass.DigitClass => "a Unicode digit", RegexCharClass.ECMADigitClass => "'0' through '9'", RegexCharClass.ECMASpaceClass => "a whitespace character (ECMA)", RegexCharClass.ECMAWordClass => "a word character (ECMA)", RegexCharClass.NotDigitClass => "any character other than a Unicode digit", RegexCharClass.NotECMADigitClass => "any character other than '0' through '9'", RegexCharClass.NotECMASpaceClass => "any character other than a space character (ECMA)", RegexCharClass.NotECMAWordClass => "any character other than a word character (ECMA)", RegexCharClass.NotSpaceClass => "any character other than a space character", RegexCharClass.NotWordClass => "any character other than a word character", RegexCharClass.SpaceClass => "a whitespace character", RegexCharClass.WordClass => "a word character", _ => $"a character in the set {RegexCharClass.DescribeSet(charClass)}", }; /// <summary>Writes a textual description of the node tree fit for rending in source.</summary> /// <param name="writer">The writer to which the description should be written.</param> /// <param name="node">The node being written.</param> /// <param name="prefix">The prefix to write at the beginning of every line, including a "//" for a comment.</param> /// <param name="analyses">Analysis of the tree</param> /// <param name="depth">The depth of the current node.</param> private static void DescribeExpression(TextWriter writer, RegexNode node, string prefix, AnalysisResults analysis, int depth = 0) { bool skip = node.Kind switch { // For concatenations, flatten the contents into the parent, but only if the parent isn't a form of alternation, // where each branch is considered to be independent rather than a concatenation. RegexNodeKind.Concatenate when node.Parent is not { Kind: RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional } => true, // For atomic, skip the node if we'll instead render the atomic label as part of rendering the child. RegexNodeKind.Atomic when node.Child(0).Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop or RegexNodeKind.Alternate => true, // Don't skip anything else. _ => false, }; if (!skip) { string tag = node.Parent?.Kind switch { RegexNodeKind.ExpressionConditional when node.Parent.Child(0) == node => "Condition: ", RegexNodeKind.ExpressionConditional when node.Parent.Child(1) == node => "Matched: ", RegexNodeKind.ExpressionConditional when node.Parent.Child(2) == node => "Not Matched: ", RegexNodeKind.BackreferenceConditional when node.Parent.Child(0) == node => "Matched: ", RegexNodeKind.BackreferenceConditional when node.Parent.Child(1) == node => "Not Matched: ", _ => "", }; // Write out the line for the node. const char BulletPoint = '\u25CB'; writer.WriteLine($"{prefix}{new string(' ', depth * 4)}{BulletPoint} {tag}{DescribeNode(node, analysis)}"); } // Recur into each of its children. int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { int childDepth = skip ? depth : depth + 1; DescribeExpression(writer, node.Child(i), prefix, analysis, childDepth); } } /// <summary>Gets a textual description of a loop's style and bounds.</summary> private static string DescribeLoop(RegexNode node, AnalysisResults analysis) { string style = node.Kind switch { _ when node.M == node.N => "exactly", RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloopatomic => "atomically", RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop => "greedily", RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy => "lazily", RegexNodeKind.Loop => analysis.IsAtomicByAncestor(node) ? "greedily and atomically" : "greedily", _ /* RegexNodeKind.Lazyloop */ => analysis.IsAtomicByAncestor(node) ? "lazily and atomically" : "lazily", }; string bounds = node.M == node.N ? $" {node.M} times" : (node.M, node.N) switch { (0, int.MaxValue) => " any number of times", (1, int.MaxValue) => " at least once", (2, int.MaxValue) => " at least twice", (_, int.MaxValue) => $" at least {node.M} times", (0, 1) => ", optionally", (0, _) => $" at most {node.N} times", _ => $" at least {node.M} and at most {node.N} times" }; return style + bounds; } private static FinishEmitScope EmitScope(IndentedTextWriter writer, string title, bool faux = false) => EmitBlock(writer, $"// {title}", faux: faux); private static FinishEmitScope EmitBlock(IndentedTextWriter writer, string? clause, bool faux = false) { if (clause is not null) { writer.WriteLine(clause); } writer.WriteLine(faux ? "//{" : "{"); writer.Indent++; return new FinishEmitScope(writer, faux); } private static void EmitAdd(IndentedTextWriter writer, string variable, int value) { if (value == 0) { return; } writer.WriteLine( value == 1 ? $"{variable}++;" : value == -1 ? $"{variable}--;" : value > 0 ? $"{variable} += {value};" : value < 0 && value > int.MinValue ? $"{variable} -= {-value};" : $"{variable} += {value.ToString(CultureInfo.InvariantCulture)};"); } private readonly struct FinishEmitScope : IDisposable { private readonly IndentedTextWriter _writer; private readonly bool _faux; public FinishEmitScope(IndentedTextWriter writer, bool faux) { _writer = writer; _faux = faux; } public void Dispose() { if (_writer is not null) { _writer.Indent--; _writer.WriteLine(_faux ? "//}" : "}"); } } } /// <summary>Bit flags indicating which additional helpers should be emitted into the regex class.</summary> [Flags] private enum RequiredHelperFunctions { /// <summary>No additional functions are required.</summary> None = 0b0, /// <summary>The IsWordChar helper is required.</summary> IsWordChar = 0b1, /// <summary>The IsBoundary helper is required.</summary> IsBoundary = 0b10, /// <summary>The IsECMABoundary helper is required.</summary> IsECMABoundary = 0b100 } } }
1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCharClass.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.CompilerServices; using System.Threading; namespace System.Text.RegularExpressions { // The main function of RegexCharClass is as a builder to turn ranges, characters and // Unicode categories into a single string. This string is used as a black box // representation of a character class by the rest of Regex. The format is as follows. // // Char index Use // 0 Flags - currently this only holds the "negate" flag // 1 length of the string representing the "set" portion, e.g. [a-z0-9] only has a "set" // 2 length of the string representing the "category" portion, e.g. [\p{Lu}] only has a "category" // 3...m The set. These are a series of ranges which define the characters included in the set. // To determine if a given character is in the set, we binary search over this set of ranges // and see where the character should go. Based on whether the ending index is odd or even, // we know if the character is in the set. // m+1...n The categories. This is a list of UnicodeCategory enum values which describe categories // included in this class. /// <summary>Provides the "set of Unicode chars" functionality used by the regexp engine.</summary> internal sealed partial class RegexCharClass { // Constants internal const int FlagsIndex = 0; internal const int SetLengthIndex = 1; internal const int CategoryLengthIndex = 2; internal const int SetStartIndex = 3; // must be odd for subsequent logic to work private const string NullCharString = "\0"; private const char NullChar = '\0'; internal const char LastChar = '\uFFFF'; internal const short SpaceConst = 100; private const short NotSpaceConst = -100; private const string InternalRegexIgnoreCase = "__InternalRegexIgnoreCase__"; private const string Space = "\x64"; private const string NotSpace = "\uFF9C"; private const string Word = "\u0000\u0002\u0004\u0005\u0003\u0001\u0006\u0009\u0013\u0000"; private const string NotWord = "\u0000\uFFFE\uFFFC\uFFFB\uFFFD\uFFFF\uFFFA\uFFF7\uFFED\u0000"; internal const string SpaceClass = "\u0000\u0000\u0001\u0064"; internal const string NotSpaceClass = "\u0001\u0000\u0001\u0064"; internal const string WordClass = "\u0000\u0000\u000A\u0000\u0002\u0004\u0005\u0003\u0001\u0006\u0009\u0013\u0000"; internal const string NotWordClass = "\u0001\u0000\u000A\u0000\u0002\u0004\u0005\u0003\u0001\u0006\u0009\u0013\u0000"; internal const string DigitClass = "\u0000\u0000\u0001\u0009"; internal const string NotDigitClass = "\u0000\u0000\u0001\uFFF7"; private const string ECMASpaceSet = "\u0009\u000E\u0020\u0021"; private const string NotECMASpaceSet = "\0\u0009\u000E\u0020\u0021"; private const string ECMAWordSet = "\u0030\u003A\u0041\u005B\u005F\u0060\u0061\u007B\u0130\u0131"; private const string NotECMAWordSet = "\0\u0030\u003A\u0041\u005B\u005F\u0060\u0061\u007B\u0130\u0131"; private const string ECMADigitSet = "\u0030\u003A"; private const string NotECMADigitSet = "\0\u0030\u003A"; internal const string ECMASpaceClass = "\x00\x04\x00" + ECMASpaceSet; internal const string NotECMASpaceClass = "\x01\x04\x00" + ECMASpaceSet; internal const string ECMAWordClass = "\x00\x0A\x00" + ECMAWordSet; internal const string NotECMAWordClass = "\x01\x0A\x00" + ECMAWordSet; internal const string ECMADigitClass = "\x00\x02\x00" + ECMADigitSet; internal const string NotECMADigitClass = "\x01\x02\x00" + ECMADigitSet; internal const string AnyClass = "\x00\x01\x00\x00"; private const string EmptyClass = "\x00\x00\x00"; // UnicodeCategory is zero based, so we add one to each value and subtract it off later private const int DefinedCategoriesCapacity = 38; private static readonly Dictionary<string, string> s_definedCategories = new Dictionary<string, string>(DefinedCategoriesCapacity) { // Others { "Cc", "\u000F" }, // UnicodeCategory.Control + 1 { "Cf", "\u0010" }, // UnicodeCategory.Format + 1 { "Cn", "\u001E" }, // UnicodeCategory.OtherNotAssigned + 1 { "Co", "\u0012" }, // UnicodeCategory.PrivateUse + 1 { "Cs", "\u0011" }, // UnicodeCategory.Surrogate + 1 { "C", "\u0000\u000F\u0010\u001E\u0012\u0011\u0000" }, // Letters { "Ll", "\u0002" }, // UnicodeCategory.LowercaseLetter + 1 { "Lm", "\u0004" }, // UnicodeCategory.ModifierLetter + 1 { "Lo", "\u0005" }, // UnicodeCategory.OtherLetter + 1 { "Lt", "\u0003" }, // UnicodeCategory.TitlecaseLetter + 1 { "Lu", "\u0001" }, // UnicodeCategory.UppercaseLetter + 1 { "L", "\u0000\u0002\u0004\u0005\u0003\u0001\u0000" }, // InternalRegexIgnoreCase = {LowercaseLetter} OR {TitlecaseLetter} OR {UppercaseLetter} // !!!This category should only ever be used in conjunction with RegexOptions.IgnoreCase code paths!!! { "__InternalRegexIgnoreCase__", "\u0000\u0002\u0003\u0001\u0000" }, // Marks { "Mc", "\u0007" }, // UnicodeCategory.SpacingCombiningMark + 1 { "Me", "\u0008" }, // UnicodeCategory.EnclosingMark + 1 { "Mn", "\u0006" }, // UnicodeCategory.NonSpacingMark + 1 { "M", "\u0000\u0007\u0008\u0006\u0000" }, // Numbers { "Nd", "\u0009" }, // UnicodeCategory.DecimalDigitNumber + 1 { "Nl", "\u000A" }, // UnicodeCategory.LetterNumber + 1 { "No", "\u000B" }, // UnicodeCategory.OtherNumber + 1 { "N", "\u0000\u0009\u000A\u000B\u0000" }, // Punctuation { "Pc", "\u0013" }, // UnicodeCategory.ConnectorPunctuation + 1 { "Pd", "\u0014" }, // UnicodeCategory.DashPunctuation + 1 { "Pe", "\u0016" }, // UnicodeCategory.ClosePunctuation + 1 { "Po", "\u0019" }, // UnicodeCategory.OtherPunctuation + 1 { "Ps", "\u0015" }, // UnicodeCategory.OpenPunctuation + 1 { "Pf", "\u0018" }, // UnicodeCategory.FinalQuotePunctuation + 1 { "Pi", "\u0017" }, // UnicodeCategory.InitialQuotePunctuation + 1 { "P", "\u0000\u0013\u0014\u0016\u0019\u0015\u0018\u0017\u0000" }, // Symbols { "Sc", "\u001B" }, // UnicodeCategory.CurrencySymbol + 1 { "Sk", "\u001C" }, // UnicodeCategory.ModifierSymbol + 1 { "Sm", "\u001A" }, // UnicodeCategory.MathSymbol + 1 { "So", "\u001D" }, // UnicodeCategory.OtherSymbol + 1 { "S", "\u0000\u001B\u001C\u001A\u001D\u0000" }, // Separators { "Zl", "\u000D" }, // UnicodeCategory.LineSeparator + 1 { "Zp", "\u000E" }, // UnicodeCategory.ParagraphSeparator + 1 { "Zs", "\u000C" }, // UnicodeCategory.SpaceSeparator + 1 { "Z", "\u0000\u000D\u000E\u000C\u0000" }, }; /* * The property table contains all the block definitions defined in the * XML schema spec (http://www.w3.org/TR/2001/PR-xmlschema-2-20010316/#charcter-classes), Unicode 4.0 spec (www.unicode.org), * and Perl 5.6 (see Programming Perl, 3rd edition page 167). Three blocks defined by Perl (and here) may * not be in the Unicode: IsHighPrivateUseSurrogates, IsHighSurrogates, and IsLowSurrogates. * **/ // Has to be sorted by the first column private static readonly string[][] s_propTable = { new[] {"IsAlphabeticPresentationForms", "\uFB00\uFB50"}, new[] {"IsArabic", "\u0600\u0700"}, new[] {"IsArabicPresentationForms-A", "\uFB50\uFE00"}, new[] {"IsArabicPresentationForms-B", "\uFE70\uFF00"}, new[] {"IsArmenian", "\u0530\u0590"}, new[] {"IsArrows", "\u2190\u2200"}, new[] {"IsBasicLatin", "\u0000\u0080"}, new[] {"IsBengali", "\u0980\u0A00"}, new[] {"IsBlockElements", "\u2580\u25A0"}, new[] {"IsBopomofo", "\u3100\u3130"}, new[] {"IsBopomofoExtended", "\u31A0\u31C0"}, new[] {"IsBoxDrawing", "\u2500\u2580"}, new[] {"IsBraillePatterns", "\u2800\u2900"}, new[] {"IsBuhid", "\u1740\u1760"}, new[] {"IsCJKCompatibility", "\u3300\u3400"}, new[] {"IsCJKCompatibilityForms", "\uFE30\uFE50"}, new[] {"IsCJKCompatibilityIdeographs", "\uF900\uFB00"}, new[] {"IsCJKRadicalsSupplement", "\u2E80\u2F00"}, new[] {"IsCJKSymbolsandPunctuation", "\u3000\u3040"}, new[] {"IsCJKUnifiedIdeographs", "\u4E00\uA000"}, new[] {"IsCJKUnifiedIdeographsExtensionA", "\u3400\u4DC0"}, new[] {"IsCherokee", "\u13A0\u1400"}, new[] {"IsCombiningDiacriticalMarks", "\u0300\u0370"}, new[] {"IsCombiningDiacriticalMarksforSymbols", "\u20D0\u2100"}, new[] {"IsCombiningHalfMarks", "\uFE20\uFE30"}, new[] {"IsCombiningMarksforSymbols", "\u20D0\u2100"}, new[] {"IsControlPictures", "\u2400\u2440"}, new[] {"IsCurrencySymbols", "\u20A0\u20D0"}, new[] {"IsCyrillic", "\u0400\u0500"}, new[] {"IsCyrillicSupplement", "\u0500\u0530"}, new[] {"IsDevanagari", "\u0900\u0980"}, new[] {"IsDingbats", "\u2700\u27C0"}, new[] {"IsEnclosedAlphanumerics", "\u2460\u2500"}, new[] {"IsEnclosedCJKLettersandMonths", "\u3200\u3300"}, new[] {"IsEthiopic", "\u1200\u1380"}, new[] {"IsGeneralPunctuation", "\u2000\u2070"}, new[] {"IsGeometricShapes", "\u25A0\u2600"}, new[] {"IsGeorgian", "\u10A0\u1100"}, new[] {"IsGreek", "\u0370\u0400"}, new[] {"IsGreekExtended", "\u1F00\u2000"}, new[] {"IsGreekandCoptic", "\u0370\u0400"}, new[] {"IsGujarati", "\u0A80\u0B00"}, new[] {"IsGurmukhi", "\u0A00\u0A80"}, new[] {"IsHalfwidthandFullwidthForms", "\uFF00\uFFF0"}, new[] {"IsHangulCompatibilityJamo", "\u3130\u3190"}, new[] {"IsHangulJamo", "\u1100\u1200"}, new[] {"IsHangulSyllables", "\uAC00\uD7B0"}, new[] {"IsHanunoo", "\u1720\u1740"}, new[] {"IsHebrew", "\u0590\u0600"}, new[] {"IsHighPrivateUseSurrogates", "\uDB80\uDC00"}, new[] {"IsHighSurrogates", "\uD800\uDB80"}, new[] {"IsHiragana", "\u3040\u30A0"}, new[] {"IsIPAExtensions", "\u0250\u02B0"}, new[] {"IsIdeographicDescriptionCharacters", "\u2FF0\u3000"}, new[] {"IsKanbun", "\u3190\u31A0"}, new[] {"IsKangxiRadicals", "\u2F00\u2FE0"}, new[] {"IsKannada", "\u0C80\u0D00"}, new[] {"IsKatakana", "\u30A0\u3100"}, new[] {"IsKatakanaPhoneticExtensions", "\u31F0\u3200"}, new[] {"IsKhmer", "\u1780\u1800"}, new[] {"IsKhmerSymbols", "\u19E0\u1A00"}, new[] {"IsLao", "\u0E80\u0F00"}, new[] {"IsLatin-1Supplement", "\u0080\u0100"}, new[] {"IsLatinExtended-A", "\u0100\u0180"}, new[] {"IsLatinExtended-B", "\u0180\u0250"}, new[] {"IsLatinExtendedAdditional", "\u1E00\u1F00"}, new[] {"IsLetterlikeSymbols", "\u2100\u2150"}, new[] {"IsLimbu", "\u1900\u1950"}, new[] {"IsLowSurrogates", "\uDC00\uE000"}, new[] {"IsMalayalam", "\u0D00\u0D80"}, new[] {"IsMathematicalOperators", "\u2200\u2300"}, new[] {"IsMiscellaneousMathematicalSymbols-A", "\u27C0\u27F0"}, new[] {"IsMiscellaneousMathematicalSymbols-B", "\u2980\u2A00"}, new[] {"IsMiscellaneousSymbols", "\u2600\u2700"}, new[] {"IsMiscellaneousSymbolsandArrows", "\u2B00\u2C00"}, new[] {"IsMiscellaneousTechnical", "\u2300\u2400"}, new[] {"IsMongolian", "\u1800\u18B0"}, new[] {"IsMyanmar", "\u1000\u10A0"}, new[] {"IsNumberForms", "\u2150\u2190"}, new[] {"IsOgham", "\u1680\u16A0"}, new[] {"IsOpticalCharacterRecognition", "\u2440\u2460"}, new[] {"IsOriya", "\u0B00\u0B80"}, new[] {"IsPhoneticExtensions", "\u1D00\u1D80"}, new[] {"IsPrivateUse", "\uE000\uF900"}, new[] {"IsPrivateUseArea", "\uE000\uF900"}, new[] {"IsRunic", "\u16A0\u1700"}, new[] {"IsSinhala", "\u0D80\u0E00"}, new[] {"IsSmallFormVariants", "\uFE50\uFE70"}, new[] {"IsSpacingModifierLetters", "\u02B0\u0300"}, new[] {"IsSpecials", "\uFFF0"}, new[] {"IsSuperscriptsandSubscripts", "\u2070\u20A0"}, new[] {"IsSupplementalArrows-A", "\u27F0\u2800"}, new[] {"IsSupplementalArrows-B", "\u2900\u2980"}, new[] {"IsSupplementalMathematicalOperators", "\u2A00\u2B00"}, new[] {"IsSyriac", "\u0700\u0750"}, new[] {"IsTagalog", "\u1700\u1720"}, new[] {"IsTagbanwa", "\u1760\u1780"}, new[] {"IsTaiLe", "\u1950\u1980"}, new[] {"IsTamil", "\u0B80\u0C00"}, new[] {"IsTelugu", "\u0C00\u0C80"}, new[] {"IsThaana", "\u0780\u07C0"}, new[] {"IsThai", "\u0E00\u0E80"}, new[] {"IsTibetan", "\u0F00\u1000"}, new[] {"IsUnifiedCanadianAboriginalSyllabics", "\u1400\u1680"}, new[] {"IsVariationSelectors", "\uFE00\uFE10"}, new[] {"IsYiRadicals", "\uA490\uA4D0"}, new[] {"IsYiSyllables", "\uA000\uA490"}, new[] {"IsYijingHexagramSymbols", "\u4DC0\u4E00"}, new[] {"_xmlC", /* Name Char */ "\u002D\u002F\u0030\u003B\u0041\u005B\u005F\u0060\u0061\u007B\u00B7\u00B8\u00C0\u00D7\u00D8\u00F7\u00F8\u0132\u0134\u013F\u0141\u0149\u014A\u017F\u0180\u01C4\u01CD\u01F1\u01F4\u01F6\u01FA\u0218\u0250\u02A9\u02BB\u02C2\u02D0\u02D2\u0300\u0346\u0360\u0362\u0386\u038B\u038C\u038D\u038E\u03A2\u03A3\u03CF\u03D0\u03D7\u03DA\u03DB\u03DC\u03DD\u03DE\u03DF\u03E0\u03E1\u03E2\u03F4\u0401\u040D\u040E\u0450\u0451\u045D\u045E\u0482\u0483\u0487\u0490\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04EC\u04EE\u04F6\u04F8\u04FA\u0531\u0557\u0559\u055A\u0561\u0587\u0591\u05A2\u05A3\u05BA\u05BB\u05BE\u05BF\u05C0\u05C1\u05C3\u05C4\u05C5\u05D0\u05EB\u05F0\u05F3\u0621\u063B\u0640\u0653\u0660\u066A\u0670\u06B8\u06BA\u06BF\u06C0\u06CF\u06D0\u06D4\u06D5\u06E9\u06EA\u06EE\u06F0\u06FA\u0901\u0904\u0905\u093A\u093C\u094E\u0951\u0955\u0958\u0964\u0966\u0970\u0981\u0984\u0985\u098D\u098F\u0991\u0993\u09A9\u09AA\u09B1\u09B2\u09B3\u09B6\u09BA\u09BC\u09BD\u09BE\u09C5\u09C7\u09C9\u09CB\u09CE\u09D7\u09D8\u09DC" +"\u09DE\u09DF\u09E4\u09E6\u09F2\u0A02\u0A03\u0A05\u0A0B\u0A0F\u0A11\u0A13\u0A29\u0A2A\u0A31\u0A32\u0A34\u0A35\u0A37\u0A38\u0A3A\u0A3C\u0A3D\u0A3E\u0A43\u0A47\u0A49\u0A4B\u0A4E\u0A59\u0A5D\u0A5E\u0A5F\u0A66\u0A75\u0A81\u0A84\u0A85\u0A8C\u0A8D\u0A8E\u0A8F\u0A92\u0A93\u0AA9\u0AAA\u0AB1\u0AB2\u0AB4\u0AB5\u0ABA\u0ABC\u0AC6\u0AC7\u0ACA\u0ACB\u0ACE\u0AE0\u0AE1\u0AE6\u0AF0\u0B01\u0B04\u0B05\u0B0D\u0B0F\u0B11\u0B13\u0B29\u0B2A\u0B31\u0B32\u0B34\u0B36\u0B3A\u0B3C\u0B44\u0B47\u0B49\u0B4B\u0B4E\u0B56\u0B58\u0B5C\u0B5E\u0B5F\u0B62\u0B66\u0B70\u0B82\u0B84\u0B85\u0B8B\u0B8E\u0B91\u0B92\u0B96\u0B99\u0B9B\u0B9C\u0B9D\u0B9E\u0BA0\u0BA3\u0BA5\u0BA8\u0BAB\u0BAE\u0BB6\u0BB7\u0BBA\u0BBE\u0BC3\u0BC6\u0BC9\u0BCA\u0BCE\u0BD7\u0BD8\u0BE7\u0BF0\u0C01\u0C04\u0C05\u0C0D\u0C0E\u0C11\u0C12\u0C29\u0C2A\u0C34\u0C35\u0C3A\u0C3E\u0C45\u0C46\u0C49\u0C4A\u0C4E\u0C55\u0C57\u0C60\u0C62\u0C66\u0C70\u0C82\u0C84\u0C85\u0C8D\u0C8E\u0C91\u0C92\u0CA9\u0CAA\u0CB4\u0CB5\u0CBA\u0CBE\u0CC5\u0CC6\u0CC9\u0CCA\u0CCE\u0CD5\u0CD7\u0CDE\u0CDF\u0CE0\u0CE2" +"\u0CE6\u0CF0\u0D02\u0D04\u0D05\u0D0D\u0D0E\u0D11\u0D12\u0D29\u0D2A\u0D3A\u0D3E\u0D44\u0D46\u0D49\u0D4A\u0D4E\u0D57\u0D58\u0D60\u0D62\u0D66\u0D70\u0E01\u0E2F\u0E30\u0E3B\u0E40\u0E4F\u0E50\u0E5A\u0E81\u0E83\u0E84\u0E85\u0E87\u0E89\u0E8A\u0E8B\u0E8D\u0E8E\u0E94\u0E98\u0E99\u0EA0\u0EA1\u0EA4\u0EA5\u0EA6\u0EA7\u0EA8\u0EAA\u0EAC\u0EAD\u0EAF\u0EB0\u0EBA\u0EBB\u0EBE\u0EC0\u0EC5\u0EC6\u0EC7\u0EC8\u0ECE\u0ED0\u0EDA\u0F18\u0F1A\u0F20\u0F2A\u0F35\u0F36\u0F37\u0F38\u0F39\u0F3A\u0F3E\u0F48\u0F49\u0F6A\u0F71\u0F85\u0F86\u0F8C\u0F90\u0F96\u0F97\u0F98\u0F99\u0FAE\u0FB1\u0FB8\u0FB9\u0FBA\u10A0\u10C6\u10D0\u10F7\u1100\u1101\u1102\u1104\u1105\u1108\u1109\u110A\u110B\u110D\u110E\u1113\u113C\u113D\u113E\u113F\u1140\u1141\u114C\u114D\u114E\u114F\u1150\u1151\u1154\u1156\u1159\u115A\u115F\u1162\u1163\u1164\u1165\u1166\u1167\u1168\u1169\u116A\u116D\u116F\u1172\u1174\u1175\u1176\u119E\u119F\u11A8\u11A9\u11AB\u11AC\u11AE\u11B0\u11B7\u11B9\u11BA\u11BB\u11BC\u11C3\u11EB\u11EC\u11F0\u11F1\u11F9\u11FA\u1E00\u1E9C\u1EA0\u1EFA\u1F00" +"\u1F16\u1F18\u1F1E\u1F20\u1F46\u1F48\u1F4E\u1F50\u1F58\u1F59\u1F5A\u1F5B\u1F5C\u1F5D\u1F5E\u1F5F\u1F7E\u1F80\u1FB5\u1FB6\u1FBD\u1FBE\u1FBF\u1FC2\u1FC5\u1FC6\u1FCD\u1FD0\u1FD4\u1FD6\u1FDC\u1FE0\u1FED\u1FF2\u1FF5\u1FF6\u1FFD\u20D0\u20DD\u20E1\u20E2\u2126\u2127\u212A\u212C\u212E\u212F\u2180\u2183\u3005\u3006\u3007\u3008\u3021\u3030\u3031\u3036\u3041\u3095\u3099\u309B\u309D\u309F\u30A1\u30FB\u30FC\u30FF\u3105\u312D\u4E00\u9FA6\uAC00\uD7A4"}, new[] {"_xmlD", "\u0030\u003A\u0660\u066A\u06F0\u06FA\u0966\u0970\u09E6\u09F0\u0A66\u0A70\u0AE6\u0AF0\u0B66\u0B70\u0BE7\u0BF0\u0C66\u0C70\u0CE6\u0CF0\u0D66\u0D70\u0E50\u0E5A\u0ED0\u0EDA\u0F20\u0F2A\u1040\u104A\u1369\u1372\u17E0\u17EA\u1810\u181A\uFF10\uFF1A"}, new[] {"_xmlI", /* Start Name Char */ "\u003A\u003B\u0041\u005B\u005F\u0060\u0061\u007B\u00C0\u00D7\u00D8\u00F7\u00F8\u0132\u0134\u013F\u0141\u0149\u014A\u017F\u0180\u01C4\u01CD\u01F1\u01F4\u01F6\u01FA\u0218\u0250\u02A9\u02BB\u02C2\u0386\u0387\u0388\u038B\u038C\u038D\u038E\u03A2\u03A3\u03CF\u03D0\u03D7\u03DA\u03DB\u03DC\u03DD\u03DE\u03DF\u03E0\u03E1\u03E2\u03F4\u0401\u040D\u040E\u0450\u0451\u045D\u045E\u0482\u0490\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04EC\u04EE\u04F6\u04F8\u04FA\u0531\u0557\u0559\u055A\u0561\u0587\u05D0\u05EB\u05F0\u05F3\u0621\u063B\u0641\u064B\u0671\u06B8\u06BA\u06BF\u06C0\u06CF\u06D0\u06D4\u06D5\u06D6\u06E5\u06E7\u0905\u093A\u093D\u093E\u0958\u0962\u0985\u098D\u098F\u0991\u0993\u09A9\u09AA\u09B1\u09B2\u09B3\u09B6\u09BA\u09DC\u09DE\u09DF\u09E2\u09F0\u09F2\u0A05\u0A0B\u0A0F\u0A11\u0A13\u0A29\u0A2A\u0A31\u0A32\u0A34\u0A35\u0A37\u0A38\u0A3A\u0A59\u0A5D\u0A5E\u0A5F\u0A72\u0A75\u0A85\u0A8C\u0A8D\u0A8E\u0A8F\u0A92\u0A93\u0AA9\u0AAA\u0AB1\u0AB2\u0AB4\u0AB5\u0ABA\u0ABD\u0ABE\u0AE0\u0AE1\u0B05\u0B0D\u0B0F" +"\u0B11\u0B13\u0B29\u0B2A\u0B31\u0B32\u0B34\u0B36\u0B3A\u0B3D\u0B3E\u0B5C\u0B5E\u0B5F\u0B62\u0B85\u0B8B\u0B8E\u0B91\u0B92\u0B96\u0B99\u0B9B\u0B9C\u0B9D\u0B9E\u0BA0\u0BA3\u0BA5\u0BA8\u0BAB\u0BAE\u0BB6\u0BB7\u0BBA\u0C05\u0C0D\u0C0E\u0C11\u0C12\u0C29\u0C2A\u0C34\u0C35\u0C3A\u0C60\u0C62\u0C85\u0C8D\u0C8E\u0C91\u0C92\u0CA9\u0CAA\u0CB4\u0CB5\u0CBA\u0CDE\u0CDF\u0CE0\u0CE2\u0D05\u0D0D\u0D0E\u0D11\u0D12\u0D29\u0D2A\u0D3A\u0D60\u0D62\u0E01\u0E2F\u0E30\u0E31\u0E32\u0E34\u0E40\u0E46\u0E81\u0E83\u0E84\u0E85\u0E87\u0E89\u0E8A\u0E8B\u0E8D\u0E8E\u0E94\u0E98\u0E99\u0EA0\u0EA1\u0EA4\u0EA5\u0EA6\u0EA7\u0EA8\u0EAA\u0EAC\u0EAD\u0EAF\u0EB0\u0EB1\u0EB2\u0EB4\u0EBD\u0EBE\u0EC0\u0EC5\u0F40\u0F48\u0F49\u0F6A\u10A0\u10C6\u10D0\u10F7\u1100\u1101\u1102\u1104\u1105\u1108\u1109\u110A\u110B\u110D\u110E\u1113\u113C\u113D\u113E\u113F\u1140\u1141\u114C\u114D\u114E\u114F\u1150\u1151\u1154\u1156\u1159\u115A\u115F\u1162\u1163\u1164\u1165\u1166\u1167\u1168\u1169\u116A\u116D\u116F\u1172\u1174\u1175\u1176\u119E\u119F\u11A8\u11A9\u11AB\u11AC" +"\u11AE\u11B0\u11B7\u11B9\u11BA\u11BB\u11BC\u11C3\u11EB\u11EC\u11F0\u11F1\u11F9\u11FA\u1E00\u1E9C\u1EA0\u1EFA\u1F00\u1F16\u1F18\u1F1E\u1F20\u1F46\u1F48\u1F4E\u1F50\u1F58\u1F59\u1F5A\u1F5B\u1F5C\u1F5D\u1F5E\u1F5F\u1F7E\u1F80\u1FB5\u1FB6\u1FBD\u1FBE\u1FBF\u1FC2\u1FC5\u1FC6\u1FCD\u1FD0\u1FD4\u1FD6\u1FDC\u1FE0\u1FED\u1FF2\u1FF5\u1FF6\u1FFD\u2126\u2127\u212A\u212C\u212E\u212F\u2180\u2183\u3007\u3008\u3021\u302A\u3041\u3095\u30A1\u30FB\u3105\u312D\u4E00\u9FA6\uAC00\uD7A4"}, new[] {"_xmlW", "\u0024\u0025\u002B\u002C\u0030\u003A\u003C\u003F\u0041\u005B\u005E\u005F\u0060\u007B\u007C\u007D\u007E\u007F\u00A2\u00AB\u00AC\u00AD\u00AE\u00B7\u00B8\u00BB\u00BC\u00BF\u00C0\u0221\u0222\u0234\u0250\u02AE\u02B0\u02EF\u0300\u0350\u0360\u0370\u0374\u0376\u037A\u037B\u0384\u0387\u0388\u038B\u038C\u038D\u038E\u03A2\u03A3\u03CF\u03D0\u03F7\u0400\u0487\u0488\u04CF\u04D0\u04F6\u04F8\u04FA\u0500\u0510\u0531\u0557\u0559\u055A\u0561\u0588\u0591\u05A2\u05A3\u05BA\u05BB\u05BE\u05BF\u05C0\u05C1\u05C3\u05C4\u05C5\u05D0\u05EB\u05F0\u05F3\u0621\u063B\u0640\u0656\u0660\u066A\u066E\u06D4\u06D5\u06DD\u06DE\u06EE\u06F0\u06FF\u0710\u072D\u0730\u074B\u0780\u07B2\u0901\u0904\u0905\u093A\u093C\u094E\u0950\u0955\u0958\u0964\u0966\u0970\u0981\u0984\u0985\u098D\u098F\u0991\u0993\u09A9\u09AA\u09B1\u09B2\u09B3\u09B6\u09BA\u09BC\u09BD\u09BE\u09C5\u09C7\u09C9\u09CB\u09CE\u09D7\u09D8\u09DC\u09DE\u09DF\u09E4\u09E6\u09FB\u0A02\u0A03\u0A05\u0A0B\u0A0F\u0A11\u0A13\u0A29\u0A2A\u0A31\u0A32\u0A34\u0A35" +"\u0A37\u0A38\u0A3A\u0A3C\u0A3D\u0A3E\u0A43\u0A47\u0A49\u0A4B\u0A4E\u0A59\u0A5D\u0A5E\u0A5F\u0A66\u0A75\u0A81\u0A84\u0A85\u0A8C\u0A8D\u0A8E\u0A8F\u0A92\u0A93\u0AA9\u0AAA\u0AB1\u0AB2\u0AB4\u0AB5\u0ABA\u0ABC\u0AC6\u0AC7\u0ACA\u0ACB\u0ACE\u0AD0\u0AD1\u0AE0\u0AE1\u0AE6\u0AF0\u0B01\u0B04\u0B05\u0B0D\u0B0F\u0B11\u0B13\u0B29\u0B2A\u0B31\u0B32\u0B34\u0B36\u0B3A\u0B3C\u0B44\u0B47\u0B49\u0B4B\u0B4E\u0B56\u0B58\u0B5C\u0B5E\u0B5F\u0B62\u0B66\u0B71\u0B82\u0B84\u0B85\u0B8B\u0B8E\u0B91\u0B92\u0B96\u0B99\u0B9B\u0B9C\u0B9D\u0B9E\u0BA0\u0BA3\u0BA5\u0BA8\u0BAB\u0BAE\u0BB6\u0BB7\u0BBA\u0BBE\u0BC3\u0BC6\u0BC9\u0BCA\u0BCE\u0BD7\u0BD8\u0BE7\u0BF3\u0C01\u0C04\u0C05\u0C0D\u0C0E\u0C11\u0C12\u0C29\u0C2A\u0C34\u0C35\u0C3A\u0C3E\u0C45\u0C46\u0C49\u0C4A\u0C4E\u0C55\u0C57\u0C60\u0C62\u0C66\u0C70\u0C82\u0C84\u0C85\u0C8D\u0C8E\u0C91\u0C92\u0CA9\u0CAA\u0CB4\u0CB5\u0CBA\u0CBE\u0CC5\u0CC6\u0CC9\u0CCA\u0CCE\u0CD5\u0CD7\u0CDE\u0CDF\u0CE0\u0CE2\u0CE6\u0CF0\u0D02\u0D04\u0D05\u0D0D\u0D0E\u0D11\u0D12\u0D29\u0D2A\u0D3A\u0D3E\u0D44\u0D46\u0D49" +"\u0D4A\u0D4E\u0D57\u0D58\u0D60\u0D62\u0D66\u0D70\u0D82\u0D84\u0D85\u0D97\u0D9A\u0DB2\u0DB3\u0DBC\u0DBD\u0DBE\u0DC0\u0DC7\u0DCA\u0DCB\u0DCF\u0DD5\u0DD6\u0DD7\u0DD8\u0DE0\u0DF2\u0DF4\u0E01\u0E3B\u0E3F\u0E4F\u0E50\u0E5A\u0E81\u0E83\u0E84\u0E85\u0E87\u0E89\u0E8A\u0E8B\u0E8D\u0E8E\u0E94\u0E98\u0E99\u0EA0\u0EA1\u0EA4\u0EA5\u0EA6\u0EA7\u0EA8\u0EAA\u0EAC\u0EAD\u0EBA\u0EBB\u0EBE\u0EC0\u0EC5\u0EC6\u0EC7\u0EC8\u0ECE\u0ED0\u0EDA\u0EDC\u0EDE\u0F00\u0F04\u0F13\u0F3A\u0F3E\u0F48\u0F49\u0F6B\u0F71\u0F85\u0F86\u0F8C\u0F90\u0F98\u0F99\u0FBD\u0FBE\u0FCD\u0FCF\u0FD0\u1000\u1022\u1023\u1028\u1029\u102B\u102C\u1033\u1036\u103A\u1040\u104A\u1050\u105A\u10A0\u10C6\u10D0\u10F9\u1100\u115A\u115F\u11A3\u11A8\u11FA\u1200\u1207\u1208\u1247\u1248\u1249\u124A\u124E\u1250\u1257\u1258\u1259\u125A\u125E\u1260\u1287\u1288\u1289\u128A\u128E\u1290\u12AF\u12B0\u12B1\u12B2\u12B6\u12B8\u12BF\u12C0\u12C1\u12C2\u12C6\u12C8\u12CF\u12D0\u12D7\u12D8\u12EF\u12F0\u130F\u1310\u1311\u1312\u1316\u1318\u131F\u1320\u1347\u1348\u135B\u1369\u137D\u13A0" +"\u13F5\u1401\u166D\u166F\u1677\u1681\u169B\u16A0\u16EB\u16EE\u16F1\u1700\u170D\u170E\u1715\u1720\u1735\u1740\u1754\u1760\u176D\u176E\u1771\u1772\u1774\u1780\u17D4\u17D7\u17D8\u17DB\u17DD\u17E0\u17EA\u180B\u180E\u1810\u181A\u1820\u1878\u1880\u18AA\u1E00\u1E9C\u1EA0\u1EFA\u1F00\u1F16\u1F18\u1F1E\u1F20\u1F46\u1F48\u1F4E\u1F50\u1F58\u1F59\u1F5A\u1F5B\u1F5C\u1F5D\u1F5E\u1F5F\u1F7E\u1F80\u1FB5\u1FB6\u1FC5\u1FC6\u1FD4\u1FD6\u1FDC\u1FDD\u1FF0\u1FF2\u1FF5\u1FF6\u1FFF\u2044\u2045\u2052\u2053\u2070\u2072\u2074\u207D\u207F\u208D\u20A0\u20B2\u20D0\u20EB\u2100\u213B\u213D\u214C\u2153\u2184\u2190\u2329\u232B\u23B4\u23B7\u23CF\u2400\u2427\u2440\u244B\u2460\u24FF\u2500\u2614\u2616\u2618\u2619\u267E\u2680\u268A\u2701\u2705\u2706\u270A\u270C\u2728\u2729\u274C\u274D\u274E\u274F\u2753\u2756\u2757\u2758\u275F\u2761\u2768\u2776\u2795\u2798\u27B0\u27B1\u27BF\u27D0\u27E6\u27F0\u2983\u2999\u29D8\u29DC\u29FC\u29FE\u2B00\u2E80\u2E9A\u2E9B\u2EF4\u2F00\u2FD6\u2FF0\u2FFC\u3004\u3008\u3012\u3014\u3020\u3030\u3031\u303D\u303E\u3040" +"\u3041\u3097\u3099\u30A0\u30A1\u30FB\u30FC\u3100\u3105\u312D\u3131\u318F\u3190\u31B8\u31F0\u321D\u3220\u3244\u3251\u327C\u327F\u32CC\u32D0\u32FF\u3300\u3377\u337B\u33DE\u33E0\u33FF\u3400\u4DB6\u4E00\u9FA6\uA000\uA48D\uA490\uA4C7\uAC00\uD7A4\uF900\uFA2E\uFA30\uFA6B\uFB00\uFB07\uFB13\uFB18\uFB1D\uFB37\uFB38\uFB3D\uFB3E\uFB3F\uFB40\uFB42\uFB43\uFB45\uFB46\uFBB2\uFBD3\uFD3E\uFD50\uFD90\uFD92\uFDC8\uFDF0\uFDFD\uFE00\uFE10\uFE20\uFE24\uFE62\uFE63\uFE64\uFE67\uFE69\uFE6A\uFE70\uFE75\uFE76\uFEFD\uFF04\uFF05\uFF0B\uFF0C\uFF10\uFF1A\uFF1C\uFF1F\uFF21\uFF3B\uFF3E\uFF3F\uFF40\uFF5B\uFF5C\uFF5D\uFF5E\uFF5F\uFF66\uFFBF\uFFC2\uFFC8\uFFCA\uFFD0\uFFD2\uFFD8\uFFDA\uFFDD\uFFE0\uFFE7\uFFE8\uFFEF\uFFFC\uFFFE"}, }; private List<(char First, char Last)>? _rangelist; private StringBuilder? _categories; private RegexCharClass? _subtractor; private bool _negate; #if DEBUG static RegexCharClass() { // Make sure the initial capacity for s_definedCategories is correct Debug.Assert( s_definedCategories.Count == DefinedCategoriesCapacity, $"Expected (s_definedCategories.Count): {s_definedCategories.Count}, Actual (DefinedCategoriesCapacity): {DefinedCategoriesCapacity}"); // Make sure the s_propTable is correctly ordered int len = s_propTable.Length; for (int i = 0; i < len - 1; i++) Debug.Assert(string.Compare(s_propTable[i][0], s_propTable[i + 1][0], StringComparison.Ordinal) < 0, $"RegexCharClass s_propTable is out of order at ({s_propTable[i][0]}, {s_propTable[i + 1][0]})"); } #endif /// <summary> /// Creates an empty character class. /// </summary> public RegexCharClass() { } private RegexCharClass(bool negate, List<(char First, char Last)>? ranges, StringBuilder? categories, RegexCharClass? subtraction) { _rangelist = ranges; _categories = categories; _negate = negate; _subtractor = subtraction; } public bool CanMerge => !_negate && _subtractor == null; public bool Negate { set { _negate = value; } } public void AddChar(char c) => AddRange(c, c); /// <summary> /// Adds a regex char class /// </summary> public void AddCharClass(RegexCharClass cc) { Debug.Assert(cc.CanMerge && CanMerge, "Both character classes added together must be able to merge"); int ccRangeCount = cc._rangelist?.Count ?? 0; if (ccRangeCount != 0) { EnsureRangeList().AddRange(cc._rangelist!); } if (cc._categories != null) { EnsureCategories().Append(cc._categories); } } /// <summary>Adds a regex char class if the classes are mergeable.</summary> public bool TryAddCharClass(RegexCharClass cc) { if (cc.CanMerge && CanMerge) { AddCharClass(cc); return true; } return false; } private StringBuilder EnsureCategories() => _categories ??= new StringBuilder(); private List<(char First, char Last)> EnsureRangeList() => _rangelist ??= new List<(char First, char Last)>(6); /// <summary> /// Adds a set (specified by its string representation) to the class. /// </summary> private void AddSet(ReadOnlySpan<char> set) { if (set.Length == 0) { return; } List<(char First, char Last)> rangeList = EnsureRangeList(); int i; for (i = 0; i < set.Length - 1; i += 2) { rangeList.Add((set[i], (char)(set[i + 1] - 1))); } if (i < set.Length) { rangeList.Add((set[i], LastChar)); } } public void AddSubtraction(RegexCharClass sub) { Debug.Assert(_subtractor == null, "Can't add two subtractions to a char class. "); _subtractor = sub; } /// <summary> /// Adds a single range of characters to the class. /// </summary> public void AddRange(char first, char last) => EnsureRangeList().Add((first, last)); public void AddCategoryFromName(string categoryName, bool invert, bool caseInsensitive, string pattern, int currentPos) { if (s_definedCategories.TryGetValue(categoryName, out string? category) && !categoryName.Equals(InternalRegexIgnoreCase)) { if (caseInsensitive && (categoryName.Equals("Ll") || categoryName.Equals("Lu") || categoryName.Equals("Lt"))) { // when RegexOptions.IgnoreCase is specified then {Ll}, {Lu}, and {Lt} cases should all match category = s_definedCategories[InternalRegexIgnoreCase]; } StringBuilder categories = EnsureCategories(); if (invert) { // Negate category for (int i = 0; i < category.Length; i++) { short ch = (short)category[i]; categories.Append((char)-ch); } } else { categories.Append(category); } } else { AddSet(SetFromProperty(categoryName, invert, pattern, currentPos)); } } private void AddCategory(string category) => EnsureCategories().Append(category); /// <summary> /// Adds to the class any lowercase versions of characters already /// in the class. Used for case-insensitivity. /// </summary> public void AddLowercase(CultureInfo culture) { List<(char First, char Last)>? rangeList = _rangelist; if (rangeList != null) { int count = rangeList.Count; for (int i = 0; i < count; i++) { (char First, char Last) range = rangeList[i]; if (range.First == range.Last) { char lower = culture.TextInfo.ToLower(range.First); rangeList[i] = (lower, lower); } else { AddLowercaseRange(range.First, range.Last); } } } } /// <summary> /// For a single range that's in the set, adds any additional ranges /// necessary to ensure that lowercase equivalents are also included. /// </summary> private void AddLowercaseRange(char chMin, char chMax) { int i = 0; for (int iMax = s_lcTable.Length; i < iMax;) { int iMid = (i + iMax) >> 1; if (s_lcTable[iMid].ChMax < chMin) { i = iMid + 1; } else { iMax = iMid; } } if (i >= s_lcTable.Length) { return; } char chMinT, chMaxT; LowerCaseMapping lc; for (; i < s_lcTable.Length && (lc = s_lcTable[i]).ChMin <= chMax; i++) { if ((chMinT = lc.ChMin) < chMin) { chMinT = chMin; } if ((chMaxT = lc.ChMax) > chMax) { chMaxT = chMax; } switch (lc.LcOp) { case LowercaseSet: chMinT = (char)lc.Data; chMaxT = (char)lc.Data; break; case LowercaseAdd: chMinT += (char)lc.Data; chMaxT += (char)lc.Data; break; case LowercaseBor: chMinT |= (char)1; chMaxT |= (char)1; break; case LowercaseBad: chMinT += (char)(chMinT & 1); chMaxT += (char)(chMaxT & 1); break; } if (chMinT < chMin || chMaxT > chMax) { AddRange(chMinT, chMaxT); } } } public void AddWord(bool ecma, bool negate) { if (ecma) { AddSet((negate ? NotECMAWordSet : ECMAWordSet).AsSpan()); } else { AddCategory(negate ? NotWord : Word); } } public void AddSpace(bool ecma, bool negate) { if (ecma) { AddSet((negate ? NotECMASpaceSet : ECMASpaceSet).AsSpan()); } else { AddCategory(negate ? NotSpace : Space); } } public void AddDigit(bool ecma, bool negate, string pattern, int currentPos) { if (ecma) { AddSet((negate ? NotECMADigitSet : ECMADigitSet).AsSpan()); } else { AddCategoryFromName("Nd", negate, caseInsensitive: false, pattern, currentPos); } } public static string ConvertOldStringsToClass(string set, string category) { bool startsWithNulls = set.Length >= 2 && set[0] == '\0' && set[1] == '\0'; int strLength = SetStartIndex + set.Length + category.Length; if (startsWithNulls) { strLength -= 2; } #if REGEXGENERATOR return StringExtensions.Create #else return string.Create #endif (strLength, (set, category, startsWithNulls), static (span, state) => { int index; if (state.startsWithNulls) { span[FlagsIndex] = (char)0x1; span[SetLengthIndex] = (char)(state.set.Length - 2); span[CategoryLengthIndex] = (char)state.category.Length; state.set.AsSpan(2).CopyTo(span.Slice(SetStartIndex)); index = SetStartIndex + state.set.Length - 2; } else { span[FlagsIndex] = '\0'; span[SetLengthIndex] = (char)state.set.Length; span[CategoryLengthIndex] = (char)state.category.Length; state.set.AsSpan().CopyTo(span.Slice(SetStartIndex)); index = SetStartIndex + state.set.Length; } state.category.AsSpan().CopyTo(span.Slice(index)); }); } /// <summary> /// Returns the char /// </summary> public static char SingletonChar(string set) { Debug.Assert(IsSingleton(set) || IsSingletonInverse(set), "Tried to get the singleton char out of a non singleton character class"); return set[SetStartIndex]; } public static bool IsMergeable(string charClass) => charClass != null && !IsNegated(charClass) && !IsSubtraction(charClass); public static bool IsEmpty(string charClass) => charClass[CategoryLengthIndex] == 0 && charClass[SetLengthIndex] == 0 && !IsNegated(charClass) && !IsSubtraction(charClass); /// <summary><c>true</c> if the set contains a single character only</summary> /// <remarks> /// This will happen not only from character classes manually written to contain a single character, /// but much more frequently by the implementation/parser itself, e.g. when looking for \n as part of /// finding the end of a line, when processing an alternation like "hello|hithere" where the first /// character of both options is the same, etc. /// </remarks> public static bool IsSingleton(string set) => set[CategoryLengthIndex] == 0 && set[SetLengthIndex] == 2 && !IsNegated(set) && !IsSubtraction(set) && (set[SetStartIndex] == LastChar || set[SetStartIndex] + 1 == set[SetStartIndex + 1]); public static bool IsSingletonInverse(string set) => set[CategoryLengthIndex] == 0 && set[SetLengthIndex] == 2 && IsNegated(set) && !IsSubtraction(set) && (set[SetStartIndex] == LastChar || set[SetStartIndex] + 1 == set[SetStartIndex + 1]); /// <summary>Gets whether the set contains nothing other than a single UnicodeCategory (it may be negated).</summary> /// <param name="set">The set to examine.</param> /// <param name="category">The single category if there was one.</param> /// <param name="negated">true if the single category is a not match.</param> /// <returns>true if a single category could be obtained; otherwise, false.</returns> public static bool TryGetSingleUnicodeCategory(string set, out UnicodeCategory category, out bool negated) { if (set[CategoryLengthIndex] == 1 && set[SetLengthIndex] == 0 && !IsSubtraction(set)) { short c = (short)set[SetStartIndex]; if (c > 0) { if (c != SpaceConst) { category = (UnicodeCategory)(c - 1); negated = IsNegated(set); return true; } } else if (c < 0) { if (c != NotSpaceConst) { category = (UnicodeCategory)(-1 - c); negated = !IsNegated(set); return true; } } } category = default; negated = false; return false; } /// <summary>Attempts to get a single range stored in the set.</summary> /// <param name="set">The set.</param> /// <param name="lowInclusive">The inclusive lower-bound of the range, if available.</param> /// <param name="highInclusive">The inclusive upper-bound of the range, if available.</param> /// <returns>true if the set contained a single range; otherwise, false.</returns> /// <remarks> /// <paramref name="lowInclusive"/> and <paramref name="highInclusive"/> will be equal if the /// range is a singleton or singleton inverse. The range will need to be negated by the caller /// if <see cref="IsNegated(string)"/> is true. /// </remarks> public static bool TryGetSingleRange(string set, out char lowInclusive, out char highInclusive) { if (set[CategoryLengthIndex] == 0 && // must not have any categories set.Length == SetStartIndex + set[SetLengthIndex]) // and no subtraction { switch ((int)set[SetLengthIndex]) { case 1: lowInclusive = set[SetStartIndex]; highInclusive = LastChar; return true; case 2: lowInclusive = set[SetStartIndex]; highInclusive = (char)(set[SetStartIndex + 1] - 1); return true; } } lowInclusive = highInclusive = '\0'; return false; } /// <summary>Gets all of the characters in the specified set, storing them into the provided span.</summary> /// <param name="set">The character class.</param> /// <param name="chars">The span into which the chars should be stored.</param> /// <returns> /// The number of stored chars. If they won't all fit, 0 is returned. /// If 0 is returned, no assumptions can be made about the characters. /// </returns> /// <remarks> /// Only considers character classes that only contain sets (no categories) /// and no subtraction... just simple sets containing starting/ending pairs. /// The returned characters may be negated: if IsNegated(set) is false, then /// the returned characters are the only ones that match; if it returns true, /// then the returned characters are the only ones that don't match. /// </remarks> public static int GetSetChars(string set, Span<char> chars) { // We get the characters by enumerating the set portion, so we validate that it's // set up to enable that, e.g. no categories. if (!CanEasilyEnumerateSetContents(set)) { return 0; } // Iterate through the pairs of ranges, storing each value in each range // into the supplied span. If they all won't fit, we give up and return 0. // Otherwise we return the number found. Note that we don't bother to handle // the corner case where the last range's upper bound is LastChar (\uFFFF), // based on it a) complicating things, and b) it being really unlikely to // be part of a small set. int setLength = set[SetLengthIndex]; int count = 0; for (int i = SetStartIndex; i < SetStartIndex + setLength; i += 2) { int curSetEnd = set[i + 1]; for (int c = set[i]; c < curSetEnd; c++) { if (count >= chars.Length) { return 0; } chars[count++] = (char)c; } } return count; } /// <summary> /// Determines whether two sets may overlap. /// </summary> /// <returns>false if the two sets do not overlap; true if they may.</returns> /// <remarks> /// If the method returns false, the caller can be sure the sets do not overlap. /// If the method returns true, it's still possible the sets don't overlap. /// </remarks> public static bool MayOverlap(string set1, string set2) { // If the sets are identical, there's obviously overlap. if (set1 == set2) { return true; } // If either set is all-inclusive, there's overlap by definition (unless // the other set is empty, but that's so rare it's not worth checking.) if (set1 == AnyClass || set2 == AnyClass) { return true; } // If one set is negated and the other one isn't, we're in one of two situations: // - The remainder of the sets are identical, in which case these are inverses of // each other, and they don't overlap. // - The remainder of the sets aren't identical, in which case there's very likely // overlap, and it's not worth spending more time investigating. bool set1Negated = IsNegated(set1); bool set2Negated = IsNegated(set2); if (set1Negated != set2Negated) { return !set1.AsSpan(1).SequenceEqual(set2.AsSpan(1)); } // If the sets are negated, since they're not equal, there's almost certainly overlap. Debug.Assert(set1Negated == set2Negated); if (set1Negated) { return true; } // Special-case some known, common classes that don't overlap. if (KnownDistinctSets(set1, set2) || KnownDistinctSets(set2, set1)) { return false; } // If set2 can be easily enumerated (e.g. no unicode categories), then enumerate it and // check if any of its members are in set1. Otherwise, the same for set1. if (CanEasilyEnumerateSetContents(set2)) { return MayOverlapByEnumeration(set1, set2); } else if (CanEasilyEnumerateSetContents(set1)) { return MayOverlapByEnumeration(set2, set1); } // Assume that everything else might overlap. In the future if it proved impactful, we could be more accurate here, // at the exense of more computation time. return true; static bool KnownDistinctSets(string set1, string set2) => (set1 == SpaceClass || set1 == ECMASpaceClass) && (set2 == DigitClass || set2 == WordClass || set2 == ECMADigitClass || set2 == ECMAWordClass); static bool MayOverlapByEnumeration(string set1, string set2) { Debug.Assert(!IsNegated(set1) && !IsNegated(set2)); for (int i = SetStartIndex; i < SetStartIndex + set2[SetLengthIndex]; i += 2) { int curSetEnd = set2[i + 1]; for (int c = set2[i]; c < curSetEnd; c++) { if (CharInClass((char)c, set1)) { return true; } } } return false; } } /// <summary>Gets whether the specified character participates in case conversion.</summary> /// <remarks> /// This method is used to perform operations as if they were case-sensitive even if they're /// specified as being case-insensitive. Such a reduction can be applied when the only character /// that would lower-case to the one being searched for / compared against is that character itself. /// </remarks> public static bool ParticipatesInCaseConversion(int comparison) { Debug.Assert((uint)comparison <= char.MaxValue); switch (char.GetUnicodeCategory((char)comparison)) { case UnicodeCategory.ClosePunctuation: case UnicodeCategory.ConnectorPunctuation: case UnicodeCategory.Control: case UnicodeCategory.DashPunctuation: case UnicodeCategory.DecimalDigitNumber: case UnicodeCategory.FinalQuotePunctuation: case UnicodeCategory.InitialQuotePunctuation: case UnicodeCategory.LineSeparator: case UnicodeCategory.OpenPunctuation: case UnicodeCategory.OtherNumber: case UnicodeCategory.OtherPunctuation: case UnicodeCategory.ParagraphSeparator: case UnicodeCategory.SpaceSeparator: // All chars in these categories meet the criteria that the only way // `char.ToLower(toTest, AnyCulture) == charInAboveCategory` is when // toTest == charInAboveCategory. return false; default: // We don't know (without testing the character against every other // character), so assume it does. return true; } } /// <summary>Gets whether the specified span participates in case conversion.</summary> /// <remarks>The span participates in case conversion if any of its characters do.</remarks> public static bool ParticipatesInCaseConversion(ReadOnlySpan<char> s) { foreach (char c in s) { if (ParticipatesInCaseConversion(c)) { return true; } } return false; } /// <summary>Gets whether we can iterate through the set list pairs in order to completely enumerate the set's contents.</summary> /// <remarks>This may enumerate negated characters if the set is negated.</remarks> private static bool CanEasilyEnumerateSetContents(string set) => set.Length > SetStartIndex && set[SetLengthIndex] > 0 && set[SetLengthIndex] % 2 == 0 && set[CategoryLengthIndex] == 0 && !IsSubtraction(set); /// <summary>Provides results from <see cref="Analyze"/>.</summary> internal struct CharClassAnalysisResults { /// <summary>true if we know for sure that the set contains only ASCII values; otherwise, false.</summary> public bool ContainsOnlyAscii; /// <summary>true if we know for sure that the set doesn't contain any ASCII values; otherwise, false.</summary> public bool ContainsNoAscii; /// <summary>true if we know for sure that all ASCII values are in the set; otherwise, false.</summary> public bool AllAsciiContained; /// <summary>true if we know for sure that all non-ASCII values are in the set; otherwise, false.</summary> public bool AllNonAsciiContained; } /// <summary>Analyzes the set to determine some basic properties that can be used to optimize usage.</summary> internal static CharClassAnalysisResults Analyze(string set) { if (!CanEasilyEnumerateSetContents(set)) { // We can't make any strong claims about the set. return default; } #if DEBUG for (int i = SetStartIndex; i < set.Length - 1; i += 2) { Debug.Assert(set[i] < set[i + 1]); } #endif if (IsNegated(set)) { // We're negated: if the upper bound of the range is ASCII, that means everything // above it is actually included, meaning all non-ASCII are in the class. // Similarly if the lower bound is non-ASCII, that means in a negated world // everything ASCII is included. return new CharClassAnalysisResults { AllNonAsciiContained = set[set.Length - 1] < 128, AllAsciiContained = set[SetStartIndex] >= 128, ContainsNoAscii = false, ContainsOnlyAscii = false }; } // If the upper bound is ASCII, that means everything included in the class is ASCII. // Similarly if the lower bound is non-ASCII, that means no ASCII is in the class. return new CharClassAnalysisResults { AllNonAsciiContained = false, AllAsciiContained = false, ContainsOnlyAscii = set[set.Length - 1] <= 128, ContainsNoAscii = set[SetStartIndex] >= 128, }; } internal static bool IsSubtraction(string charClass) => charClass.Length > SetStartIndex + charClass[CategoryLengthIndex] + charClass[SetLengthIndex]; internal static bool IsNegated(string set) => set[FlagsIndex] == 1; internal static bool IsNegated(string set, int setOffset) => set[FlagsIndex + setOffset] == 1; public static bool IsECMAWordChar(char ch) => // According to ECMA-262, \s, \S, ., ^, and $ use Unicode-based interpretations of // whitespace and newline, while \d, \D\, \w, \W, \b, and \B use ASCII-only // interpretations of digit, word character, and word boundary. In other words, // no special treatment of Unicode ZERO WIDTH NON-JOINER (ZWNJ U+200C) and // ZERO WIDTH JOINER (ZWJ U+200D) is required for ECMA word boundaries. ((((uint)ch - 'A') & ~0x20) < 26) || // ASCII letter (((uint)ch - '0') < 10) || // digit ch == '_' || // underscore ch == '\u0130'; // latin capital letter I with dot above /// <summary>16 bytes, representing the chars 0 through 127, with a 1 for a bit where that char is a word char.</summary> private static ReadOnlySpan<byte> WordCharAsciiLookup => new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07 }; /// <summary>Determines whether a character is considered a word character for the purposes of testing the \w set.</summary> public static bool IsWordChar(char ch) { // This is the same as IsBoundaryWordChar, except that IsBoundaryWordChar also // returns true for \u200c and \u200d. // Fast lookup in our lookup table for ASCII characters. This is purely an optimization, and has the // behavior as if we fell through to the switch below (which was actually used to produce the lookup table). ReadOnlySpan<byte> asciiLookup = WordCharAsciiLookup; int chDiv8 = ch >> 3; if ((uint)chDiv8 < (uint)asciiLookup.Length) { return (asciiLookup[chDiv8] & (1 << (ch & 0x7))) != 0; } // For non-ASCII, fall back to checking the Unicode category. switch (CharUnicodeInfo.GetUnicodeCategory(ch)) { case UnicodeCategory.UppercaseLetter: case UnicodeCategory.LowercaseLetter: case UnicodeCategory.TitlecaseLetter: case UnicodeCategory.ModifierLetter: case UnicodeCategory.OtherLetter: case UnicodeCategory.NonSpacingMark: case UnicodeCategory.DecimalDigitNumber: case UnicodeCategory.ConnectorPunctuation: return true; default: return false; } } /// <summary>Determines whether a character is considered a word character for the purposes of testing a word character boundary.</summary> public static bool IsBoundaryWordChar(char ch) { // According to UTS#18 Unicode Regular Expressions (http://www.unicode.org/reports/tr18/) // RL 1.4 Simple Word Boundaries The class of <word_character> includes all Alphabetic // values from the Unicode character database, from UnicodeData.txt [UData], plus the U+200C // ZERO WIDTH NON-JOINER and U+200D ZERO WIDTH JOINER. // Fast lookup in our lookup table for ASCII characters. This is purely an optimization, and has the // behavior as if we fell through to the switch below (which was actually used to produce the lookup table). ReadOnlySpan<byte> asciiLookup = WordCharAsciiLookup; int chDiv8 = ch >> 3; if ((uint)chDiv8 < (uint)asciiLookup.Length) { return (asciiLookup[chDiv8] & (1 << (ch & 0x7))) != 0; } // For non-ASCII, fall back to checking the Unicode category. switch (CharUnicodeInfo.GetUnicodeCategory(ch)) { case UnicodeCategory.UppercaseLetter: case UnicodeCategory.LowercaseLetter: case UnicodeCategory.TitlecaseLetter: case UnicodeCategory.ModifierLetter: case UnicodeCategory.OtherLetter: case UnicodeCategory.NonSpacingMark: case UnicodeCategory.DecimalDigitNumber: case UnicodeCategory.ConnectorPunctuation: return true; default: const char ZeroWidthNonJoiner = '\u200C', ZeroWidthJoiner = '\u200D'; return ch == ZeroWidthJoiner | ch == ZeroWidthNonJoiner; } } /// <summary>Determines whether the 'a' and 'b' values differ by only a single bit, setting that bit in 'mask'.</summary> /// <remarks>This isn't specific to RegexCharClass; it's just a convenient place to host it.</remarks> public static bool DifferByOneBit(char a, char b, out int mask) { mask = a ^ b; return mask != 0 && (mask & (mask - 1)) == 0; } /// <summary>Determines a character's membership in a character class (via the string representation of the class).</summary> /// <param name="ch">The character.</param> /// <param name="set">The string representation of the character class.</param> /// <param name="asciiLazyCache">A lazily-populated cache for ASCII results stored in a 256-bit array.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool CharInClass(char ch, string set, ref uint[]? asciiLazyCache) { // The uint[] contains 8 ints, or 256 bits. These are laid out as pairs, where the first bit in the pair // says whether the second bit in the pair has already been computed. Once a value is computed, it's never // changed, so since Int32s are written/read atomically, we can trust the value bit if we see that the known bit // has been set. If the known bit hasn't been set, then we proceed to look it up, and then swap in the result. const int CacheArrayLength = 8; Debug.Assert(asciiLazyCache is null || asciiLazyCache.Length == CacheArrayLength, "set lookup should be able to store two bits for each of the first 128 characters"); // If the value is ASCII and already has an answer for this value, use it. if (asciiLazyCache is uint[] cache) { int index = ch >> 4; if ((uint)index < (uint)cache.Length) { Debug.Assert(ch < 128); uint current = cache[index]; uint bit = 1u << ((ch & 0xF) << 1); if ((current & bit) != 0) { return (current & (bit << 1)) != 0; } } } // For ASCII, lazily initialize. For non-ASCII, just compute the value. return ch < 128 ? InitializeValue(ch, set, ref asciiLazyCache) : CharInClassRecursive(ch, set, 0); static bool InitializeValue(char ch, string set, ref uint[]? asciiLazyCache) { // (After warm-up, we should find ourselves rarely getting here.) Debug.Assert(ch < 128); // Compute the result and determine which bits to write back to the array and "or" the bits back in a thread-safe manner. bool isInClass = CharInClass(ch, set); uint bitsToSet = 1u << ((ch & 0xF) << 1); if (isInClass) { bitsToSet |= bitsToSet << 1; } uint[]? cache = asciiLazyCache ?? Interlocked.CompareExchange(ref asciiLazyCache, new uint[CacheArrayLength], null) ?? asciiLazyCache; #if REGEXGENERATOR InterlockedExtensions.Or(ref cache[ch >> 4], bitsToSet); #else Interlocked.Or(ref cache[ch >> 4], bitsToSet); #endif // Return the computed value. return isInClass; } } /// <summary> /// Determines a character's membership in a character class (via the string representation of the class). /// </summary> public static bool CharInClass(char ch, string set) => CharInClassRecursive(ch, set, 0); private static bool CharInClassRecursive(char ch, string set, int start) { int setLength = set[start + SetLengthIndex]; int categoryLength = set[start + CategoryLengthIndex]; int endPosition = start + SetStartIndex + setLength + categoryLength; bool inClass = CharInClassInternal(ch, set, start, setLength, categoryLength); // Note that we apply the negation *before* performing the subtraction. This is because // the negation only applies to the first char class, not the entire subtraction. if (IsNegated(set, start)) { inClass = !inClass; } // Subtract if necessary if (inClass && set.Length > endPosition) { inClass = !CharInClassRecursive(ch, set, endPosition); } return inClass; } /// <summary> /// Determines a character's membership in a character class (via the /// string representation of the class). /// </summary> private static bool CharInClassInternal(char ch, string set, int start, int setLength, int categoryLength) { int min = start + SetStartIndex; int max = min + setLength; while (min != max) { int mid = (min + max) >> 1; if (ch < set[mid]) { max = mid; } else { min = mid + 1; } } // The starting position of the set within the character class determines // whether what an odd or even ending position means. If the start is odd, // an *even* ending position means the character was in the set. With recursive // subtractions in the mix, the starting position = start+SetStartIndex. Since we know that // SetStartIndex is odd, we can simplify it out of the equation. But if it changes we need to // reverse this check. Debug.Assert((SetStartIndex & 0x1) == 1, "If SetStartIndex is not odd, the calculation below this will be reversed"); if ((min & 0x1) == (start & 0x1)) { return true; } if (categoryLength == 0) { return false; } return CharInCategory(ch, set, start, setLength, categoryLength); } private static bool CharInCategory(char ch, string set, int start, int setLength, int categoryLength) { UnicodeCategory chcategory = char.GetUnicodeCategory(ch); int i = start + SetStartIndex + setLength; int end = i + categoryLength; while (i < end) { int curcat = (short)set[i]; if (curcat == 0) { // zero is our marker for a group of categories - treated as a unit if (CharInCategoryGroup(chcategory, set, ref i)) { return true; } } else if (curcat > 0) { // greater than zero is a positive case if (curcat == SpaceConst) { if (char.IsWhiteSpace(ch)) { return true; } } else if (chcategory == (UnicodeCategory)(curcat - 1)) { return true; } } else { // less than zero is a negative case if (curcat == NotSpaceConst) { if (!char.IsWhiteSpace(ch)) { return true; } } else if (chcategory != (UnicodeCategory)(-1 - curcat)) { return true; } } i++; } return false; } /// <summary> /// This is used for categories which are composed of other categories - L, N, Z, W... /// These groups need special treatment when they are negated /// </summary> private static bool CharInCategoryGroup(UnicodeCategory chcategory, string category, ref int i) { int pos = i + 1; int curcat = (short)category[pos]; bool result; if (curcat > 0) { // positive case - the character must be in ANY of the categories in the group result = false; for (; curcat != 0; curcat = (short)category[pos]) { pos++; if (!result && chcategory == (UnicodeCategory)(curcat - 1)) { result = true; } } } else { // negative case - the character must be in NONE of the categories in the group result = true; for (; curcat != 0; curcat = (short)category[pos]) { pos++; if (result && chcategory == (UnicodeCategory)(-1 - curcat)) { result = false; } } } i = pos; return result; } public static RegexCharClass Parse(string charClass) => ParseRecursive(charClass, 0); private static RegexCharClass ParseRecursive(string charClass, int start) { int setLength = charClass[start + SetLengthIndex]; int categoryLength = charClass[start + CategoryLengthIndex]; int endPosition = start + SetStartIndex + setLength + categoryLength; int i = start + SetStartIndex; int end = i + setLength; List<(char First, char Last)>? ranges = ComputeRanges(charClass.AsSpan(start)); RegexCharClass? sub = null; if (charClass.Length > endPosition) { sub = ParseRecursive(charClass, endPosition); } StringBuilder? categoriesBuilder = null; if (categoryLength > 0) { categoriesBuilder = new StringBuilder().Append(charClass.AsSpan(end, categoryLength)); } return new RegexCharClass(IsNegated(charClass, start), ranges, categoriesBuilder, sub); } /// <summary>Computes a list of all of the character ranges in the set string.</summary> public static List<(char First, char Last)>? ComputeRanges(ReadOnlySpan<char> set) { int setLength = set[SetLengthIndex]; int i = SetStartIndex; int end = i + setLength; List<(char First, char Last)>? ranges = null; if (setLength > 0) { ranges = new List<(char First, char Last)>(setLength); while (i < end) { char first = set[i]; i++; char last = i < end ? (char)(set[i] - 1) : LastChar; i++; ranges.Add((first, last)); } } return ranges; } #region Perf workaround until https://github.com/dotnet/runtime/issues/61048 and https://github.com/dotnet/runtime/issues/59492 are addressed // TODO: https://github.com/dotnet/runtime/issues/61048 // The below functionality needs to be removed/replaced/generalized. The goal is to avoid relying on // ToLower and culture-based operation at match time, and instead be able to compute at construction // time case folding equivalence classes that let us determine up-front the set of characters considered // valid for a match. For now, we do this just for ASCII, and for anything else fall back to the // pre-existing mechanism whereby a culture is used at construction time to ToLower and then one is // used at match time to ToLower. We also skip 'i' and 'I', as the casing of those varies across culture // whereas every other ASCII value's casing is stable across culture. We could hardcode the values for // when an invariant vs tr/az culture vs any other culture is used, and we likely will, but for now doing // so would be a breaking change, as in doing so we'd be relying only on the culture present at the time // of construction rather than the one at the time of match. That will be resolved with // https://github.com/dotnet/runtime/issues/59492. /// <summary>Creates a set string for a single character, optionally factoring in case-insensitivity.</summary> /// <param name="c">The character for which to create the set.</param> /// <param name="caseInsensitive">null if case-sensitive; non-null if case-insensitive, in which case it's the culture to use.</param> /// <param name="resultIsCaseInsensitive">false if the caller should strip out RegexOptions.IgnoreCase because it's now fully represented by the set; otherwise, true.</param> /// <returns>The create set string.</returns> public static string OneToStringClass(char c, CultureInfo? caseInsensitive, out bool resultIsCaseInsensitive) { var vsb = new ValueStringBuilder(stackalloc char[4]); if (caseInsensitive is null) { resultIsCaseInsensitive = false; vsb.Append(c); } else if (c < 128 && (c | 0x20) != 'i') { resultIsCaseInsensitive = false; switch (c) { // These are the same in all cultures. As with the rest of this support, we can generalize this // once we fix the aforementioned casing issues, e.g. by lazily populating an interning cache // rather than hardcoding the strings for these values, once almost all values will be the same // regardless of culture. case 'A': case 'a': return "\0\x0004\0ABab"; case 'B': case 'b': return "\0\x0004\0BCbc"; case 'C': case 'c': return "\0\x0004\0CDcd"; case 'D': case 'd': return "\0\x0004\0DEde"; case 'E': case 'e': return "\0\x0004\0EFef"; case 'F': case 'f': return "\0\x0004\0FGfg"; case 'G': case 'g': return "\0\x0004\0GHgh"; case 'H': case 'h': return "\0\x0004\0HIhi"; // allow 'i' to fall through case 'J': case 'j': return "\0\x0004\0JKjk"; case 'K': case 'k': return "\0\x0006\0KLkl\u212A\u212B"; case 'L': case 'l': return "\0\x0004\0LMlm"; case 'M': case 'm': return "\0\x0004\0MNmn"; case 'N': case 'n': return "\0\x0004\0NOno"; case 'O': case 'o': return "\0\x0004\0OPop"; case 'P': case 'p': return "\0\x0004\0PQpq"; case 'Q': case 'q': return "\0\x0004\0QRqr"; case 'R': case 'r': return "\0\x0004\0RSrs"; case 'S': case 's': return "\0\x0004\0STst"; case 'T': case 't': return "\0\x0004\0TUtu"; case 'U': case 'u': return "\0\x0004\0UVuv"; case 'V': case 'v': return "\0\x0004\0VWvw"; case 'W': case 'w': return "\0\x0004\0WXwx"; case 'X': case 'x': return "\0\x0004\0XYxy"; case 'Y': case 'y': return "\0\x0004\0YZyz"; case 'Z': case 'z': return "\0\x0004\0Z[z{"; // All the ASCII !ParticipatesInCaseConversion case '\u0000': return "\0\u0002\0\u0000\u0001"; case '\u0001': return "\0\u0002\0\u0001\u0002"; case '\u0002': return "\0\u0002\0\u0002\u0003"; case '\u0003': return "\0\u0002\0\u0003\u0004"; case '\u0004': return "\0\u0002\0\u0004\u0005"; case '\u0005': return "\0\u0002\0\u0005\u0006"; case '\u0006': return "\0\u0002\0\u0006\u0007"; case '\u0007': return "\0\u0002\0\u0007\u0008"; case '\u0008': return "\0\u0002\0\u0008\u0009"; case '\u0009': return "\0\u0002\0\u0009\u000A"; case '\u000A': return "\0\u0002\0\u000A\u000B"; case '\u000B': return "\0\u0002\0\u000B\u000C"; case '\u000C': return "\0\u0002\0\u000C\u000D"; case '\u000D': return "\0\u0002\0\u000D\u000E"; case '\u000E': return "\0\u0002\0\u000E\u000F"; case '\u000F': return "\0\u0002\0\u000F\u0010"; case '\u0010': return "\0\u0002\0\u0010\u0011"; case '\u0011': return "\0\u0002\0\u0011\u0012"; case '\u0012': return "\0\u0002\0\u0012\u0013"; case '\u0013': return "\0\u0002\0\u0013\u0014"; case '\u0014': return "\0\u0002\0\u0014\u0015"; case '\u0015': return "\0\u0002\0\u0015\u0016"; case '\u0016': return "\0\u0002\0\u0016\u0017"; case '\u0017': return "\0\u0002\0\u0017\u0018"; case '\u0018': return "\0\u0002\0\u0018\u0019"; case '\u0019': return "\0\u0002\0\u0019\u001A"; case '\u001A': return "\0\u0002\0\u001A\u001B"; case '\u001B': return "\0\u0002\0\u001B\u001C"; case '\u001C': return "\0\u0002\0\u001C\u001D"; case '\u001D': return "\0\u0002\0\u001D\u001E"; case '\u001E': return "\0\u0002\0\u001E\u001F"; case '\u001F': return "\0\u0002\0\u001F\u0020"; case '\u0020': return "\0\u0002\0\u0020\u0021"; case '\u0021': return "\0\u0002\0\u0021\u0022"; case '\u0022': return "\0\u0002\0\u0022\u0023"; case '\u0023': return "\0\u0002\0\u0023\u0024"; case '\u0025': return "\0\u0002\0\u0025\u0026"; case '\u0026': return "\0\u0002\0\u0026\u0027"; case '\u0027': return "\0\u0002\0\u0027\u0028"; case '\u0028': return "\0\u0002\0\u0028\u0029"; case '\u0029': return "\0\u0002\0\u0029\u002A"; case '\u002A': return "\0\u0002\0\u002A\u002B"; case '\u002C': return "\0\u0002\0\u002C\u002D"; case '\u002D': return "\0\u0002\0\u002D\u002E"; case '\u002E': return "\0\u0002\0\u002E\u002F"; case '\u002F': return "\0\u0002\0\u002F\u0030"; case '\u0030': return "\0\u0002\0\u0030\u0031"; case '\u0031': return "\0\u0002\0\u0031\u0032"; case '\u0032': return "\0\u0002\0\u0032\u0033"; case '\u0033': return "\0\u0002\0\u0033\u0034"; case '\u0034': return "\0\u0002\0\u0034\u0035"; case '\u0035': return "\0\u0002\0\u0035\u0036"; case '\u0036': return "\0\u0002\0\u0036\u0037"; case '\u0037': return "\0\u0002\0\u0037\u0038"; case '\u0038': return "\0\u0002\0\u0038\u0039"; case '\u0039': return "\0\u0002\0\u0039\u003A"; case '\u003A': return "\0\u0002\0\u003A\u003B"; case '\u003B': return "\0\u0002\0\u003B\u003C"; case '\u003F': return "\0\u0002\0\u003F\u0040"; case '\u0040': return "\0\u0002\0\u0040\u0041"; case '\u005B': return "\0\u0002\0\u005B\u005C"; case '\u005C': return "\0\u0002\0\u005C\u005D"; case '\u005D': return "\0\u0002\0\u005D\u005E"; case '\u005F': return "\0\u0002\0\u005F\u0060"; case '\u007B': return "\0\u0002\0\u007B\u007C"; case '\u007D': return "\0\u0002\0\u007D\u007E"; case '\u007F': return "\0\u0002\0\u007F\u0080"; } AddAsciiCharIgnoreCaseEquivalence(c, ref vsb, caseInsensitive); } else if (!ParticipatesInCaseConversion(c)) { resultIsCaseInsensitive = false; vsb.Append(c); } else { resultIsCaseInsensitive = true; vsb.Append(char.ToLower(c, caseInsensitive)); } string result = CharsToStringClass(vsb.AsSpan()); vsb.Dispose(); return result; } private static unsafe string CharsToStringClass(ReadOnlySpan<char> chars) { #if DEBUG // Make sure they're all sorted with no duplicates for (int index = 0; index < chars.Length - 1; index++) { Debug.Assert(chars[index] < chars[index + 1]); } #endif // If there aren't any chars, just return an empty class. if (chars.Length == 0) { return EmptyClass; } // Count how many characters there actually are. All but the very last possible // char value will have two characters, one for the inclusive beginning of range // and one for the exclusive end of range. int count = chars.Length * 2; if (chars[chars.Length - 1] == LastChar) { count--; } // Get the pointer/length of the span to be able to pass it into string.Create. fixed (char* charsPtr = chars) { #if REGEXGENERATOR return StringExtensions.Create( #else return string.Create( #endif SetStartIndex + count, ((IntPtr)charsPtr, chars.Length), static (span, state) => { // Reconstruct the span now that we're inside of the lambda. ReadOnlySpan<char> chars = new ReadOnlySpan<char>((char*)state.Item1, state.Length); // Fill in the set string span[FlagsIndex] = (char)0; span[CategoryLengthIndex] = (char)0; span[SetLengthIndex] = (char)(span.Length - SetStartIndex); int i = SetStartIndex; foreach (char c in chars) { span[i++] = c; if (c != LastChar) { span[i++] = (char)(c + 1); } } Debug.Assert(i == span.Length); }); } } /// <summary>Tries to create from a RegexOptions.IgnoreCase set string a new set string that can be used without RegexOptions.IgnoreCase.</summary> /// <param name="set">The original set string from a RegexOptions.IgnoreCase node.</param> /// <param name="culture">The culture in use.</param> /// <returns>A new set string if one could be created.</returns> public static string? MakeCaseSensitiveIfPossible(string set, CultureInfo culture) { if (IsNegated(set)) { return null; } // We'll eventually need a more robust way to do this for any set. For now, we iterate through each character // in the set, and to avoid spending lots of time doing so, we limit the number of characters. This approach also // limits the structure of the sets allowed, e.g. they can't be negated, can't use subtraction, etc. Span<char> setChars = stackalloc char[64]; // arbitary limit chosen to include common groupings like all ASCII letters and digits // Try to get the set's characters. int setCharsCount = GetSetChars(set, setChars); if (setCharsCount == 0) { return null; } // Enumerate all the characters and add all characters that form their case folding equivalence class. var rcc = new RegexCharClass(); var vsb = new ValueStringBuilder(stackalloc char[4]); foreach (char c in setChars.Slice(0, setCharsCount)) { if (c >= 128 || c == 'i' || c == 'I') { return null; } vsb.Length = 0; AddAsciiCharIgnoreCaseEquivalence(c, ref vsb, culture); foreach (char v in vsb.AsSpan()) { rcc.AddChar(v); } } // Return the constructed class. return rcc.ToStringClass(); } private static void AddAsciiCharIgnoreCaseEquivalence(char c, ref ValueStringBuilder vsb, CultureInfo culture) { Debug.Assert(c < 128, $"Expected ASCII, got {(int)c}"); Debug.Assert(c != 'i' && c != 'I', "'i' currently doesn't work correctly in all cultures"); char upper = char.ToUpper(c, culture); char lower = char.ToLower(c, culture); if (upper < lower) { vsb.Append(upper); } vsb.Append(lower); if (upper > lower) { vsb.Append(upper); } if (c == 'k' || c == 'K') { vsb.Append((char)0x212A); // kelvin sign } } #endregion /// <summary> /// Constructs the string representation of the class. /// </summary> public string ToStringClass(RegexOptions options = RegexOptions.None) { bool isNonBacktracking = (options & RegexOptions.NonBacktracking) != 0; var vsb = new ValueStringBuilder(stackalloc char[256]); ToStringClass(isNonBacktracking, ref vsb); return vsb.ToString(); } private void ToStringClass(bool isNonBacktracking, ref ValueStringBuilder vsb) { Canonicalize(isNonBacktracking); int initialLength = vsb.Length; int categoriesLength = _categories?.Length ?? 0; Span<char> headerSpan = vsb.AppendSpan(SetStartIndex); headerSpan[FlagsIndex] = (char)(_negate ? 1 : 0); headerSpan[SetLengthIndex] = '\0'; // (will be replaced once we know how long a range we've added) headerSpan[CategoryLengthIndex] = (char)categoriesLength; // Append ranges List<(char First, char Last)>? rangelist = _rangelist; if (rangelist != null) { for (int i = 0; i < rangelist.Count; i++) { (char First, char Last) currentRange = rangelist[i]; vsb.Append(currentRange.First); if (currentRange.Last != LastChar) { vsb.Append((char)(currentRange.Last + 1)); } } } // Update the range length. The ValueStringBuilder may have already had some // contents (if this is a subtactor), so we need to offset by the initial length. vsb[initialLength + SetLengthIndex] = (char)(vsb.Length - initialLength - SetStartIndex); // Append categories if (categoriesLength != 0) { foreach (ReadOnlyMemory<char> chunk in _categories!.GetChunks()) { vsb.Append(chunk.Span); } } // Append a subtractor if there is one. _subtractor?.ToStringClass(isNonBacktracking, ref vsb); } /// <summary> /// Logic to reduce a character class to a unique, sorted form. /// </summary> private void Canonicalize(bool isNonBacktracking) { List<(char First, char Last)>? rangelist = _rangelist; if (rangelist != null) { // Find and eliminate overlapping or abutting ranges. if (rangelist.Count > 1) { rangelist.Sort((x, y) => x.First.CompareTo(y.First)); bool done = false; int j = 0; for (int i = 1; ; i++) { char last; for (last = rangelist[j].Last; ; i++) { if (i == rangelist.Count || last == LastChar) { done = true; break; } (char First, char Last) currentRange; if ((currentRange = rangelist[i]).First > last + 1) { break; } if (last < currentRange.Last) { last = currentRange.Last; } } rangelist[j] = (rangelist[j].First, last); j++; if (done) { break; } if (j < i) { rangelist[j] = rangelist[i]; } } rangelist.RemoveRange(j, rangelist.Count - j); } // If the class now represents a single negated range, but does so by including every // other character, invert it to produce a normalized form with a single range. This // is valuable for subsequent optimizations in most of the engines. // TODO: https://github.com/dotnet/runtime/issues/61048. The special-casing for NonBacktracking // can be deleted once this issue is addressed. The special-casing exists because NonBacktracking // is on a different casing plan than the other engines and doesn't use ToLower on each input // character at match time; this in turn can highlight differences between sets and their inverted // versions of themselves, e.g. a difference between [0-AC-\uFFFF] and [^B]. if (!isNonBacktracking && !_negate && _subtractor is null && (_categories is null || _categories.Length == 0)) { if (rangelist.Count == 2) { // There are two ranges in the list. See if there's one missing range between them. // Such a range might be as small as a single character. if (rangelist[0].First == 0 && rangelist[1].Last == LastChar && rangelist[0].Last < rangelist[1].First - 1) { rangelist[0] = ((char)(rangelist[0].Last + 1), (char)(rangelist[1].First - 1)); rangelist.RemoveAt(1); _negate = true; } } else if (rangelist.Count == 1) { if (rangelist[0].First == 0) { // There's only one range in the list. Does it include everything but the last char? if (rangelist[0].Last == LastChar - 1) { rangelist[0] = (LastChar, LastChar); _negate = true; } } else if (rangelist[0].First == 1) { // Or everything but the first char? if (rangelist[0].Last == LastChar) { rangelist[0] = ('\0', '\0'); _negate = true; } } } } } } private static ReadOnlySpan<char> SetFromProperty(string capname, bool invert, string pattern, int currentPos) { int min = 0; int max = s_propTable.Length; while (min != max) { int mid = (min + max) / 2; int res = string.Compare(capname, s_propTable[mid][0], StringComparison.Ordinal); if (res < 0) { max = mid; } else if (res > 0) { min = mid + 1; } else { string set = s_propTable[mid][1]; Debug.Assert(!string.IsNullOrEmpty(set), "Found a null/empty element in RegexCharClass prop table"); return !invert ? set.AsSpan() : set[0] == NullChar ? set.AsSpan(1) : (NullCharString + set).AsSpan(); } } throw new RegexParseException(RegexParseError.UnrecognizedUnicodeProperty, currentPos, SR.Format(SR.MakeException, pattern, currentPos, SR.Format(SR.UnrecognizedUnicodeProperty, capname))); } public static readonly string[] CategoryIdToName = PopulateCategoryIdToName(); private static string[] PopulateCategoryIdToName() { // Populate category reverse lookup used for diagnostic output var temp = new List<KeyValuePair<string, string>>(s_definedCategories); temp.RemoveAll(kvp => kvp.Value.Length != 1); temp.Sort((kvp1, kvp2) => ((short)kvp1.Value[0]).CompareTo((short)kvp2.Value[0])); return temp.ConvertAll(kvp => kvp.Key).ToArray(); } /// <summary> /// Produces a human-readable description for a set string. /// </summary> [ExcludeFromCodeCoverage] public static string DescribeSet(string set) { int setLength = set[SetLengthIndex]; int categoryLength = set[CategoryLengthIndex]; int endPosition = SetStartIndex + setLength + categoryLength; var desc = new StringBuilder(); desc.Append('['); int index = SetStartIndex; char ch1; char ch2; if (IsNegated(set)) { desc.Append('^'); } while (index < SetStartIndex + set[SetLengthIndex]) { ch1 = set[index]; ch2 = index + 1 < set.Length ? (char)(set[index + 1] - 1) : LastChar; desc.Append(DescribeChar(ch1)); if (ch2 != ch1) { if (ch1 + 1 != ch2) { desc.Append('-'); } desc.Append(DescribeChar(ch2)); } index += 2; } while (index < SetStartIndex + set[SetLengthIndex] + set[CategoryLengthIndex]) { ch1 = set[index]; if (ch1 == 0) { bool found = false; const char GroupChar = (char)0; int lastindex = set.IndexOf(GroupChar, index + 1); if (lastindex != -1) { string group = set.Substring(index, lastindex - index + 1); foreach (KeyValuePair<string, string> kvp in s_definedCategories) { if (group.Equals(kvp.Value)) { desc.Append((short)set[index + 1] > 0 ? "\\p{" : "\\P{").Append(kvp.Key).Append('}'); found = true; break; } } if (!found) { if (group.Equals(Word)) { desc.Append("\\w"); } else if (group.Equals(NotWord)) { desc.Append("\\W"); } else { // TODO: The code is incorrectly handling pretty-printing groups like \P{P}. } } index = lastindex; } } else { desc.Append(DescribeCategory(ch1)); } index++; } if (set.Length > endPosition) { desc.Append('-').Append(DescribeSet(set.Substring(endPosition))); } return desc.Append(']').ToString(); } /// <summary>Produces a human-readable description for a single character.</summary> [ExcludeFromCodeCoverage] public static string DescribeChar(char ch) => ch switch { '\a' => "\\a", '\b' => "\\b", '\t' => "\\t", '\r' => "\\r", '\v' => "\\v", '\f' => "\\f", '\n' => "\\n", '\\' => "\\\\", >= ' ' and <= '~' => ch.ToString(), _ => $"\\u{(uint)ch:X4}" }; [ExcludeFromCodeCoverage] private static string DescribeCategory(char ch) => (short)ch switch { SpaceConst => @"\s", NotSpaceConst => @"\S", (short)(UnicodeCategory.DecimalDigitNumber + 1) => @"\d", -(short)(UnicodeCategory.DecimalDigitNumber + 1) => @"\D", < 0 => $"\\P{{{CategoryIdToName[-(short)ch - 1]}}}", _ => $"\\p{{{CategoryIdToName[ch - 1]}}}", }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.CompilerServices; using System.Threading; namespace System.Text.RegularExpressions { // The main function of RegexCharClass is as a builder to turn ranges, characters and // Unicode categories into a single string. This string is used as a black box // representation of a character class by the rest of Regex. The format is as follows. // // Char index Use // 0 Flags - currently this only holds the "negate" flag // 1 length of the string representing the "set" portion, e.g. [a-z0-9] only has a "set" // 2 length of the string representing the "category" portion, e.g. [\p{Lu}] only has a "category" // 3...m The set. These are a series of ranges which define the characters included in the set. // To determine if a given character is in the set, we binary search over this set of ranges // and see where the character should go. Based on whether the ending index is odd or even, // we know if the character is in the set. // m+1...n The categories. This is a list of UnicodeCategory enum values which describe categories // included in this class. /// <summary>Provides the "set of Unicode chars" functionality used by the regexp engine.</summary> internal sealed partial class RegexCharClass { // Constants internal const int FlagsIndex = 0; internal const int SetLengthIndex = 1; internal const int CategoryLengthIndex = 2; internal const int SetStartIndex = 3; // must be odd for subsequent logic to work private const string NullCharString = "\0"; private const char NullChar = '\0'; internal const char LastChar = '\uFFFF'; internal const short SpaceConst = 100; private const short NotSpaceConst = -100; private const string InternalRegexIgnoreCase = "__InternalRegexIgnoreCase__"; private const string Space = "\x64"; private const string NotSpace = "\uFF9C"; private const string Word = "\u0000\u0002\u0004\u0005\u0003\u0001\u0006\u0009\u0013\u0000"; private const string NotWord = "\u0000\uFFFE\uFFFC\uFFFB\uFFFD\uFFFF\uFFFA\uFFF7\uFFED\u0000"; internal const string SpaceClass = "\u0000\u0000\u0001\u0064"; internal const string NotSpaceClass = "\u0001\u0000\u0001\u0064"; internal const string WordClass = "\u0000\u0000\u000A\u0000\u0002\u0004\u0005\u0003\u0001\u0006\u0009\u0013\u0000"; internal const string NotWordClass = "\u0001\u0000\u000A\u0000\u0002\u0004\u0005\u0003\u0001\u0006\u0009\u0013\u0000"; internal const string DigitClass = "\u0000\u0000\u0001\u0009"; internal const string NotDigitClass = "\u0000\u0000\u0001\uFFF7"; private const string ECMASpaceSet = "\u0009\u000E\u0020\u0021"; private const string NotECMASpaceSet = "\0\u0009\u000E\u0020\u0021"; private const string ECMAWordSet = "\u0030\u003A\u0041\u005B\u005F\u0060\u0061\u007B\u0130\u0131"; private const string NotECMAWordSet = "\0\u0030\u003A\u0041\u005B\u005F\u0060\u0061\u007B\u0130\u0131"; private const string ECMADigitSet = "\u0030\u003A"; private const string NotECMADigitSet = "\0\u0030\u003A"; internal const string ECMASpaceClass = "\x00\x04\x00" + ECMASpaceSet; internal const string NotECMASpaceClass = "\x01\x04\x00" + ECMASpaceSet; internal const string ECMAWordClass = "\x00\x0A\x00" + ECMAWordSet; internal const string NotECMAWordClass = "\x01\x0A\x00" + ECMAWordSet; internal const string ECMADigitClass = "\x00\x02\x00" + ECMADigitSet; internal const string NotECMADigitClass = "\x01\x02\x00" + ECMADigitSet; internal const string AnyClass = "\x00\x01\x00\x00"; private const string EmptyClass = "\x00\x00\x00"; // UnicodeCategory is zero based, so we add one to each value and subtract it off later private const int DefinedCategoriesCapacity = 38; private static readonly Dictionary<string, string> s_definedCategories = new Dictionary<string, string>(DefinedCategoriesCapacity) { // Others { "Cc", "\u000F" }, // UnicodeCategory.Control + 1 { "Cf", "\u0010" }, // UnicodeCategory.Format + 1 { "Cn", "\u001E" }, // UnicodeCategory.OtherNotAssigned + 1 { "Co", "\u0012" }, // UnicodeCategory.PrivateUse + 1 { "Cs", "\u0011" }, // UnicodeCategory.Surrogate + 1 { "C", "\u0000\u000F\u0010\u001E\u0012\u0011\u0000" }, // Letters { "Ll", "\u0002" }, // UnicodeCategory.LowercaseLetter + 1 { "Lm", "\u0004" }, // UnicodeCategory.ModifierLetter + 1 { "Lo", "\u0005" }, // UnicodeCategory.OtherLetter + 1 { "Lt", "\u0003" }, // UnicodeCategory.TitlecaseLetter + 1 { "Lu", "\u0001" }, // UnicodeCategory.UppercaseLetter + 1 { "L", "\u0000\u0002\u0004\u0005\u0003\u0001\u0000" }, // InternalRegexIgnoreCase = {LowercaseLetter} OR {TitlecaseLetter} OR {UppercaseLetter} // !!!This category should only ever be used in conjunction with RegexOptions.IgnoreCase code paths!!! { "__InternalRegexIgnoreCase__", "\u0000\u0002\u0003\u0001\u0000" }, // Marks { "Mc", "\u0007" }, // UnicodeCategory.SpacingCombiningMark + 1 { "Me", "\u0008" }, // UnicodeCategory.EnclosingMark + 1 { "Mn", "\u0006" }, // UnicodeCategory.NonSpacingMark + 1 { "M", "\u0000\u0007\u0008\u0006\u0000" }, // Numbers { "Nd", "\u0009" }, // UnicodeCategory.DecimalDigitNumber + 1 { "Nl", "\u000A" }, // UnicodeCategory.LetterNumber + 1 { "No", "\u000B" }, // UnicodeCategory.OtherNumber + 1 { "N", "\u0000\u0009\u000A\u000B\u0000" }, // Punctuation { "Pc", "\u0013" }, // UnicodeCategory.ConnectorPunctuation + 1 { "Pd", "\u0014" }, // UnicodeCategory.DashPunctuation + 1 { "Pe", "\u0016" }, // UnicodeCategory.ClosePunctuation + 1 { "Po", "\u0019" }, // UnicodeCategory.OtherPunctuation + 1 { "Ps", "\u0015" }, // UnicodeCategory.OpenPunctuation + 1 { "Pf", "\u0018" }, // UnicodeCategory.FinalQuotePunctuation + 1 { "Pi", "\u0017" }, // UnicodeCategory.InitialQuotePunctuation + 1 { "P", "\u0000\u0013\u0014\u0016\u0019\u0015\u0018\u0017\u0000" }, // Symbols { "Sc", "\u001B" }, // UnicodeCategory.CurrencySymbol + 1 { "Sk", "\u001C" }, // UnicodeCategory.ModifierSymbol + 1 { "Sm", "\u001A" }, // UnicodeCategory.MathSymbol + 1 { "So", "\u001D" }, // UnicodeCategory.OtherSymbol + 1 { "S", "\u0000\u001B\u001C\u001A\u001D\u0000" }, // Separators { "Zl", "\u000D" }, // UnicodeCategory.LineSeparator + 1 { "Zp", "\u000E" }, // UnicodeCategory.ParagraphSeparator + 1 { "Zs", "\u000C" }, // UnicodeCategory.SpaceSeparator + 1 { "Z", "\u0000\u000D\u000E\u000C\u0000" }, }; /* * The property table contains all the block definitions defined in the * XML schema spec (http://www.w3.org/TR/2001/PR-xmlschema-2-20010316/#charcter-classes), Unicode 4.0 spec (www.unicode.org), * and Perl 5.6 (see Programming Perl, 3rd edition page 167). Three blocks defined by Perl (and here) may * not be in the Unicode: IsHighPrivateUseSurrogates, IsHighSurrogates, and IsLowSurrogates. * **/ // Has to be sorted by the first column private static readonly string[][] s_propTable = { new[] {"IsAlphabeticPresentationForms", "\uFB00\uFB50"}, new[] {"IsArabic", "\u0600\u0700"}, new[] {"IsArabicPresentationForms-A", "\uFB50\uFE00"}, new[] {"IsArabicPresentationForms-B", "\uFE70\uFF00"}, new[] {"IsArmenian", "\u0530\u0590"}, new[] {"IsArrows", "\u2190\u2200"}, new[] {"IsBasicLatin", "\u0000\u0080"}, new[] {"IsBengali", "\u0980\u0A00"}, new[] {"IsBlockElements", "\u2580\u25A0"}, new[] {"IsBopomofo", "\u3100\u3130"}, new[] {"IsBopomofoExtended", "\u31A0\u31C0"}, new[] {"IsBoxDrawing", "\u2500\u2580"}, new[] {"IsBraillePatterns", "\u2800\u2900"}, new[] {"IsBuhid", "\u1740\u1760"}, new[] {"IsCJKCompatibility", "\u3300\u3400"}, new[] {"IsCJKCompatibilityForms", "\uFE30\uFE50"}, new[] {"IsCJKCompatibilityIdeographs", "\uF900\uFB00"}, new[] {"IsCJKRadicalsSupplement", "\u2E80\u2F00"}, new[] {"IsCJKSymbolsandPunctuation", "\u3000\u3040"}, new[] {"IsCJKUnifiedIdeographs", "\u4E00\uA000"}, new[] {"IsCJKUnifiedIdeographsExtensionA", "\u3400\u4DC0"}, new[] {"IsCherokee", "\u13A0\u1400"}, new[] {"IsCombiningDiacriticalMarks", "\u0300\u0370"}, new[] {"IsCombiningDiacriticalMarksforSymbols", "\u20D0\u2100"}, new[] {"IsCombiningHalfMarks", "\uFE20\uFE30"}, new[] {"IsCombiningMarksforSymbols", "\u20D0\u2100"}, new[] {"IsControlPictures", "\u2400\u2440"}, new[] {"IsCurrencySymbols", "\u20A0\u20D0"}, new[] {"IsCyrillic", "\u0400\u0500"}, new[] {"IsCyrillicSupplement", "\u0500\u0530"}, new[] {"IsDevanagari", "\u0900\u0980"}, new[] {"IsDingbats", "\u2700\u27C0"}, new[] {"IsEnclosedAlphanumerics", "\u2460\u2500"}, new[] {"IsEnclosedCJKLettersandMonths", "\u3200\u3300"}, new[] {"IsEthiopic", "\u1200\u1380"}, new[] {"IsGeneralPunctuation", "\u2000\u2070"}, new[] {"IsGeometricShapes", "\u25A0\u2600"}, new[] {"IsGeorgian", "\u10A0\u1100"}, new[] {"IsGreek", "\u0370\u0400"}, new[] {"IsGreekExtended", "\u1F00\u2000"}, new[] {"IsGreekandCoptic", "\u0370\u0400"}, new[] {"IsGujarati", "\u0A80\u0B00"}, new[] {"IsGurmukhi", "\u0A00\u0A80"}, new[] {"IsHalfwidthandFullwidthForms", "\uFF00\uFFF0"}, new[] {"IsHangulCompatibilityJamo", "\u3130\u3190"}, new[] {"IsHangulJamo", "\u1100\u1200"}, new[] {"IsHangulSyllables", "\uAC00\uD7B0"}, new[] {"IsHanunoo", "\u1720\u1740"}, new[] {"IsHebrew", "\u0590\u0600"}, new[] {"IsHighPrivateUseSurrogates", "\uDB80\uDC00"}, new[] {"IsHighSurrogates", "\uD800\uDB80"}, new[] {"IsHiragana", "\u3040\u30A0"}, new[] {"IsIPAExtensions", "\u0250\u02B0"}, new[] {"IsIdeographicDescriptionCharacters", "\u2FF0\u3000"}, new[] {"IsKanbun", "\u3190\u31A0"}, new[] {"IsKangxiRadicals", "\u2F00\u2FE0"}, new[] {"IsKannada", "\u0C80\u0D00"}, new[] {"IsKatakana", "\u30A0\u3100"}, new[] {"IsKatakanaPhoneticExtensions", "\u31F0\u3200"}, new[] {"IsKhmer", "\u1780\u1800"}, new[] {"IsKhmerSymbols", "\u19E0\u1A00"}, new[] {"IsLao", "\u0E80\u0F00"}, new[] {"IsLatin-1Supplement", "\u0080\u0100"}, new[] {"IsLatinExtended-A", "\u0100\u0180"}, new[] {"IsLatinExtended-B", "\u0180\u0250"}, new[] {"IsLatinExtendedAdditional", "\u1E00\u1F00"}, new[] {"IsLetterlikeSymbols", "\u2100\u2150"}, new[] {"IsLimbu", "\u1900\u1950"}, new[] {"IsLowSurrogates", "\uDC00\uE000"}, new[] {"IsMalayalam", "\u0D00\u0D80"}, new[] {"IsMathematicalOperators", "\u2200\u2300"}, new[] {"IsMiscellaneousMathematicalSymbols-A", "\u27C0\u27F0"}, new[] {"IsMiscellaneousMathematicalSymbols-B", "\u2980\u2A00"}, new[] {"IsMiscellaneousSymbols", "\u2600\u2700"}, new[] {"IsMiscellaneousSymbolsandArrows", "\u2B00\u2C00"}, new[] {"IsMiscellaneousTechnical", "\u2300\u2400"}, new[] {"IsMongolian", "\u1800\u18B0"}, new[] {"IsMyanmar", "\u1000\u10A0"}, new[] {"IsNumberForms", "\u2150\u2190"}, new[] {"IsOgham", "\u1680\u16A0"}, new[] {"IsOpticalCharacterRecognition", "\u2440\u2460"}, new[] {"IsOriya", "\u0B00\u0B80"}, new[] {"IsPhoneticExtensions", "\u1D00\u1D80"}, new[] {"IsPrivateUse", "\uE000\uF900"}, new[] {"IsPrivateUseArea", "\uE000\uF900"}, new[] {"IsRunic", "\u16A0\u1700"}, new[] {"IsSinhala", "\u0D80\u0E00"}, new[] {"IsSmallFormVariants", "\uFE50\uFE70"}, new[] {"IsSpacingModifierLetters", "\u02B0\u0300"}, new[] {"IsSpecials", "\uFFF0"}, new[] {"IsSuperscriptsandSubscripts", "\u2070\u20A0"}, new[] {"IsSupplementalArrows-A", "\u27F0\u2800"}, new[] {"IsSupplementalArrows-B", "\u2900\u2980"}, new[] {"IsSupplementalMathematicalOperators", "\u2A00\u2B00"}, new[] {"IsSyriac", "\u0700\u0750"}, new[] {"IsTagalog", "\u1700\u1720"}, new[] {"IsTagbanwa", "\u1760\u1780"}, new[] {"IsTaiLe", "\u1950\u1980"}, new[] {"IsTamil", "\u0B80\u0C00"}, new[] {"IsTelugu", "\u0C00\u0C80"}, new[] {"IsThaana", "\u0780\u07C0"}, new[] {"IsThai", "\u0E00\u0E80"}, new[] {"IsTibetan", "\u0F00\u1000"}, new[] {"IsUnifiedCanadianAboriginalSyllabics", "\u1400\u1680"}, new[] {"IsVariationSelectors", "\uFE00\uFE10"}, new[] {"IsYiRadicals", "\uA490\uA4D0"}, new[] {"IsYiSyllables", "\uA000\uA490"}, new[] {"IsYijingHexagramSymbols", "\u4DC0\u4E00"}, new[] {"_xmlC", /* Name Char */ "\u002D\u002F\u0030\u003B\u0041\u005B\u005F\u0060\u0061\u007B\u00B7\u00B8\u00C0\u00D7\u00D8\u00F7\u00F8\u0132\u0134\u013F\u0141\u0149\u014A\u017F\u0180\u01C4\u01CD\u01F1\u01F4\u01F6\u01FA\u0218\u0250\u02A9\u02BB\u02C2\u02D0\u02D2\u0300\u0346\u0360\u0362\u0386\u038B\u038C\u038D\u038E\u03A2\u03A3\u03CF\u03D0\u03D7\u03DA\u03DB\u03DC\u03DD\u03DE\u03DF\u03E0\u03E1\u03E2\u03F4\u0401\u040D\u040E\u0450\u0451\u045D\u045E\u0482\u0483\u0487\u0490\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04EC\u04EE\u04F6\u04F8\u04FA\u0531\u0557\u0559\u055A\u0561\u0587\u0591\u05A2\u05A3\u05BA\u05BB\u05BE\u05BF\u05C0\u05C1\u05C3\u05C4\u05C5\u05D0\u05EB\u05F0\u05F3\u0621\u063B\u0640\u0653\u0660\u066A\u0670\u06B8\u06BA\u06BF\u06C0\u06CF\u06D0\u06D4\u06D5\u06E9\u06EA\u06EE\u06F0\u06FA\u0901\u0904\u0905\u093A\u093C\u094E\u0951\u0955\u0958\u0964\u0966\u0970\u0981\u0984\u0985\u098D\u098F\u0991\u0993\u09A9\u09AA\u09B1\u09B2\u09B3\u09B6\u09BA\u09BC\u09BD\u09BE\u09C5\u09C7\u09C9\u09CB\u09CE\u09D7\u09D8\u09DC" +"\u09DE\u09DF\u09E4\u09E6\u09F2\u0A02\u0A03\u0A05\u0A0B\u0A0F\u0A11\u0A13\u0A29\u0A2A\u0A31\u0A32\u0A34\u0A35\u0A37\u0A38\u0A3A\u0A3C\u0A3D\u0A3E\u0A43\u0A47\u0A49\u0A4B\u0A4E\u0A59\u0A5D\u0A5E\u0A5F\u0A66\u0A75\u0A81\u0A84\u0A85\u0A8C\u0A8D\u0A8E\u0A8F\u0A92\u0A93\u0AA9\u0AAA\u0AB1\u0AB2\u0AB4\u0AB5\u0ABA\u0ABC\u0AC6\u0AC7\u0ACA\u0ACB\u0ACE\u0AE0\u0AE1\u0AE6\u0AF0\u0B01\u0B04\u0B05\u0B0D\u0B0F\u0B11\u0B13\u0B29\u0B2A\u0B31\u0B32\u0B34\u0B36\u0B3A\u0B3C\u0B44\u0B47\u0B49\u0B4B\u0B4E\u0B56\u0B58\u0B5C\u0B5E\u0B5F\u0B62\u0B66\u0B70\u0B82\u0B84\u0B85\u0B8B\u0B8E\u0B91\u0B92\u0B96\u0B99\u0B9B\u0B9C\u0B9D\u0B9E\u0BA0\u0BA3\u0BA5\u0BA8\u0BAB\u0BAE\u0BB6\u0BB7\u0BBA\u0BBE\u0BC3\u0BC6\u0BC9\u0BCA\u0BCE\u0BD7\u0BD8\u0BE7\u0BF0\u0C01\u0C04\u0C05\u0C0D\u0C0E\u0C11\u0C12\u0C29\u0C2A\u0C34\u0C35\u0C3A\u0C3E\u0C45\u0C46\u0C49\u0C4A\u0C4E\u0C55\u0C57\u0C60\u0C62\u0C66\u0C70\u0C82\u0C84\u0C85\u0C8D\u0C8E\u0C91\u0C92\u0CA9\u0CAA\u0CB4\u0CB5\u0CBA\u0CBE\u0CC5\u0CC6\u0CC9\u0CCA\u0CCE\u0CD5\u0CD7\u0CDE\u0CDF\u0CE0\u0CE2" +"\u0CE6\u0CF0\u0D02\u0D04\u0D05\u0D0D\u0D0E\u0D11\u0D12\u0D29\u0D2A\u0D3A\u0D3E\u0D44\u0D46\u0D49\u0D4A\u0D4E\u0D57\u0D58\u0D60\u0D62\u0D66\u0D70\u0E01\u0E2F\u0E30\u0E3B\u0E40\u0E4F\u0E50\u0E5A\u0E81\u0E83\u0E84\u0E85\u0E87\u0E89\u0E8A\u0E8B\u0E8D\u0E8E\u0E94\u0E98\u0E99\u0EA0\u0EA1\u0EA4\u0EA5\u0EA6\u0EA7\u0EA8\u0EAA\u0EAC\u0EAD\u0EAF\u0EB0\u0EBA\u0EBB\u0EBE\u0EC0\u0EC5\u0EC6\u0EC7\u0EC8\u0ECE\u0ED0\u0EDA\u0F18\u0F1A\u0F20\u0F2A\u0F35\u0F36\u0F37\u0F38\u0F39\u0F3A\u0F3E\u0F48\u0F49\u0F6A\u0F71\u0F85\u0F86\u0F8C\u0F90\u0F96\u0F97\u0F98\u0F99\u0FAE\u0FB1\u0FB8\u0FB9\u0FBA\u10A0\u10C6\u10D0\u10F7\u1100\u1101\u1102\u1104\u1105\u1108\u1109\u110A\u110B\u110D\u110E\u1113\u113C\u113D\u113E\u113F\u1140\u1141\u114C\u114D\u114E\u114F\u1150\u1151\u1154\u1156\u1159\u115A\u115F\u1162\u1163\u1164\u1165\u1166\u1167\u1168\u1169\u116A\u116D\u116F\u1172\u1174\u1175\u1176\u119E\u119F\u11A8\u11A9\u11AB\u11AC\u11AE\u11B0\u11B7\u11B9\u11BA\u11BB\u11BC\u11C3\u11EB\u11EC\u11F0\u11F1\u11F9\u11FA\u1E00\u1E9C\u1EA0\u1EFA\u1F00" +"\u1F16\u1F18\u1F1E\u1F20\u1F46\u1F48\u1F4E\u1F50\u1F58\u1F59\u1F5A\u1F5B\u1F5C\u1F5D\u1F5E\u1F5F\u1F7E\u1F80\u1FB5\u1FB6\u1FBD\u1FBE\u1FBF\u1FC2\u1FC5\u1FC6\u1FCD\u1FD0\u1FD4\u1FD6\u1FDC\u1FE0\u1FED\u1FF2\u1FF5\u1FF6\u1FFD\u20D0\u20DD\u20E1\u20E2\u2126\u2127\u212A\u212C\u212E\u212F\u2180\u2183\u3005\u3006\u3007\u3008\u3021\u3030\u3031\u3036\u3041\u3095\u3099\u309B\u309D\u309F\u30A1\u30FB\u30FC\u30FF\u3105\u312D\u4E00\u9FA6\uAC00\uD7A4"}, new[] {"_xmlD", "\u0030\u003A\u0660\u066A\u06F0\u06FA\u0966\u0970\u09E6\u09F0\u0A66\u0A70\u0AE6\u0AF0\u0B66\u0B70\u0BE7\u0BF0\u0C66\u0C70\u0CE6\u0CF0\u0D66\u0D70\u0E50\u0E5A\u0ED0\u0EDA\u0F20\u0F2A\u1040\u104A\u1369\u1372\u17E0\u17EA\u1810\u181A\uFF10\uFF1A"}, new[] {"_xmlI", /* Start Name Char */ "\u003A\u003B\u0041\u005B\u005F\u0060\u0061\u007B\u00C0\u00D7\u00D8\u00F7\u00F8\u0132\u0134\u013F\u0141\u0149\u014A\u017F\u0180\u01C4\u01CD\u01F1\u01F4\u01F6\u01FA\u0218\u0250\u02A9\u02BB\u02C2\u0386\u0387\u0388\u038B\u038C\u038D\u038E\u03A2\u03A3\u03CF\u03D0\u03D7\u03DA\u03DB\u03DC\u03DD\u03DE\u03DF\u03E0\u03E1\u03E2\u03F4\u0401\u040D\u040E\u0450\u0451\u045D\u045E\u0482\u0490\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04EC\u04EE\u04F6\u04F8\u04FA\u0531\u0557\u0559\u055A\u0561\u0587\u05D0\u05EB\u05F0\u05F3\u0621\u063B\u0641\u064B\u0671\u06B8\u06BA\u06BF\u06C0\u06CF\u06D0\u06D4\u06D5\u06D6\u06E5\u06E7\u0905\u093A\u093D\u093E\u0958\u0962\u0985\u098D\u098F\u0991\u0993\u09A9\u09AA\u09B1\u09B2\u09B3\u09B6\u09BA\u09DC\u09DE\u09DF\u09E2\u09F0\u09F2\u0A05\u0A0B\u0A0F\u0A11\u0A13\u0A29\u0A2A\u0A31\u0A32\u0A34\u0A35\u0A37\u0A38\u0A3A\u0A59\u0A5D\u0A5E\u0A5F\u0A72\u0A75\u0A85\u0A8C\u0A8D\u0A8E\u0A8F\u0A92\u0A93\u0AA9\u0AAA\u0AB1\u0AB2\u0AB4\u0AB5\u0ABA\u0ABD\u0ABE\u0AE0\u0AE1\u0B05\u0B0D\u0B0F" +"\u0B11\u0B13\u0B29\u0B2A\u0B31\u0B32\u0B34\u0B36\u0B3A\u0B3D\u0B3E\u0B5C\u0B5E\u0B5F\u0B62\u0B85\u0B8B\u0B8E\u0B91\u0B92\u0B96\u0B99\u0B9B\u0B9C\u0B9D\u0B9E\u0BA0\u0BA3\u0BA5\u0BA8\u0BAB\u0BAE\u0BB6\u0BB7\u0BBA\u0C05\u0C0D\u0C0E\u0C11\u0C12\u0C29\u0C2A\u0C34\u0C35\u0C3A\u0C60\u0C62\u0C85\u0C8D\u0C8E\u0C91\u0C92\u0CA9\u0CAA\u0CB4\u0CB5\u0CBA\u0CDE\u0CDF\u0CE0\u0CE2\u0D05\u0D0D\u0D0E\u0D11\u0D12\u0D29\u0D2A\u0D3A\u0D60\u0D62\u0E01\u0E2F\u0E30\u0E31\u0E32\u0E34\u0E40\u0E46\u0E81\u0E83\u0E84\u0E85\u0E87\u0E89\u0E8A\u0E8B\u0E8D\u0E8E\u0E94\u0E98\u0E99\u0EA0\u0EA1\u0EA4\u0EA5\u0EA6\u0EA7\u0EA8\u0EAA\u0EAC\u0EAD\u0EAF\u0EB0\u0EB1\u0EB2\u0EB4\u0EBD\u0EBE\u0EC0\u0EC5\u0F40\u0F48\u0F49\u0F6A\u10A0\u10C6\u10D0\u10F7\u1100\u1101\u1102\u1104\u1105\u1108\u1109\u110A\u110B\u110D\u110E\u1113\u113C\u113D\u113E\u113F\u1140\u1141\u114C\u114D\u114E\u114F\u1150\u1151\u1154\u1156\u1159\u115A\u115F\u1162\u1163\u1164\u1165\u1166\u1167\u1168\u1169\u116A\u116D\u116F\u1172\u1174\u1175\u1176\u119E\u119F\u11A8\u11A9\u11AB\u11AC" +"\u11AE\u11B0\u11B7\u11B9\u11BA\u11BB\u11BC\u11C3\u11EB\u11EC\u11F0\u11F1\u11F9\u11FA\u1E00\u1E9C\u1EA0\u1EFA\u1F00\u1F16\u1F18\u1F1E\u1F20\u1F46\u1F48\u1F4E\u1F50\u1F58\u1F59\u1F5A\u1F5B\u1F5C\u1F5D\u1F5E\u1F5F\u1F7E\u1F80\u1FB5\u1FB6\u1FBD\u1FBE\u1FBF\u1FC2\u1FC5\u1FC6\u1FCD\u1FD0\u1FD4\u1FD6\u1FDC\u1FE0\u1FED\u1FF2\u1FF5\u1FF6\u1FFD\u2126\u2127\u212A\u212C\u212E\u212F\u2180\u2183\u3007\u3008\u3021\u302A\u3041\u3095\u30A1\u30FB\u3105\u312D\u4E00\u9FA6\uAC00\uD7A4"}, new[] {"_xmlW", "\u0024\u0025\u002B\u002C\u0030\u003A\u003C\u003F\u0041\u005B\u005E\u005F\u0060\u007B\u007C\u007D\u007E\u007F\u00A2\u00AB\u00AC\u00AD\u00AE\u00B7\u00B8\u00BB\u00BC\u00BF\u00C0\u0221\u0222\u0234\u0250\u02AE\u02B0\u02EF\u0300\u0350\u0360\u0370\u0374\u0376\u037A\u037B\u0384\u0387\u0388\u038B\u038C\u038D\u038E\u03A2\u03A3\u03CF\u03D0\u03F7\u0400\u0487\u0488\u04CF\u04D0\u04F6\u04F8\u04FA\u0500\u0510\u0531\u0557\u0559\u055A\u0561\u0588\u0591\u05A2\u05A3\u05BA\u05BB\u05BE\u05BF\u05C0\u05C1\u05C3\u05C4\u05C5\u05D0\u05EB\u05F0\u05F3\u0621\u063B\u0640\u0656\u0660\u066A\u066E\u06D4\u06D5\u06DD\u06DE\u06EE\u06F0\u06FF\u0710\u072D\u0730\u074B\u0780\u07B2\u0901\u0904\u0905\u093A\u093C\u094E\u0950\u0955\u0958\u0964\u0966\u0970\u0981\u0984\u0985\u098D\u098F\u0991\u0993\u09A9\u09AA\u09B1\u09B2\u09B3\u09B6\u09BA\u09BC\u09BD\u09BE\u09C5\u09C7\u09C9\u09CB\u09CE\u09D7\u09D8\u09DC\u09DE\u09DF\u09E4\u09E6\u09FB\u0A02\u0A03\u0A05\u0A0B\u0A0F\u0A11\u0A13\u0A29\u0A2A\u0A31\u0A32\u0A34\u0A35" +"\u0A37\u0A38\u0A3A\u0A3C\u0A3D\u0A3E\u0A43\u0A47\u0A49\u0A4B\u0A4E\u0A59\u0A5D\u0A5E\u0A5F\u0A66\u0A75\u0A81\u0A84\u0A85\u0A8C\u0A8D\u0A8E\u0A8F\u0A92\u0A93\u0AA9\u0AAA\u0AB1\u0AB2\u0AB4\u0AB5\u0ABA\u0ABC\u0AC6\u0AC7\u0ACA\u0ACB\u0ACE\u0AD0\u0AD1\u0AE0\u0AE1\u0AE6\u0AF0\u0B01\u0B04\u0B05\u0B0D\u0B0F\u0B11\u0B13\u0B29\u0B2A\u0B31\u0B32\u0B34\u0B36\u0B3A\u0B3C\u0B44\u0B47\u0B49\u0B4B\u0B4E\u0B56\u0B58\u0B5C\u0B5E\u0B5F\u0B62\u0B66\u0B71\u0B82\u0B84\u0B85\u0B8B\u0B8E\u0B91\u0B92\u0B96\u0B99\u0B9B\u0B9C\u0B9D\u0B9E\u0BA0\u0BA3\u0BA5\u0BA8\u0BAB\u0BAE\u0BB6\u0BB7\u0BBA\u0BBE\u0BC3\u0BC6\u0BC9\u0BCA\u0BCE\u0BD7\u0BD8\u0BE7\u0BF3\u0C01\u0C04\u0C05\u0C0D\u0C0E\u0C11\u0C12\u0C29\u0C2A\u0C34\u0C35\u0C3A\u0C3E\u0C45\u0C46\u0C49\u0C4A\u0C4E\u0C55\u0C57\u0C60\u0C62\u0C66\u0C70\u0C82\u0C84\u0C85\u0C8D\u0C8E\u0C91\u0C92\u0CA9\u0CAA\u0CB4\u0CB5\u0CBA\u0CBE\u0CC5\u0CC6\u0CC9\u0CCA\u0CCE\u0CD5\u0CD7\u0CDE\u0CDF\u0CE0\u0CE2\u0CE6\u0CF0\u0D02\u0D04\u0D05\u0D0D\u0D0E\u0D11\u0D12\u0D29\u0D2A\u0D3A\u0D3E\u0D44\u0D46\u0D49" +"\u0D4A\u0D4E\u0D57\u0D58\u0D60\u0D62\u0D66\u0D70\u0D82\u0D84\u0D85\u0D97\u0D9A\u0DB2\u0DB3\u0DBC\u0DBD\u0DBE\u0DC0\u0DC7\u0DCA\u0DCB\u0DCF\u0DD5\u0DD6\u0DD7\u0DD8\u0DE0\u0DF2\u0DF4\u0E01\u0E3B\u0E3F\u0E4F\u0E50\u0E5A\u0E81\u0E83\u0E84\u0E85\u0E87\u0E89\u0E8A\u0E8B\u0E8D\u0E8E\u0E94\u0E98\u0E99\u0EA0\u0EA1\u0EA4\u0EA5\u0EA6\u0EA7\u0EA8\u0EAA\u0EAC\u0EAD\u0EBA\u0EBB\u0EBE\u0EC0\u0EC5\u0EC6\u0EC7\u0EC8\u0ECE\u0ED0\u0EDA\u0EDC\u0EDE\u0F00\u0F04\u0F13\u0F3A\u0F3E\u0F48\u0F49\u0F6B\u0F71\u0F85\u0F86\u0F8C\u0F90\u0F98\u0F99\u0FBD\u0FBE\u0FCD\u0FCF\u0FD0\u1000\u1022\u1023\u1028\u1029\u102B\u102C\u1033\u1036\u103A\u1040\u104A\u1050\u105A\u10A0\u10C6\u10D0\u10F9\u1100\u115A\u115F\u11A3\u11A8\u11FA\u1200\u1207\u1208\u1247\u1248\u1249\u124A\u124E\u1250\u1257\u1258\u1259\u125A\u125E\u1260\u1287\u1288\u1289\u128A\u128E\u1290\u12AF\u12B0\u12B1\u12B2\u12B6\u12B8\u12BF\u12C0\u12C1\u12C2\u12C6\u12C8\u12CF\u12D0\u12D7\u12D8\u12EF\u12F0\u130F\u1310\u1311\u1312\u1316\u1318\u131F\u1320\u1347\u1348\u135B\u1369\u137D\u13A0" +"\u13F5\u1401\u166D\u166F\u1677\u1681\u169B\u16A0\u16EB\u16EE\u16F1\u1700\u170D\u170E\u1715\u1720\u1735\u1740\u1754\u1760\u176D\u176E\u1771\u1772\u1774\u1780\u17D4\u17D7\u17D8\u17DB\u17DD\u17E0\u17EA\u180B\u180E\u1810\u181A\u1820\u1878\u1880\u18AA\u1E00\u1E9C\u1EA0\u1EFA\u1F00\u1F16\u1F18\u1F1E\u1F20\u1F46\u1F48\u1F4E\u1F50\u1F58\u1F59\u1F5A\u1F5B\u1F5C\u1F5D\u1F5E\u1F5F\u1F7E\u1F80\u1FB5\u1FB6\u1FC5\u1FC6\u1FD4\u1FD6\u1FDC\u1FDD\u1FF0\u1FF2\u1FF5\u1FF6\u1FFF\u2044\u2045\u2052\u2053\u2070\u2072\u2074\u207D\u207F\u208D\u20A0\u20B2\u20D0\u20EB\u2100\u213B\u213D\u214C\u2153\u2184\u2190\u2329\u232B\u23B4\u23B7\u23CF\u2400\u2427\u2440\u244B\u2460\u24FF\u2500\u2614\u2616\u2618\u2619\u267E\u2680\u268A\u2701\u2705\u2706\u270A\u270C\u2728\u2729\u274C\u274D\u274E\u274F\u2753\u2756\u2757\u2758\u275F\u2761\u2768\u2776\u2795\u2798\u27B0\u27B1\u27BF\u27D0\u27E6\u27F0\u2983\u2999\u29D8\u29DC\u29FC\u29FE\u2B00\u2E80\u2E9A\u2E9B\u2EF4\u2F00\u2FD6\u2FF0\u2FFC\u3004\u3008\u3012\u3014\u3020\u3030\u3031\u303D\u303E\u3040" +"\u3041\u3097\u3099\u30A0\u30A1\u30FB\u30FC\u3100\u3105\u312D\u3131\u318F\u3190\u31B8\u31F0\u321D\u3220\u3244\u3251\u327C\u327F\u32CC\u32D0\u32FF\u3300\u3377\u337B\u33DE\u33E0\u33FF\u3400\u4DB6\u4E00\u9FA6\uA000\uA48D\uA490\uA4C7\uAC00\uD7A4\uF900\uFA2E\uFA30\uFA6B\uFB00\uFB07\uFB13\uFB18\uFB1D\uFB37\uFB38\uFB3D\uFB3E\uFB3F\uFB40\uFB42\uFB43\uFB45\uFB46\uFBB2\uFBD3\uFD3E\uFD50\uFD90\uFD92\uFDC8\uFDF0\uFDFD\uFE00\uFE10\uFE20\uFE24\uFE62\uFE63\uFE64\uFE67\uFE69\uFE6A\uFE70\uFE75\uFE76\uFEFD\uFF04\uFF05\uFF0B\uFF0C\uFF10\uFF1A\uFF1C\uFF1F\uFF21\uFF3B\uFF3E\uFF3F\uFF40\uFF5B\uFF5C\uFF5D\uFF5E\uFF5F\uFF66\uFFBF\uFFC2\uFFC8\uFFCA\uFFD0\uFFD2\uFFD8\uFFDA\uFFDD\uFFE0\uFFE7\uFFE8\uFFEF\uFFFC\uFFFE"}, }; private List<(char First, char Last)>? _rangelist; private StringBuilder? _categories; private RegexCharClass? _subtractor; private bool _negate; #if DEBUG static RegexCharClass() { // Make sure the initial capacity for s_definedCategories is correct Debug.Assert( s_definedCategories.Count == DefinedCategoriesCapacity, $"Expected (s_definedCategories.Count): {s_definedCategories.Count}, Actual (DefinedCategoriesCapacity): {DefinedCategoriesCapacity}"); // Make sure the s_propTable is correctly ordered int len = s_propTable.Length; for (int i = 0; i < len - 1; i++) Debug.Assert(string.Compare(s_propTable[i][0], s_propTable[i + 1][0], StringComparison.Ordinal) < 0, $"RegexCharClass s_propTable is out of order at ({s_propTable[i][0]}, {s_propTable[i + 1][0]})"); } #endif /// <summary> /// Creates an empty character class. /// </summary> public RegexCharClass() { } private RegexCharClass(bool negate, List<(char First, char Last)>? ranges, StringBuilder? categories, RegexCharClass? subtraction) { _rangelist = ranges; _categories = categories; _negate = negate; _subtractor = subtraction; } public bool CanMerge => !_negate && _subtractor == null; public bool Negate { set { _negate = value; } } public void AddChar(char c) => AddRange(c, c); /// <summary> /// Adds a regex char class /// </summary> public void AddCharClass(RegexCharClass cc) { Debug.Assert(cc.CanMerge && CanMerge, "Both character classes added together must be able to merge"); int ccRangeCount = cc._rangelist?.Count ?? 0; if (ccRangeCount != 0) { EnsureRangeList().AddRange(cc._rangelist!); } if (cc._categories != null) { EnsureCategories().Append(cc._categories); } } /// <summary>Adds a regex char class if the classes are mergeable.</summary> public bool TryAddCharClass(RegexCharClass cc) { if (cc.CanMerge && CanMerge) { AddCharClass(cc); return true; } return false; } private StringBuilder EnsureCategories() => _categories ??= new StringBuilder(); private List<(char First, char Last)> EnsureRangeList() => _rangelist ??= new List<(char First, char Last)>(6); /// <summary> /// Adds a set (specified by its string representation) to the class. /// </summary> private void AddSet(ReadOnlySpan<char> set) { if (set.Length == 0) { return; } List<(char First, char Last)> rangeList = EnsureRangeList(); int i; for (i = 0; i < set.Length - 1; i += 2) { rangeList.Add((set[i], (char)(set[i + 1] - 1))); } if (i < set.Length) { rangeList.Add((set[i], LastChar)); } } public void AddSubtraction(RegexCharClass sub) { Debug.Assert(_subtractor == null, "Can't add two subtractions to a char class. "); _subtractor = sub; } /// <summary> /// Adds a single range of characters to the class. /// </summary> public void AddRange(char first, char last) => EnsureRangeList().Add((first, last)); public void AddCategoryFromName(string categoryName, bool invert, bool caseInsensitive, string pattern, int currentPos) { if (s_definedCategories.TryGetValue(categoryName, out string? category) && !categoryName.Equals(InternalRegexIgnoreCase)) { if (caseInsensitive && (categoryName.Equals("Ll") || categoryName.Equals("Lu") || categoryName.Equals("Lt"))) { // when RegexOptions.IgnoreCase is specified then {Ll}, {Lu}, and {Lt} cases should all match category = s_definedCategories[InternalRegexIgnoreCase]; } StringBuilder categories = EnsureCategories(); if (invert) { // Negate category for (int i = 0; i < category.Length; i++) { short ch = (short)category[i]; categories.Append((char)-ch); } } else { categories.Append(category); } } else { AddSet(SetFromProperty(categoryName, invert, pattern, currentPos)); } } private void AddCategory(string category) => EnsureCategories().Append(category); /// <summary> /// Adds to the class any lowercase versions of characters already /// in the class. Used for case-insensitivity. /// </summary> public void AddLowercase(CultureInfo culture) { List<(char First, char Last)>? rangeList = _rangelist; if (rangeList != null) { int count = rangeList.Count; for (int i = 0; i < count; i++) { (char First, char Last) range = rangeList[i]; if (range.First == range.Last) { char lower = culture.TextInfo.ToLower(range.First); rangeList[i] = (lower, lower); } else { AddLowercaseRange(range.First, range.Last); } } } } /// <summary> /// For a single range that's in the set, adds any additional ranges /// necessary to ensure that lowercase equivalents are also included. /// </summary> private void AddLowercaseRange(char chMin, char chMax) { int i = 0; for (int iMax = s_lcTable.Length; i < iMax;) { int iMid = (i + iMax) >> 1; if (s_lcTable[iMid].ChMax < chMin) { i = iMid + 1; } else { iMax = iMid; } } if (i >= s_lcTable.Length) { return; } char chMinT, chMaxT; LowerCaseMapping lc; for (; i < s_lcTable.Length && (lc = s_lcTable[i]).ChMin <= chMax; i++) { if ((chMinT = lc.ChMin) < chMin) { chMinT = chMin; } if ((chMaxT = lc.ChMax) > chMax) { chMaxT = chMax; } switch (lc.LcOp) { case LowercaseSet: chMinT = (char)lc.Data; chMaxT = (char)lc.Data; break; case LowercaseAdd: chMinT += (char)lc.Data; chMaxT += (char)lc.Data; break; case LowercaseBor: chMinT |= (char)1; chMaxT |= (char)1; break; case LowercaseBad: chMinT += (char)(chMinT & 1); chMaxT += (char)(chMaxT & 1); break; } if (chMinT < chMin || chMaxT > chMax) { AddRange(chMinT, chMaxT); } } } public void AddWord(bool ecma, bool negate) { if (ecma) { AddSet((negate ? NotECMAWordSet : ECMAWordSet).AsSpan()); } else { AddCategory(negate ? NotWord : Word); } } public void AddSpace(bool ecma, bool negate) { if (ecma) { AddSet((negate ? NotECMASpaceSet : ECMASpaceSet).AsSpan()); } else { AddCategory(negate ? NotSpace : Space); } } public void AddDigit(bool ecma, bool negate, string pattern, int currentPos) { if (ecma) { AddSet((negate ? NotECMADigitSet : ECMADigitSet).AsSpan()); } else { AddCategoryFromName("Nd", negate, caseInsensitive: false, pattern, currentPos); } } public static string ConvertOldStringsToClass(string set, string category) { bool startsWithNulls = set.Length >= 2 && set[0] == '\0' && set[1] == '\0'; int strLength = SetStartIndex + set.Length + category.Length; if (startsWithNulls) { strLength -= 2; } #if REGEXGENERATOR return StringExtensions.Create #else return string.Create #endif (strLength, (set, category, startsWithNulls), static (span, state) => { int index; if (state.startsWithNulls) { span[FlagsIndex] = (char)0x1; span[SetLengthIndex] = (char)(state.set.Length - 2); span[CategoryLengthIndex] = (char)state.category.Length; state.set.AsSpan(2).CopyTo(span.Slice(SetStartIndex)); index = SetStartIndex + state.set.Length - 2; } else { span[FlagsIndex] = '\0'; span[SetLengthIndex] = (char)state.set.Length; span[CategoryLengthIndex] = (char)state.category.Length; state.set.AsSpan().CopyTo(span.Slice(SetStartIndex)); index = SetStartIndex + state.set.Length; } state.category.AsSpan().CopyTo(span.Slice(index)); }); } /// <summary> /// Returns the char /// </summary> public static char SingletonChar(string set) { Debug.Assert(IsSingleton(set) || IsSingletonInverse(set), "Tried to get the singleton char out of a non singleton character class"); return set[SetStartIndex]; } public static bool IsMergeable(string charClass) => charClass != null && !IsNegated(charClass) && !IsSubtraction(charClass); public static bool IsEmpty(string charClass) => charClass[CategoryLengthIndex] == 0 && charClass[SetLengthIndex] == 0 && !IsNegated(charClass) && !IsSubtraction(charClass); /// <summary><c>true</c> if the set contains a single character only</summary> /// <remarks> /// This will happen not only from character classes manually written to contain a single character, /// but much more frequently by the implementation/parser itself, e.g. when looking for \n as part of /// finding the end of a line, when processing an alternation like "hello|hithere" where the first /// character of both options is the same, etc. /// </remarks> public static bool IsSingleton(string set) => set[CategoryLengthIndex] == 0 && set[SetLengthIndex] == 2 && !IsNegated(set) && !IsSubtraction(set) && (set[SetStartIndex] == LastChar || set[SetStartIndex] + 1 == set[SetStartIndex + 1]); public static bool IsSingletonInverse(string set) => set[CategoryLengthIndex] == 0 && set[SetLengthIndex] == 2 && IsNegated(set) && !IsSubtraction(set) && (set[SetStartIndex] == LastChar || set[SetStartIndex] + 1 == set[SetStartIndex + 1]); /// <summary>Gets whether the set contains nothing other than a single UnicodeCategory (it may be negated).</summary> /// <param name="set">The set to examine.</param> /// <param name="category">The single category if there was one.</param> /// <param name="negated">true if the single category is a not match.</param> /// <returns>true if a single category could be obtained; otherwise, false.</returns> public static bool TryGetSingleUnicodeCategory(string set, out UnicodeCategory category, out bool negated) { if (set[CategoryLengthIndex] == 1 && set[SetLengthIndex] == 0 && !IsSubtraction(set)) { short c = (short)set[SetStartIndex]; if (c > 0) { if (c != SpaceConst) { category = (UnicodeCategory)(c - 1); negated = IsNegated(set); return true; } } else if (c < 0) { if (c != NotSpaceConst) { category = (UnicodeCategory)(-1 - c); negated = !IsNegated(set); return true; } } } category = default; negated = false; return false; } /// <summary>Attempts to get a single range stored in the set.</summary> /// <param name="set">The set.</param> /// <param name="lowInclusive">The inclusive lower-bound of the range, if available.</param> /// <param name="highInclusive">The inclusive upper-bound of the range, if available.</param> /// <returns>true if the set contained a single range; otherwise, false.</returns> /// <remarks> /// <paramref name="lowInclusive"/> and <paramref name="highInclusive"/> will be equal if the /// range is a singleton or singleton inverse. The range will need to be negated by the caller /// if <see cref="IsNegated(string)"/> is true. /// </remarks> public static bool TryGetSingleRange(string set, out char lowInclusive, out char highInclusive) { if (set[CategoryLengthIndex] == 0 && // must not have any categories set.Length == SetStartIndex + set[SetLengthIndex]) // and no subtraction { switch ((int)set[SetLengthIndex]) { case 1: lowInclusive = set[SetStartIndex]; highInclusive = LastChar; return true; case 2: lowInclusive = set[SetStartIndex]; highInclusive = (char)(set[SetStartIndex + 1] - 1); return true; } } lowInclusive = highInclusive = '\0'; return false; } /// <summary>Gets all of the characters in the specified set, storing them into the provided span.</summary> /// <param name="set">The character class.</param> /// <param name="chars">The span into which the chars should be stored.</param> /// <returns> /// The number of stored chars. If they won't all fit, 0 is returned. /// If 0 is returned, no assumptions can be made about the characters. /// </returns> /// <remarks> /// Only considers character classes that only contain sets (no categories) /// and no subtraction... just simple sets containing starting/ending pairs. /// The returned characters may be negated: if IsNegated(set) is false, then /// the returned characters are the only ones that match; if it returns true, /// then the returned characters are the only ones that don't match. /// </remarks> public static int GetSetChars(string set, Span<char> chars) { // We get the characters by enumerating the set portion, so we validate that it's // set up to enable that, e.g. no categories. if (!CanEasilyEnumerateSetContents(set)) { return 0; } // Iterate through the pairs of ranges, storing each value in each range // into the supplied span. If they all won't fit, we give up and return 0. // Otherwise we return the number found. Note that we don't bother to handle // the corner case where the last range's upper bound is LastChar (\uFFFF), // based on it a) complicating things, and b) it being really unlikely to // be part of a small set. int setLength = set[SetLengthIndex]; int count = 0; for (int i = SetStartIndex; i < SetStartIndex + setLength; i += 2) { int curSetEnd = set[i + 1]; for (int c = set[i]; c < curSetEnd; c++) { if (count >= chars.Length) { return 0; } chars[count++] = (char)c; } } return count; } /// <summary> /// Determines whether two sets may overlap. /// </summary> /// <returns>false if the two sets do not overlap; true if they may.</returns> /// <remarks> /// If the method returns false, the caller can be sure the sets do not overlap. /// If the method returns true, it's still possible the sets don't overlap. /// </remarks> public static bool MayOverlap(string set1, string set2) { // If the sets are identical, there's obviously overlap. if (set1 == set2) { return true; } // If either set is all-inclusive, there's overlap by definition (unless // the other set is empty, but that's so rare it's not worth checking.) if (set1 == AnyClass || set2 == AnyClass) { return true; } // If one set is negated and the other one isn't, we're in one of two situations: // - The remainder of the sets are identical, in which case these are inverses of // each other, and they don't overlap. // - The remainder of the sets aren't identical, in which case there's very likely // overlap, and it's not worth spending more time investigating. bool set1Negated = IsNegated(set1); bool set2Negated = IsNegated(set2); if (set1Negated != set2Negated) { return !set1.AsSpan(1).SequenceEqual(set2.AsSpan(1)); } // If the sets are negated, since they're not equal, there's almost certainly overlap. Debug.Assert(set1Negated == set2Negated); if (set1Negated) { return true; } // Special-case some known, common classes that don't overlap. if (KnownDistinctSets(set1, set2) || KnownDistinctSets(set2, set1)) { return false; } // If set2 can be easily enumerated (e.g. no unicode categories), then enumerate it and // check if any of its members are in set1. Otherwise, the same for set1. if (CanEasilyEnumerateSetContents(set2)) { return MayOverlapByEnumeration(set1, set2); } else if (CanEasilyEnumerateSetContents(set1)) { return MayOverlapByEnumeration(set2, set1); } // Assume that everything else might overlap. In the future if it proved impactful, we could be more accurate here, // at the exense of more computation time. return true; static bool KnownDistinctSets(string set1, string set2) => (set1 == SpaceClass || set1 == ECMASpaceClass) && (set2 == DigitClass || set2 == WordClass || set2 == ECMADigitClass || set2 == ECMAWordClass); static bool MayOverlapByEnumeration(string set1, string set2) { Debug.Assert(!IsNegated(set1) && !IsNegated(set2)); for (int i = SetStartIndex; i < SetStartIndex + set2[SetLengthIndex]; i += 2) { int curSetEnd = set2[i + 1]; for (int c = set2[i]; c < curSetEnd; c++) { if (CharInClass((char)c, set1)) { return true; } } } return false; } } /// <summary>Gets whether the specified character participates in case conversion.</summary> /// <remarks> /// This method is used to perform operations as if they were case-sensitive even if they're /// specified as being case-insensitive. Such a reduction can be applied when the only character /// that would lower-case to the one being searched for / compared against is that character itself. /// </remarks> public static bool ParticipatesInCaseConversion(int comparison) { Debug.Assert((uint)comparison <= char.MaxValue); switch (char.GetUnicodeCategory((char)comparison)) { case UnicodeCategory.ClosePunctuation: case UnicodeCategory.ConnectorPunctuation: case UnicodeCategory.Control: case UnicodeCategory.DashPunctuation: case UnicodeCategory.DecimalDigitNumber: case UnicodeCategory.FinalQuotePunctuation: case UnicodeCategory.InitialQuotePunctuation: case UnicodeCategory.LineSeparator: case UnicodeCategory.OpenPunctuation: case UnicodeCategory.OtherNumber: case UnicodeCategory.OtherPunctuation: case UnicodeCategory.ParagraphSeparator: case UnicodeCategory.SpaceSeparator: // All chars in these categories meet the criteria that the only way // `char.ToLower(toTest, AnyCulture) == charInAboveCategory` is when // toTest == charInAboveCategory. return false; default: // We don't know (without testing the character against every other // character), so assume it does. return true; } } /// <summary>Gets whether the specified span participates in case conversion.</summary> /// <remarks>The span participates in case conversion if any of its characters do.</remarks> public static bool ParticipatesInCaseConversion(ReadOnlySpan<char> s) { foreach (char c in s) { if (ParticipatesInCaseConversion(c)) { return true; } } return false; } /// <summary>Gets whether the specified span contains only ASCII.</summary> public static bool IsAscii(ReadOnlySpan<char> s) // TODO https://github.com/dotnet/runtime/issues/28230: Replace once Ascii is available { foreach (char c in s) { if (c >= 128) { return false; } } return true; } /// <summary>Gets whether we can iterate through the set list pairs in order to completely enumerate the set's contents.</summary> /// <remarks>This may enumerate negated characters if the set is negated.</remarks> private static bool CanEasilyEnumerateSetContents(string set) => set.Length > SetStartIndex && set[SetLengthIndex] > 0 && set[SetLengthIndex] % 2 == 0 && set[CategoryLengthIndex] == 0 && !IsSubtraction(set); /// <summary>Provides results from <see cref="Analyze"/>.</summary> internal struct CharClassAnalysisResults { /// <summary>true if we know for sure that the set contains only ASCII values; otherwise, false.</summary> public bool ContainsOnlyAscii; /// <summary>true if we know for sure that the set doesn't contain any ASCII values; otherwise, false.</summary> public bool ContainsNoAscii; /// <summary>true if we know for sure that all ASCII values are in the set; otherwise, false.</summary> public bool AllAsciiContained; /// <summary>true if we know for sure that all non-ASCII values are in the set; otherwise, false.</summary> public bool AllNonAsciiContained; } /// <summary>Analyzes the set to determine some basic properties that can be used to optimize usage.</summary> internal static CharClassAnalysisResults Analyze(string set) { if (!CanEasilyEnumerateSetContents(set)) { // We can't make any strong claims about the set. return default; } #if DEBUG for (int i = SetStartIndex; i < set.Length - 1; i += 2) { Debug.Assert(set[i] < set[i + 1]); } #endif if (IsNegated(set)) { // We're negated: if the upper bound of the range is ASCII, that means everything // above it is actually included, meaning all non-ASCII are in the class. // Similarly if the lower bound is non-ASCII, that means in a negated world // everything ASCII is included. return new CharClassAnalysisResults { AllNonAsciiContained = set[set.Length - 1] < 128, AllAsciiContained = set[SetStartIndex] >= 128, ContainsNoAscii = false, ContainsOnlyAscii = false }; } // If the upper bound is ASCII, that means everything included in the class is ASCII. // Similarly if the lower bound is non-ASCII, that means no ASCII is in the class. return new CharClassAnalysisResults { AllNonAsciiContained = false, AllAsciiContained = false, ContainsOnlyAscii = set[set.Length - 1] <= 128, ContainsNoAscii = set[SetStartIndex] >= 128, }; } internal static bool IsSubtraction(string charClass) => charClass.Length > SetStartIndex + charClass[CategoryLengthIndex] + charClass[SetLengthIndex]; internal static bool IsNegated(string set) => set[FlagsIndex] == 1; internal static bool IsNegated(string set, int setOffset) => set[FlagsIndex + setOffset] == 1; public static bool IsECMAWordChar(char ch) => // According to ECMA-262, \s, \S, ., ^, and $ use Unicode-based interpretations of // whitespace and newline, while \d, \D\, \w, \W, \b, and \B use ASCII-only // interpretations of digit, word character, and word boundary. In other words, // no special treatment of Unicode ZERO WIDTH NON-JOINER (ZWNJ U+200C) and // ZERO WIDTH JOINER (ZWJ U+200D) is required for ECMA word boundaries. ((((uint)ch - 'A') & ~0x20) < 26) || // ASCII letter (((uint)ch - '0') < 10) || // digit ch == '_' || // underscore ch == '\u0130'; // latin capital letter I with dot above /// <summary>16 bytes, representing the chars 0 through 127, with a 1 for a bit where that char is a word char.</summary> private static ReadOnlySpan<byte> WordCharAsciiLookup => new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07 }; /// <summary>Determines whether a character is considered a word character for the purposes of testing the \w set.</summary> public static bool IsWordChar(char ch) { // This is the same as IsBoundaryWordChar, except that IsBoundaryWordChar also // returns true for \u200c and \u200d. // Fast lookup in our lookup table for ASCII characters. This is purely an optimization, and has the // behavior as if we fell through to the switch below (which was actually used to produce the lookup table). ReadOnlySpan<byte> asciiLookup = WordCharAsciiLookup; int chDiv8 = ch >> 3; if ((uint)chDiv8 < (uint)asciiLookup.Length) { return (asciiLookup[chDiv8] & (1 << (ch & 0x7))) != 0; } // For non-ASCII, fall back to checking the Unicode category. switch (CharUnicodeInfo.GetUnicodeCategory(ch)) { case UnicodeCategory.UppercaseLetter: case UnicodeCategory.LowercaseLetter: case UnicodeCategory.TitlecaseLetter: case UnicodeCategory.ModifierLetter: case UnicodeCategory.OtherLetter: case UnicodeCategory.NonSpacingMark: case UnicodeCategory.DecimalDigitNumber: case UnicodeCategory.ConnectorPunctuation: return true; default: return false; } } /// <summary>Determines whether a character is considered a word character for the purposes of testing a word character boundary.</summary> public static bool IsBoundaryWordChar(char ch) { // According to UTS#18 Unicode Regular Expressions (http://www.unicode.org/reports/tr18/) // RL 1.4 Simple Word Boundaries The class of <word_character> includes all Alphabetic // values from the Unicode character database, from UnicodeData.txt [UData], plus the U+200C // ZERO WIDTH NON-JOINER and U+200D ZERO WIDTH JOINER. // Fast lookup in our lookup table for ASCII characters. This is purely an optimization, and has the // behavior as if we fell through to the switch below (which was actually used to produce the lookup table). ReadOnlySpan<byte> asciiLookup = WordCharAsciiLookup; int chDiv8 = ch >> 3; if ((uint)chDiv8 < (uint)asciiLookup.Length) { return (asciiLookup[chDiv8] & (1 << (ch & 0x7))) != 0; } // For non-ASCII, fall back to checking the Unicode category. switch (CharUnicodeInfo.GetUnicodeCategory(ch)) { case UnicodeCategory.UppercaseLetter: case UnicodeCategory.LowercaseLetter: case UnicodeCategory.TitlecaseLetter: case UnicodeCategory.ModifierLetter: case UnicodeCategory.OtherLetter: case UnicodeCategory.NonSpacingMark: case UnicodeCategory.DecimalDigitNumber: case UnicodeCategory.ConnectorPunctuation: return true; default: const char ZeroWidthNonJoiner = '\u200C', ZeroWidthJoiner = '\u200D'; return ch == ZeroWidthJoiner | ch == ZeroWidthNonJoiner; } } /// <summary>Determines whether the 'a' and 'b' values differ by only a single bit, setting that bit in 'mask'.</summary> /// <remarks>This isn't specific to RegexCharClass; it's just a convenient place to host it.</remarks> public static bool DifferByOneBit(char a, char b, out int mask) { mask = a ^ b; return mask != 0 && (mask & (mask - 1)) == 0; } /// <summary>Determines a character's membership in a character class (via the string representation of the class).</summary> /// <param name="ch">The character.</param> /// <param name="set">The string representation of the character class.</param> /// <param name="asciiLazyCache">A lazily-populated cache for ASCII results stored in a 256-bit array.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool CharInClass(char ch, string set, ref uint[]? asciiLazyCache) { // The uint[] contains 8 ints, or 256 bits. These are laid out as pairs, where the first bit in the pair // says whether the second bit in the pair has already been computed. Once a value is computed, it's never // changed, so since Int32s are written/read atomically, we can trust the value bit if we see that the known bit // has been set. If the known bit hasn't been set, then we proceed to look it up, and then swap in the result. const int CacheArrayLength = 8; Debug.Assert(asciiLazyCache is null || asciiLazyCache.Length == CacheArrayLength, "set lookup should be able to store two bits for each of the first 128 characters"); // If the value is ASCII and already has an answer for this value, use it. if (asciiLazyCache is uint[] cache) { int index = ch >> 4; if ((uint)index < (uint)cache.Length) { Debug.Assert(ch < 128); uint current = cache[index]; uint bit = 1u << ((ch & 0xF) << 1); if ((current & bit) != 0) { return (current & (bit << 1)) != 0; } } } // For ASCII, lazily initialize. For non-ASCII, just compute the value. return ch < 128 ? InitializeValue(ch, set, ref asciiLazyCache) : CharInClassRecursive(ch, set, 0); static bool InitializeValue(char ch, string set, ref uint[]? asciiLazyCache) { // (After warm-up, we should find ourselves rarely getting here.) Debug.Assert(ch < 128); // Compute the result and determine which bits to write back to the array and "or" the bits back in a thread-safe manner. bool isInClass = CharInClass(ch, set); uint bitsToSet = 1u << ((ch & 0xF) << 1); if (isInClass) { bitsToSet |= bitsToSet << 1; } uint[]? cache = asciiLazyCache ?? Interlocked.CompareExchange(ref asciiLazyCache, new uint[CacheArrayLength], null) ?? asciiLazyCache; #if REGEXGENERATOR InterlockedExtensions.Or(ref cache[ch >> 4], bitsToSet); #else Interlocked.Or(ref cache[ch >> 4], bitsToSet); #endif // Return the computed value. return isInClass; } } /// <summary> /// Determines a character's membership in a character class (via the string representation of the class). /// </summary> public static bool CharInClass(char ch, string set) => CharInClassRecursive(ch, set, 0); private static bool CharInClassRecursive(char ch, string set, int start) { int setLength = set[start + SetLengthIndex]; int categoryLength = set[start + CategoryLengthIndex]; int endPosition = start + SetStartIndex + setLength + categoryLength; bool inClass = CharInClassInternal(ch, set, start, setLength, categoryLength); // Note that we apply the negation *before* performing the subtraction. This is because // the negation only applies to the first char class, not the entire subtraction. if (IsNegated(set, start)) { inClass = !inClass; } // Subtract if necessary if (inClass && set.Length > endPosition) { inClass = !CharInClassRecursive(ch, set, endPosition); } return inClass; } /// <summary> /// Determines a character's membership in a character class (via the /// string representation of the class). /// </summary> private static bool CharInClassInternal(char ch, string set, int start, int setLength, int categoryLength) { int min = start + SetStartIndex; int max = min + setLength; while (min != max) { int mid = (min + max) >> 1; if (ch < set[mid]) { max = mid; } else { min = mid + 1; } } // The starting position of the set within the character class determines // whether what an odd or even ending position means. If the start is odd, // an *even* ending position means the character was in the set. With recursive // subtractions in the mix, the starting position = start+SetStartIndex. Since we know that // SetStartIndex is odd, we can simplify it out of the equation. But if it changes we need to // reverse this check. Debug.Assert((SetStartIndex & 0x1) == 1, "If SetStartIndex is not odd, the calculation below this will be reversed"); if ((min & 0x1) == (start & 0x1)) { return true; } if (categoryLength == 0) { return false; } return CharInCategory(ch, set, start, setLength, categoryLength); } private static bool CharInCategory(char ch, string set, int start, int setLength, int categoryLength) { UnicodeCategory chcategory = char.GetUnicodeCategory(ch); int i = start + SetStartIndex + setLength; int end = i + categoryLength; while (i < end) { int curcat = (short)set[i]; if (curcat == 0) { // zero is our marker for a group of categories - treated as a unit if (CharInCategoryGroup(chcategory, set, ref i)) { return true; } } else if (curcat > 0) { // greater than zero is a positive case if (curcat == SpaceConst) { if (char.IsWhiteSpace(ch)) { return true; } } else if (chcategory == (UnicodeCategory)(curcat - 1)) { return true; } } else { // less than zero is a negative case if (curcat == NotSpaceConst) { if (!char.IsWhiteSpace(ch)) { return true; } } else if (chcategory != (UnicodeCategory)(-1 - curcat)) { return true; } } i++; } return false; } /// <summary> /// This is used for categories which are composed of other categories - L, N, Z, W... /// These groups need special treatment when they are negated /// </summary> private static bool CharInCategoryGroup(UnicodeCategory chcategory, string category, ref int i) { int pos = i + 1; int curcat = (short)category[pos]; bool result; if (curcat > 0) { // positive case - the character must be in ANY of the categories in the group result = false; for (; curcat != 0; curcat = (short)category[pos]) { pos++; if (!result && chcategory == (UnicodeCategory)(curcat - 1)) { result = true; } } } else { // negative case - the character must be in NONE of the categories in the group result = true; for (; curcat != 0; curcat = (short)category[pos]) { pos++; if (result && chcategory == (UnicodeCategory)(-1 - curcat)) { result = false; } } } i = pos; return result; } public static RegexCharClass Parse(string charClass) => ParseRecursive(charClass, 0); private static RegexCharClass ParseRecursive(string charClass, int start) { int setLength = charClass[start + SetLengthIndex]; int categoryLength = charClass[start + CategoryLengthIndex]; int endPosition = start + SetStartIndex + setLength + categoryLength; int i = start + SetStartIndex; int end = i + setLength; List<(char First, char Last)>? ranges = ComputeRanges(charClass.AsSpan(start)); RegexCharClass? sub = null; if (charClass.Length > endPosition) { sub = ParseRecursive(charClass, endPosition); } StringBuilder? categoriesBuilder = null; if (categoryLength > 0) { categoriesBuilder = new StringBuilder().Append(charClass.AsSpan(end, categoryLength)); } return new RegexCharClass(IsNegated(charClass, start), ranges, categoriesBuilder, sub); } /// <summary>Computes a list of all of the character ranges in the set string.</summary> public static List<(char First, char Last)>? ComputeRanges(ReadOnlySpan<char> set) { int setLength = set[SetLengthIndex]; int i = SetStartIndex; int end = i + setLength; List<(char First, char Last)>? ranges = null; if (setLength > 0) { ranges = new List<(char First, char Last)>(setLength); while (i < end) { char first = set[i]; i++; char last = i < end ? (char)(set[i] - 1) : LastChar; i++; ranges.Add((first, last)); } } return ranges; } #region Perf workaround until https://github.com/dotnet/runtime/issues/61048 and https://github.com/dotnet/runtime/issues/59492 are addressed // TODO: https://github.com/dotnet/runtime/issues/61048 // The below functionality needs to be removed/replaced/generalized. The goal is to avoid relying on // ToLower and culture-based operation at match time, and instead be able to compute at construction // time case folding equivalence classes that let us determine up-front the set of characters considered // valid for a match. For now, we do this just for ASCII, and for anything else fall back to the // pre-existing mechanism whereby a culture is used at construction time to ToLower and then one is // used at match time to ToLower. We also skip 'i' and 'I', as the casing of those varies across culture // whereas every other ASCII value's casing is stable across culture. We could hardcode the values for // when an invariant vs tr/az culture vs any other culture is used, and we likely will, but for now doing // so would be a breaking change, as in doing so we'd be relying only on the culture present at the time // of construction rather than the one at the time of match. That will be resolved with // https://github.com/dotnet/runtime/issues/59492. /// <summary>Creates a set string for a single character, optionally factoring in case-insensitivity.</summary> /// <param name="c">The character for which to create the set.</param> /// <param name="caseInsensitive">null if case-sensitive; non-null if case-insensitive, in which case it's the culture to use.</param> /// <param name="resultIsCaseInsensitive">false if the caller should strip out RegexOptions.IgnoreCase because it's now fully represented by the set; otherwise, true.</param> /// <returns>The create set string.</returns> public static string OneToStringClass(char c, CultureInfo? caseInsensitive, out bool resultIsCaseInsensitive) { var vsb = new ValueStringBuilder(stackalloc char[4]); if (caseInsensitive is null) { resultIsCaseInsensitive = false; vsb.Append(c); } else if (c < 128 && (c | 0x20) != 'i') { resultIsCaseInsensitive = false; switch (c) { // These are the same in all cultures. As with the rest of this support, we can generalize this // once we fix the aforementioned casing issues, e.g. by lazily populating an interning cache // rather than hardcoding the strings for these values, once almost all values will be the same // regardless of culture. case 'A': case 'a': return "\0\x0004\0ABab"; case 'B': case 'b': return "\0\x0004\0BCbc"; case 'C': case 'c': return "\0\x0004\0CDcd"; case 'D': case 'd': return "\0\x0004\0DEde"; case 'E': case 'e': return "\0\x0004\0EFef"; case 'F': case 'f': return "\0\x0004\0FGfg"; case 'G': case 'g': return "\0\x0004\0GHgh"; case 'H': case 'h': return "\0\x0004\0HIhi"; // allow 'i' to fall through case 'J': case 'j': return "\0\x0004\0JKjk"; case 'K': case 'k': return "\0\x0006\0KLkl\u212A\u212B"; case 'L': case 'l': return "\0\x0004\0LMlm"; case 'M': case 'm': return "\0\x0004\0MNmn"; case 'N': case 'n': return "\0\x0004\0NOno"; case 'O': case 'o': return "\0\x0004\0OPop"; case 'P': case 'p': return "\0\x0004\0PQpq"; case 'Q': case 'q': return "\0\x0004\0QRqr"; case 'R': case 'r': return "\0\x0004\0RSrs"; case 'S': case 's': return "\0\x0004\0STst"; case 'T': case 't': return "\0\x0004\0TUtu"; case 'U': case 'u': return "\0\x0004\0UVuv"; case 'V': case 'v': return "\0\x0004\0VWvw"; case 'W': case 'w': return "\0\x0004\0WXwx"; case 'X': case 'x': return "\0\x0004\0XYxy"; case 'Y': case 'y': return "\0\x0004\0YZyz"; case 'Z': case 'z': return "\0\x0004\0Z[z{"; // All the ASCII !ParticipatesInCaseConversion case '\u0000': return "\0\u0002\0\u0000\u0001"; case '\u0001': return "\0\u0002\0\u0001\u0002"; case '\u0002': return "\0\u0002\0\u0002\u0003"; case '\u0003': return "\0\u0002\0\u0003\u0004"; case '\u0004': return "\0\u0002\0\u0004\u0005"; case '\u0005': return "\0\u0002\0\u0005\u0006"; case '\u0006': return "\0\u0002\0\u0006\u0007"; case '\u0007': return "\0\u0002\0\u0007\u0008"; case '\u0008': return "\0\u0002\0\u0008\u0009"; case '\u0009': return "\0\u0002\0\u0009\u000A"; case '\u000A': return "\0\u0002\0\u000A\u000B"; case '\u000B': return "\0\u0002\0\u000B\u000C"; case '\u000C': return "\0\u0002\0\u000C\u000D"; case '\u000D': return "\0\u0002\0\u000D\u000E"; case '\u000E': return "\0\u0002\0\u000E\u000F"; case '\u000F': return "\0\u0002\0\u000F\u0010"; case '\u0010': return "\0\u0002\0\u0010\u0011"; case '\u0011': return "\0\u0002\0\u0011\u0012"; case '\u0012': return "\0\u0002\0\u0012\u0013"; case '\u0013': return "\0\u0002\0\u0013\u0014"; case '\u0014': return "\0\u0002\0\u0014\u0015"; case '\u0015': return "\0\u0002\0\u0015\u0016"; case '\u0016': return "\0\u0002\0\u0016\u0017"; case '\u0017': return "\0\u0002\0\u0017\u0018"; case '\u0018': return "\0\u0002\0\u0018\u0019"; case '\u0019': return "\0\u0002\0\u0019\u001A"; case '\u001A': return "\0\u0002\0\u001A\u001B"; case '\u001B': return "\0\u0002\0\u001B\u001C"; case '\u001C': return "\0\u0002\0\u001C\u001D"; case '\u001D': return "\0\u0002\0\u001D\u001E"; case '\u001E': return "\0\u0002\0\u001E\u001F"; case '\u001F': return "\0\u0002\0\u001F\u0020"; case '\u0020': return "\0\u0002\0\u0020\u0021"; case '\u0021': return "\0\u0002\0\u0021\u0022"; case '\u0022': return "\0\u0002\0\u0022\u0023"; case '\u0023': return "\0\u0002\0\u0023\u0024"; case '\u0025': return "\0\u0002\0\u0025\u0026"; case '\u0026': return "\0\u0002\0\u0026\u0027"; case '\u0027': return "\0\u0002\0\u0027\u0028"; case '\u0028': return "\0\u0002\0\u0028\u0029"; case '\u0029': return "\0\u0002\0\u0029\u002A"; case '\u002A': return "\0\u0002\0\u002A\u002B"; case '\u002C': return "\0\u0002\0\u002C\u002D"; case '\u002D': return "\0\u0002\0\u002D\u002E"; case '\u002E': return "\0\u0002\0\u002E\u002F"; case '\u002F': return "\0\u0002\0\u002F\u0030"; case '\u0030': return "\0\u0002\0\u0030\u0031"; case '\u0031': return "\0\u0002\0\u0031\u0032"; case '\u0032': return "\0\u0002\0\u0032\u0033"; case '\u0033': return "\0\u0002\0\u0033\u0034"; case '\u0034': return "\0\u0002\0\u0034\u0035"; case '\u0035': return "\0\u0002\0\u0035\u0036"; case '\u0036': return "\0\u0002\0\u0036\u0037"; case '\u0037': return "\0\u0002\0\u0037\u0038"; case '\u0038': return "\0\u0002\0\u0038\u0039"; case '\u0039': return "\0\u0002\0\u0039\u003A"; case '\u003A': return "\0\u0002\0\u003A\u003B"; case '\u003B': return "\0\u0002\0\u003B\u003C"; case '\u003F': return "\0\u0002\0\u003F\u0040"; case '\u0040': return "\0\u0002\0\u0040\u0041"; case '\u005B': return "\0\u0002\0\u005B\u005C"; case '\u005C': return "\0\u0002\0\u005C\u005D"; case '\u005D': return "\0\u0002\0\u005D\u005E"; case '\u005F': return "\0\u0002\0\u005F\u0060"; case '\u007B': return "\0\u0002\0\u007B\u007C"; case '\u007D': return "\0\u0002\0\u007D\u007E"; case '\u007F': return "\0\u0002\0\u007F\u0080"; } AddAsciiCharIgnoreCaseEquivalence(c, ref vsb, caseInsensitive); } else if (!ParticipatesInCaseConversion(c)) { resultIsCaseInsensitive = false; vsb.Append(c); } else { resultIsCaseInsensitive = true; vsb.Append(char.ToLower(c, caseInsensitive)); } string result = CharsToStringClass(vsb.AsSpan()); vsb.Dispose(); return result; } private static unsafe string CharsToStringClass(ReadOnlySpan<char> chars) { #if DEBUG // Make sure they're all sorted with no duplicates for (int index = 0; index < chars.Length - 1; index++) { Debug.Assert(chars[index] < chars[index + 1]); } #endif // If there aren't any chars, just return an empty class. if (chars.Length == 0) { return EmptyClass; } // Count how many characters there actually are. All but the very last possible // char value will have two characters, one for the inclusive beginning of range // and one for the exclusive end of range. int count = chars.Length * 2; if (chars[chars.Length - 1] == LastChar) { count--; } // Get the pointer/length of the span to be able to pass it into string.Create. fixed (char* charsPtr = chars) { #if REGEXGENERATOR return StringExtensions.Create( #else return string.Create( #endif SetStartIndex + count, ((IntPtr)charsPtr, chars.Length), static (span, state) => { // Reconstruct the span now that we're inside of the lambda. ReadOnlySpan<char> chars = new ReadOnlySpan<char>((char*)state.Item1, state.Length); // Fill in the set string span[FlagsIndex] = (char)0; span[CategoryLengthIndex] = (char)0; span[SetLengthIndex] = (char)(span.Length - SetStartIndex); int i = SetStartIndex; foreach (char c in chars) { span[i++] = c; if (c != LastChar) { span[i++] = (char)(c + 1); } } Debug.Assert(i == span.Length); }); } } /// <summary>Tries to create from a RegexOptions.IgnoreCase set string a new set string that can be used without RegexOptions.IgnoreCase.</summary> /// <param name="set">The original set string from a RegexOptions.IgnoreCase node.</param> /// <param name="culture">The culture in use.</param> /// <returns>A new set string if one could be created.</returns> public static string? MakeCaseSensitiveIfPossible(string set, CultureInfo culture) { if (IsNegated(set)) { return null; } // We'll eventually need a more robust way to do this for any set. For now, we iterate through each character // in the set, and to avoid spending lots of time doing so, we limit the number of characters. This approach also // limits the structure of the sets allowed, e.g. they can't be negated, can't use subtraction, etc. Span<char> setChars = stackalloc char[64]; // arbitary limit chosen to include common groupings like all ASCII letters and digits // Try to get the set's characters. int setCharsCount = GetSetChars(set, setChars); if (setCharsCount == 0) { return null; } // Enumerate all the characters and add all characters that form their case folding equivalence class. var rcc = new RegexCharClass(); var vsb = new ValueStringBuilder(stackalloc char[4]); foreach (char c in setChars.Slice(0, setCharsCount)) { if (c >= 128 || c == 'i' || c == 'I') { return null; } vsb.Length = 0; AddAsciiCharIgnoreCaseEquivalence(c, ref vsb, culture); foreach (char v in vsb.AsSpan()) { rcc.AddChar(v); } } // Return the constructed class. return rcc.ToStringClass(); } private static void AddAsciiCharIgnoreCaseEquivalence(char c, ref ValueStringBuilder vsb, CultureInfo culture) { Debug.Assert(c < 128, $"Expected ASCII, got {(int)c}"); Debug.Assert(c != 'i' && c != 'I', "'i' currently doesn't work correctly in all cultures"); char upper = char.ToUpper(c, culture); char lower = char.ToLower(c, culture); if (upper < lower) { vsb.Append(upper); } vsb.Append(lower); if (upper > lower) { vsb.Append(upper); } if (c == 'k' || c == 'K') { vsb.Append((char)0x212A); // kelvin sign } } #endregion /// <summary> /// Constructs the string representation of the class. /// </summary> public string ToStringClass(RegexOptions options = RegexOptions.None) { bool isNonBacktracking = (options & RegexOptions.NonBacktracking) != 0; var vsb = new ValueStringBuilder(stackalloc char[256]); ToStringClass(isNonBacktracking, ref vsb); return vsb.ToString(); } private void ToStringClass(bool isNonBacktracking, ref ValueStringBuilder vsb) { Canonicalize(isNonBacktracking); int initialLength = vsb.Length; int categoriesLength = _categories?.Length ?? 0; Span<char> headerSpan = vsb.AppendSpan(SetStartIndex); headerSpan[FlagsIndex] = (char)(_negate ? 1 : 0); headerSpan[SetLengthIndex] = '\0'; // (will be replaced once we know how long a range we've added) headerSpan[CategoryLengthIndex] = (char)categoriesLength; // Append ranges List<(char First, char Last)>? rangelist = _rangelist; if (rangelist != null) { for (int i = 0; i < rangelist.Count; i++) { (char First, char Last) currentRange = rangelist[i]; vsb.Append(currentRange.First); if (currentRange.Last != LastChar) { vsb.Append((char)(currentRange.Last + 1)); } } } // Update the range length. The ValueStringBuilder may have already had some // contents (if this is a subtactor), so we need to offset by the initial length. vsb[initialLength + SetLengthIndex] = (char)(vsb.Length - initialLength - SetStartIndex); // Append categories if (categoriesLength != 0) { foreach (ReadOnlyMemory<char> chunk in _categories!.GetChunks()) { vsb.Append(chunk.Span); } } // Append a subtractor if there is one. _subtractor?.ToStringClass(isNonBacktracking, ref vsb); } /// <summary> /// Logic to reduce a character class to a unique, sorted form. /// </summary> private void Canonicalize(bool isNonBacktracking) { List<(char First, char Last)>? rangelist = _rangelist; if (rangelist != null) { // Find and eliminate overlapping or abutting ranges. if (rangelist.Count > 1) { rangelist.Sort((x, y) => x.First.CompareTo(y.First)); bool done = false; int j = 0; for (int i = 1; ; i++) { char last; for (last = rangelist[j].Last; ; i++) { if (i == rangelist.Count || last == LastChar) { done = true; break; } (char First, char Last) currentRange; if ((currentRange = rangelist[i]).First > last + 1) { break; } if (last < currentRange.Last) { last = currentRange.Last; } } rangelist[j] = (rangelist[j].First, last); j++; if (done) { break; } if (j < i) { rangelist[j] = rangelist[i]; } } rangelist.RemoveRange(j, rangelist.Count - j); } // If the class now represents a single negated range, but does so by including every // other character, invert it to produce a normalized form with a single range. This // is valuable for subsequent optimizations in most of the engines. // TODO: https://github.com/dotnet/runtime/issues/61048. The special-casing for NonBacktracking // can be deleted once this issue is addressed. The special-casing exists because NonBacktracking // is on a different casing plan than the other engines and doesn't use ToLower on each input // character at match time; this in turn can highlight differences between sets and their inverted // versions of themselves, e.g. a difference between [0-AC-\uFFFF] and [^B]. if (!isNonBacktracking && !_negate && _subtractor is null && (_categories is null || _categories.Length == 0)) { if (rangelist.Count == 2) { // There are two ranges in the list. See if there's one missing range between them. // Such a range might be as small as a single character. if (rangelist[0].First == 0 && rangelist[1].Last == LastChar && rangelist[0].Last < rangelist[1].First - 1) { rangelist[0] = ((char)(rangelist[0].Last + 1), (char)(rangelist[1].First - 1)); rangelist.RemoveAt(1); _negate = true; } } else if (rangelist.Count == 1) { if (rangelist[0].First == 0) { // There's only one range in the list. Does it include everything but the last char? if (rangelist[0].Last == LastChar - 1) { rangelist[0] = (LastChar, LastChar); _negate = true; } } else if (rangelist[0].First == 1) { // Or everything but the first char? if (rangelist[0].Last == LastChar) { rangelist[0] = ('\0', '\0'); _negate = true; } } } } } } private static ReadOnlySpan<char> SetFromProperty(string capname, bool invert, string pattern, int currentPos) { int min = 0; int max = s_propTable.Length; while (min != max) { int mid = (min + max) / 2; int res = string.Compare(capname, s_propTable[mid][0], StringComparison.Ordinal); if (res < 0) { max = mid; } else if (res > 0) { min = mid + 1; } else { string set = s_propTable[mid][1]; Debug.Assert(!string.IsNullOrEmpty(set), "Found a null/empty element in RegexCharClass prop table"); return !invert ? set.AsSpan() : set[0] == NullChar ? set.AsSpan(1) : (NullCharString + set).AsSpan(); } } throw new RegexParseException(RegexParseError.UnrecognizedUnicodeProperty, currentPos, SR.Format(SR.MakeException, pattern, currentPos, SR.Format(SR.UnrecognizedUnicodeProperty, capname))); } public static readonly string[] CategoryIdToName = PopulateCategoryIdToName(); private static string[] PopulateCategoryIdToName() { // Populate category reverse lookup used for diagnostic output var temp = new List<KeyValuePair<string, string>>(s_definedCategories); temp.RemoveAll(kvp => kvp.Value.Length != 1); temp.Sort((kvp1, kvp2) => ((short)kvp1.Value[0]).CompareTo((short)kvp2.Value[0])); return temp.ConvertAll(kvp => kvp.Key).ToArray(); } /// <summary> /// Produces a human-readable description for a set string. /// </summary> [ExcludeFromCodeCoverage] public static string DescribeSet(string set) { int setLength = set[SetLengthIndex]; int categoryLength = set[CategoryLengthIndex]; int endPosition = SetStartIndex + setLength + categoryLength; var desc = new StringBuilder(); desc.Append('['); int index = SetStartIndex; char ch1; char ch2; if (IsNegated(set)) { desc.Append('^'); } while (index < SetStartIndex + set[SetLengthIndex]) { ch1 = set[index]; ch2 = index + 1 < set.Length ? (char)(set[index + 1] - 1) : LastChar; desc.Append(DescribeChar(ch1)); if (ch2 != ch1) { if (ch1 + 1 != ch2) { desc.Append('-'); } desc.Append(DescribeChar(ch2)); } index += 2; } while (index < SetStartIndex + set[SetLengthIndex] + set[CategoryLengthIndex]) { ch1 = set[index]; if (ch1 == 0) { bool found = false; const char GroupChar = (char)0; int lastindex = set.IndexOf(GroupChar, index + 1); if (lastindex != -1) { string group = set.Substring(index, lastindex - index + 1); foreach (KeyValuePair<string, string> kvp in s_definedCategories) { if (group.Equals(kvp.Value)) { desc.Append((short)set[index + 1] > 0 ? "\\p{" : "\\P{").Append(kvp.Key).Append('}'); found = true; break; } } if (!found) { if (group.Equals(Word)) { desc.Append("\\w"); } else if (group.Equals(NotWord)) { desc.Append("\\W"); } else { // TODO: The code is incorrectly handling pretty-printing groups like \P{P}. } } index = lastindex; } } else { desc.Append(DescribeCategory(ch1)); } index++; } if (set.Length > endPosition) { desc.Append('-').Append(DescribeSet(set.Substring(endPosition))); } return desc.Append(']').ToString(); } /// <summary>Produces a human-readable description for a single character.</summary> [ExcludeFromCodeCoverage] public static string DescribeChar(char ch) => ch switch { '\a' => "\\a", '\b' => "\\b", '\t' => "\\t", '\r' => "\\r", '\v' => "\\v", '\f' => "\\f", '\n' => "\\n", '\\' => "\\\\", >= ' ' and <= '~' => ch.ToString(), _ => $"\\u{(uint)ch:X4}" }; [ExcludeFromCodeCoverage] private static string DescribeCategory(char ch) => (short)ch switch { SpaceConst => @"\s", NotSpaceConst => @"\S", (short)(UnicodeCategory.DecimalDigitNumber + 1) => @"\d", -(short)(UnicodeCategory.DecimalDigitNumber + 1) => @"\D", < 0 => $"\\P{{{CategoryIdToName[-(short)ch - 1]}}}", _ => $"\\p{{{CategoryIdToName[ch - 1]}}}", }; } }
1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices; using System.Threading; namespace System.Text.RegularExpressions { /// <summary> /// RegexCompiler translates a block of RegexCode to MSIL, and creates a subclass of the RegexRunner type. /// </summary> internal abstract class RegexCompiler { private static readonly FieldInfo s_runtextstartField = RegexRunnerField("runtextstart"); private static readonly FieldInfo s_runtextposField = RegexRunnerField("runtextpos"); private static readonly FieldInfo s_runstackField = RegexRunnerField("runstack"); private static readonly MethodInfo s_captureMethod = RegexRunnerMethod("Capture"); private static readonly MethodInfo s_transferCaptureMethod = RegexRunnerMethod("TransferCapture"); private static readonly MethodInfo s_uncaptureMethod = RegexRunnerMethod("Uncapture"); private static readonly MethodInfo s_isMatchedMethod = RegexRunnerMethod("IsMatched"); private static readonly MethodInfo s_matchLengthMethod = RegexRunnerMethod("MatchLength"); private static readonly MethodInfo s_matchIndexMethod = RegexRunnerMethod("MatchIndex"); private static readonly MethodInfo s_isBoundaryMethod = typeof(RegexRunner).GetMethod("IsBoundary", BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(ReadOnlySpan<char>), typeof(int) })!; private static readonly MethodInfo s_isWordCharMethod = RegexRunnerMethod("IsWordChar"); private static readonly MethodInfo s_isECMABoundaryMethod = typeof(RegexRunner).GetMethod("IsECMABoundary", BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(ReadOnlySpan<char>), typeof(int) })!; private static readonly MethodInfo s_crawlposMethod = RegexRunnerMethod("Crawlpos"); private static readonly MethodInfo s_charInClassMethod = RegexRunnerMethod("CharInClass"); private static readonly MethodInfo s_checkTimeoutMethod = RegexRunnerMethod("CheckTimeout"); private static readonly MethodInfo s_charIsDigitMethod = typeof(char).GetMethod("IsDigit", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charIsWhiteSpaceMethod = typeof(char).GetMethod("IsWhiteSpace", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charGetUnicodeInfo = typeof(char).GetMethod("GetUnicodeCategory", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charToLowerInvariantMethod = typeof(char).GetMethod("ToLowerInvariant", new Type[] { typeof(char) })!; private static readonly MethodInfo s_cultureInfoGetCurrentCultureMethod = typeof(CultureInfo).GetMethod("get_CurrentCulture")!; private static readonly MethodInfo s_cultureInfoGetTextInfoMethod = typeof(CultureInfo).GetMethod("get_TextInfo")!; private static readonly MethodInfo s_spanGetItemMethod = typeof(ReadOnlySpan<char>).GetMethod("get_Item", new Type[] { typeof(int) })!; private static readonly MethodInfo s_spanGetLengthMethod = typeof(ReadOnlySpan<char>).GetMethod("get_Length")!; private static readonly MethodInfo s_memoryMarshalGetReference = typeof(MemoryMarshal).GetMethod("GetReference", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfChar = typeof(MemoryExtensions).GetMethod("IndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfSpan = typeof(MemoryExtensions).GetMethod("IndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnyCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnyCharCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnySpan = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfChar = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnyCharChar = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnyCharCharChar = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnySpan = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfSpan = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanSliceIntMethod = typeof(ReadOnlySpan<char>).GetMethod("Slice", new Type[] { typeof(int) })!; private static readonly MethodInfo s_spanSliceIntIntMethod = typeof(ReadOnlySpan<char>).GetMethod("Slice", new Type[] { typeof(int), typeof(int) })!; private static readonly MethodInfo s_spanStartsWith = typeof(MemoryExtensions).GetMethod("StartsWith", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_stringAsSpanMethod = typeof(MemoryExtensions).GetMethod("AsSpan", new Type[] { typeof(string) })!; private static readonly MethodInfo s_stringGetCharsMethod = typeof(string).GetMethod("get_Chars", new Type[] { typeof(int) })!; private static readonly MethodInfo s_textInfoToLowerMethod = typeof(TextInfo).GetMethod("ToLower", new Type[] { typeof(char) })!; private static readonly MethodInfo s_arrayResize = typeof(Array).GetMethod("Resize")!.MakeGenericMethod(typeof(int)); private static readonly MethodInfo s_mathMinIntInt = typeof(Math).GetMethod("Min", new Type[] { typeof(int), typeof(int) })!; /// <summary>The ILGenerator currently in use.</summary> protected ILGenerator? _ilg; /// <summary>The options for the expression.</summary> protected RegexOptions _options; /// <summary>The <see cref="RegexTree"/> written for the expression.</summary> protected RegexTree? _regexTree; /// <summary>Whether this expression has a non-infinite timeout.</summary> protected bool _hasTimeout; /// <summary>Pool of Int32 LocalBuilders.</summary> private Stack<LocalBuilder>? _int32LocalsPool; /// <summary>Pool of ReadOnlySpan of char locals.</summary> private Stack<LocalBuilder>? _readOnlySpanCharLocalsPool; /// <summary>Local representing a cached TextInfo for the culture to use for all case-insensitive operations.</summary> private LocalBuilder? _textInfo; /// <summary>Local representing a timeout counter for loops (set loops and node loops).</summary> private LocalBuilder? _loopTimeoutCounter; /// <summary>A frequency with which the timeout should be validated.</summary> private const int LoopTimeoutCheckCount = 2048; private static FieldInfo RegexRunnerField(string fieldname) => typeof(RegexRunner).GetField(fieldname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)!; private static MethodInfo RegexRunnerMethod(string methname) => typeof(RegexRunner).GetMethod(methname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)!; /// <summary> /// Entry point to dynamically compile a regular expression. The expression is compiled to /// an in-memory assembly. /// </summary> internal static RegexRunnerFactory? Compile(string pattern, RegexTree regexTree, RegexOptions options, bool hasTimeout) => new RegexLWCGCompiler().FactoryInstanceFromCode(pattern, regexTree, options, hasTimeout); /// <summary>A macro for _ilg.DefineLabel</summary> private Label DefineLabel() => _ilg!.DefineLabel(); /// <summary>A macro for _ilg.MarkLabel</summary> private void MarkLabel(Label l) => _ilg!.MarkLabel(l); /// <summary>A macro for _ilg.Emit(Opcodes.Ldstr, str)</summary> protected void Ldstr(string str) => _ilg!.Emit(OpCodes.Ldstr, str); /// <summary>A macro for the various forms of Ldc.</summary> protected void Ldc(int i) => _ilg!.Emit(OpCodes.Ldc_I4, i); /// <summary>A macro for _ilg.Emit(OpCodes.Ldc_I8).</summary> protected void LdcI8(long i) => _ilg!.Emit(OpCodes.Ldc_I8, i); /// <summary>A macro for _ilg.Emit(OpCodes.Ret).</summary> protected void Ret() => _ilg!.Emit(OpCodes.Ret); /// <summary>A macro for _ilg.Emit(OpCodes.Dup).</summary> protected void Dup() => _ilg!.Emit(OpCodes.Dup); /// <summary>A macro for _ilg.Emit(OpCodes.Rem_Un).</summary> private void RemUn() => _ilg!.Emit(OpCodes.Rem_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Ceq).</summary> private void Ceq() => _ilg!.Emit(OpCodes.Ceq); /// <summary>A macro for _ilg.Emit(OpCodes.Cgt_Un).</summary> private void CgtUn() => _ilg!.Emit(OpCodes.Cgt_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Clt_Un).</summary> private void CltUn() => _ilg!.Emit(OpCodes.Clt_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Pop).</summary> private void Pop() => _ilg!.Emit(OpCodes.Pop); /// <summary>A macro for _ilg.Emit(OpCodes.Add).</summary> private void Add() => _ilg!.Emit(OpCodes.Add); /// <summary>A macro for _ilg.Emit(OpCodes.Sub).</summary> private void Sub() => _ilg!.Emit(OpCodes.Sub); /// <summary>A macro for _ilg.Emit(OpCodes.Mul).</summary> private void Mul() => _ilg!.Emit(OpCodes.Mul); /// <summary>A macro for _ilg.Emit(OpCodes.And).</summary> private void And() => _ilg!.Emit(OpCodes.And); /// <summary>A macro for _ilg.Emit(OpCodes.Or).</summary> private void Or() => _ilg!.Emit(OpCodes.Or); /// <summary>A macro for _ilg.Emit(OpCodes.Shl).</summary> private void Shl() => _ilg!.Emit(OpCodes.Shl); /// <summary>A macro for _ilg.Emit(OpCodes.Shr).</summary> private void Shr() => _ilg!.Emit(OpCodes.Shr); /// <summary>A macro for _ilg.Emit(OpCodes.Ldloc).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Ldloc(LocalBuilder lt) => _ilg!.Emit(OpCodes.Ldloc, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldloca).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Ldloca(LocalBuilder lt) => _ilg!.Emit(OpCodes.Ldloca, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_U2).</summary> private void LdindU2() => _ilg!.Emit(OpCodes.Ldind_U2); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_I4).</summary> private void LdindI4() => _ilg!.Emit(OpCodes.Ldind_I4); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_I8).</summary> private void LdindI8() => _ilg!.Emit(OpCodes.Ldind_I8); /// <summary>A macro for _ilg.Emit(OpCodes.Unaligned).</summary> private void Unaligned(byte alignment) => _ilg!.Emit(OpCodes.Unaligned, alignment); /// <summary>A macro for _ilg.Emit(OpCodes.Stloc).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Stloc(LocalBuilder lt) => _ilg!.Emit(OpCodes.Stloc, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldarg_0).</summary> protected void Ldthis() => _ilg!.Emit(OpCodes.Ldarg_0); /// <summary>A macro for _ilgEmit(OpCodes.Ldarg_1) </summary> private void Ldarg_1() => _ilg!.Emit(OpCodes.Ldarg_1); /// <summary>A macro for Ldthis(); Ldfld();</summary> protected void Ldthisfld(FieldInfo ft) { Ldthis(); _ilg!.Emit(OpCodes.Ldfld, ft); } /// <summary>Fetches the address of argument in passed in <paramref name="position"/></summary> /// <param name="position">The position of the argument which address needs to be fetched.</param> private void Ldarga_s(int position) => _ilg!.Emit(OpCodes.Ldarga_S, position); /// <summary>A macro for Ldthis(); Ldfld(); Stloc();</summary> private void Mvfldloc(FieldInfo ft, LocalBuilder lt) { Ldthisfld(ft); Stloc(lt); } /// <summary>A macro for _ilg.Emit(OpCodes.Stfld).</summary> protected void Stfld(FieldInfo ft) => _ilg!.Emit(OpCodes.Stfld, ft); /// <summary>A macro for _ilg.Emit(OpCodes.Callvirt, mt).</summary> protected void Callvirt(MethodInfo mt) => _ilg!.Emit(OpCodes.Callvirt, mt); /// <summary>A macro for _ilg.Emit(OpCodes.Call, mt).</summary> protected void Call(MethodInfo mt) => _ilg!.Emit(OpCodes.Call, mt); /// <summary>A macro for _ilg.Emit(OpCodes.Brfalse) (short jump).</summary> private void Brfalse(Label l) => _ilg!.Emit(OpCodes.Brfalse_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brfalse) (long form).</summary> private void BrfalseFar(Label l) => _ilg!.Emit(OpCodes.Brfalse, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brtrue) (long form).</summary> private void BrtrueFar(Label l) => _ilg!.Emit(OpCodes.Brtrue, l); /// <summary>A macro for _ilg.Emit(OpCodes.Br) (long form).</summary> private void BrFar(Label l) => _ilg!.Emit(OpCodes.Br, l); /// <summary>A macro for _ilg.Emit(OpCodes.Ble) (long form).</summary> private void BleFar(Label l) => _ilg!.Emit(OpCodes.Ble, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt) (long form).</summary> private void BltFar(Label l) => _ilg!.Emit(OpCodes.Blt, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt_Un) (long form).</summary> private void BltUnFar(Label l) => _ilg!.Emit(OpCodes.Blt_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge) (long form).</summary> private void BgeFar(Label l) => _ilg!.Emit(OpCodes.Bge, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_Un) (long form).</summary> private void BgeUnFar(Label l) => _ilg!.Emit(OpCodes.Bge_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bne) (long form).</summary> private void BneFar(Label l) => _ilg!.Emit(OpCodes.Bne_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Beq) (long form).</summary> private void BeqFar(Label l) => _ilg!.Emit(OpCodes.Beq, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brtrue_S) (short jump).</summary> private void Brtrue(Label l) => _ilg!.Emit(OpCodes.Brtrue_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Br_S) (short jump).</summary> private void Br(Label l) => _ilg!.Emit(OpCodes.Br_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Ble_S) (short jump).</summary> private void Ble(Label l) => _ilg!.Emit(OpCodes.Ble_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt_S) (short jump).</summary> private void Blt(Label l) => _ilg!.Emit(OpCodes.Blt_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_S) (short jump).</summary> private void Bge(Label l) => _ilg!.Emit(OpCodes.Bge_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_Un_S) (short jump).</summary> private void BgeUn(Label l) => _ilg!.Emit(OpCodes.Bge_Un_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bgt_S) (short jump).</summary> private void Bgt(Label l) => _ilg!.Emit(OpCodes.Bgt_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bne_S) (short jump).</summary> private void Bne(Label l) => _ilg!.Emit(OpCodes.Bne_Un_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Beq_S) (short jump).</summary> private void Beq(Label l) => _ilg!.Emit(OpCodes.Beq_S, l); /// <summary>A macro for the Ldlen instruction.</summary> private void Ldlen() => _ilg!.Emit(OpCodes.Ldlen); /// <summary>A macro for the Ldelem_I4 instruction.</summary> private void LdelemI4() => _ilg!.Emit(OpCodes.Ldelem_I4); /// <summary>A macro for the Stelem_I4 instruction.</summary> private void StelemI4() => _ilg!.Emit(OpCodes.Stelem_I4); private void Switch(Label[] table) => _ilg!.Emit(OpCodes.Switch, table); /// <summary>Declares a local bool.</summary> private LocalBuilder DeclareBool() => _ilg!.DeclareLocal(typeof(bool)); /// <summary>Declares a local int.</summary> private LocalBuilder DeclareInt32() => _ilg!.DeclareLocal(typeof(int)); /// <summary>Declares a local CultureInfo.</summary> private LocalBuilder? DeclareTextInfo() => _ilg!.DeclareLocal(typeof(TextInfo)); /// <summary>Declares a local string.</summary> private LocalBuilder DeclareString() => _ilg!.DeclareLocal(typeof(string)); private LocalBuilder DeclareReadOnlySpanChar() => _ilg!.DeclareLocal(typeof(ReadOnlySpan<char>)); /// <summary>Rents an Int32 local variable slot from the pool of locals.</summary> /// <remarks> /// Care must be taken to Dispose of the returned <see cref="RentedLocalBuilder"/> when it's no longer needed, /// and also not to jump into the middle of a block involving a rented local from outside of that block. /// </remarks> private RentedLocalBuilder RentInt32Local() => new RentedLocalBuilder( _int32LocalsPool ??= new Stack<LocalBuilder>(), _int32LocalsPool.TryPop(out LocalBuilder? iterationLocal) ? iterationLocal : DeclareInt32()); /// <summary>Rents a ReadOnlySpan(char) local variable slot from the pool of locals.</summary> /// <remarks> /// Care must be taken to Dispose of the returned <see cref="RentedLocalBuilder"/> when it's no longer needed, /// and also not to jump into the middle of a block involving a rented local from outside of that block. /// </remarks> private RentedLocalBuilder RentReadOnlySpanCharLocal() => new RentedLocalBuilder( _readOnlySpanCharLocalsPool ??= new Stack<LocalBuilder>(1), // capacity == 1 as we currently don't expect overlapping instances _readOnlySpanCharLocalsPool.TryPop(out LocalBuilder? iterationLocal) ? iterationLocal : DeclareReadOnlySpanChar()); /// <summary>Returned a rented local to the pool.</summary> private struct RentedLocalBuilder : IDisposable { private readonly Stack<LocalBuilder> _pool; private readonly LocalBuilder _local; internal RentedLocalBuilder(Stack<LocalBuilder> pool, LocalBuilder local) { _local = local; _pool = pool; } public static implicit operator LocalBuilder(RentedLocalBuilder local) => local._local; public void Dispose() { Debug.Assert(_pool != null); Debug.Assert(_local != null); Debug.Assert(!_pool.Contains(_local)); _pool.Push(_local); this = default; } } /// <summary>Sets the culture local to CultureInfo.CurrentCulture.</summary> private void InitLocalCultureInfo() { Debug.Assert(_textInfo != null); Call(s_cultureInfoGetCurrentCultureMethod); Callvirt(s_cultureInfoGetTextInfoMethod); Stloc(_textInfo); } /// <summary>Whether ToLower operations should be performed with the invariant culture as opposed to the one in <see cref="_textInfo"/>.</summary> private bool UseToLowerInvariant => _textInfo == null || (_options & RegexOptions.CultureInvariant) != 0; /// <summary>Invokes either char.ToLowerInvariant(c) or _textInfo.ToLower(c).</summary> private void CallToLower() { if (UseToLowerInvariant) { Call(s_charToLowerInvariantMethod); } else { using RentedLocalBuilder currentCharLocal = RentInt32Local(); Stloc(currentCharLocal); Ldloc(_textInfo!); Ldloc(currentCharLocal); Callvirt(s_textInfoToLowerMethod); } } /// <summary>Generates the implementation for TryFindNextPossibleStartingPosition.</summary> protected void EmitTryFindNextPossibleStartingPosition() { Debug.Assert(_regexTree != null); _int32LocalsPool?.Clear(); _readOnlySpanCharLocalsPool?.Clear(); LocalBuilder inputSpan = DeclareReadOnlySpanChar(); LocalBuilder pos = DeclareInt32(); bool rtl = (_options & RegexOptions.RightToLeft) != 0; _textInfo = null; if ((_options & RegexOptions.CultureInvariant) == 0) { bool needsCulture = _regexTree.FindOptimizations.FindMode switch { FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive => true, _ when _regexTree.FindOptimizations.FixedDistanceSets is List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets => sets.Exists(set => set.CaseInsensitive), _ => false, }; if (needsCulture) { _textInfo = DeclareTextInfo(); InitLocalCultureInfo(); } } // Load necessary locals // int pos = base.runtextpos; // ReadOnlySpan<char> inputSpan = dynamicMethodArg; // TODO: We can reference the arg directly rather than using another local. Mvfldloc(s_runtextposField, pos); Ldarg_1(); Stloc(inputSpan); // Generate length check. If the input isn't long enough to possibly match, fail quickly. // It's rare for min required length to be 0, so we don't bother special-casing the check, // especially since we want the "return false" code regardless. int minRequiredLength = _regexTree.FindOptimizations.MinRequiredLength; Debug.Assert(minRequiredLength >= 0); Label returnFalse = DefineLabel(); Label finishedLengthCheck = DefineLabel(); // if (pos > inputSpan.Length - minRequiredLength) // or pos < minRequiredLength for rtl // { // base.runtextpos = inputSpan.Length; // or 0 for rtl // return false; // } Ldloc(pos); if (!rtl) { Ldloca(inputSpan); Call(s_spanGetLengthMethod); if (minRequiredLength > 0) { Ldc(minRequiredLength); Sub(); } Ble(finishedLengthCheck); } else { Ldc(minRequiredLength); Bge(finishedLengthCheck); } MarkLabel(returnFalse); Ldthis(); if (!rtl) { Ldloca(inputSpan); Call(s_spanGetLengthMethod); } else { Ldc(0); } Stfld(s_runtextposField); Ldc(0); Ret(); MarkLabel(finishedLengthCheck); // Emit any anchors. if (EmitAnchors()) { return; } // Either anchors weren't specified, or they don't completely root all matches to a specific location. switch (_regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_LeftToRight(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_RightToLeft(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: Debug.Assert(_regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_LeftToRight(); break; case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive: Debug.Assert(_regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_RightToLeft(); break; case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: Debug.Assert(_regexTree.FindOptimizations.LiteralAfterLoop is not null); EmitLiteralAfterAtomicLoop(); break; default: Debug.Fail($"Unexpected mode: {_regexTree.FindOptimizations.FindMode}"); goto case FindNextStartingPositionMode.NoSearch; case FindNextStartingPositionMode.NoSearch: // return true; Ldc(1); Ret(); break; } // Emits any anchors. Returns true if the anchor roots any match to a specific location and thus no further // searching is required; otherwise, false. bool EmitAnchors() { Label label; // Anchors that fully implement TryFindNextPossibleStartingPosition, with a check that leads to immediate success or failure determination. switch (_regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: // if (pos != 0) goto returnFalse; // return true; Ldloc(pos); Ldc(0); Bne(returnFalse); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start: // if (pos != base.runtextstart) goto returnFalse; // return true; Ldloc(pos); Ldthisfld(s_runtextstartField); Bne(returnFalse); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: // if (pos < inputSpan.Length - 1) base.runtextpos = inputSpan.Length - 1; // return true; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: // if (pos < inputSpan.Length) base.runtextpos = inputSpan.Length; // return true; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning: // if (pos != 0) base.runtextpos = 0; // return true; label = DefineLabel(); Ldloc(pos); Ldc(0); Beq(label); Ldthis(); Ldc(0); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ: // if (pos < inputSpan.Length - 1 || ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\n') goto returnFalse; // return true; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Blt(returnFalse); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUn(label); Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); Bne(returnFalse); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End: // if (pos < inputSpan.Length) goto returnFalse; // return true; Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Blt(returnFalse); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: // Jump to the end, minus the min required length, which in this case is actually the fixed length. { int extraNewlineBump = _regexTree.FindOptimizations.FindMode == FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ ? 1 : 0; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(_regexTree.FindOptimizations.MinRequiredLength + extraNewlineBump); Sub(); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(_regexTree.FindOptimizations.MinRequiredLength + extraNewlineBump); Sub(); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; } } // Now handle anchors that boost the position but don't determine immediate success or failure. if (!rtl) // we haven't done the work to validate these optimizations for RightToLeft { switch (_regexTree.FindOptimizations.LeadingAnchor) { case RegexNodeKind.Bol: { // Optimize the handling of a Beginning-Of-Line (BOL) anchor. BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any prefix or char class searches. label = DefineLabel(); // if (pos > 0... Ldloc(pos!); Ldc(0); Ble(label); // ... && inputSpan[pos - 1] != '\n') { ... } Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); Beq(label); // int tmp = inputSpan.Slice(pos).IndexOf('\n'); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Ldc('\n'); Call(s_spanIndexOfChar); using (RentedLocalBuilder newlinePos = RentInt32Local()) { Stloc(newlinePos); // if (newlinePos < 0 || newlinePos + pos + 1 > inputSpan.Length) // { // base.runtextpos = inputSpan.Length; // return false; // } Ldloc(newlinePos); Ldc(0); Blt(returnFalse); Ldloc(newlinePos); Ldloc(pos); Add(); Ldc(1); Add(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Bgt(returnFalse); // pos += newlinePos + 1; Ldloc(pos); Ldloc(newlinePos); Add(); Ldc(1); Add(); Stloc(pos); // We've updated the position. Make sure there's still enough room in the input for a possible match. // if (pos > inputSpan.Length - minRequiredLength) returnFalse; Ldloca(inputSpan); Call(s_spanGetLengthMethod); if (minRequiredLength != 0) { Ldc(minRequiredLength); Sub(); } Ldloc(pos); BltFar(returnFalse); } MarkLabel(label); } break; } switch (_regexTree.FindOptimizations.TrailingAnchor) { case RegexNodeKind.End or RegexNodeKind.EndZ when _regexTree.FindOptimizations.MaxPossibleLength is int maxLength: // Jump to the end, minus the max allowed length. { int extraNewlineBump = _regexTree.FindOptimizations.FindMode == FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ ? 1 : 0; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(maxLength + extraNewlineBump); Sub(); Bge(label); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(maxLength + extraNewlineBump); Sub(); Stloc(pos); MarkLabel(label); break; } } } return false; } // Emits a case-sensitive prefix search for a string at the beginning of the pattern. void EmitIndexOf_LeftToRight(string prefix) { using RentedLocalBuilder i = RentInt32Local(); // int i = inputSpan.Slice(pos).IndexOf(prefix); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Ldstr(prefix); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); Stloc(i); // if (i < 0) goto ReturnFalse; Ldloc(i); Ldc(0); BltFar(returnFalse); // base.runtextpos = pos + i; // return true; Ldthis(); Ldloc(pos); Ldloc(i); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } // Emits a case-sensitive right-to-left prefix search for a string at the beginning of the pattern. void EmitIndexOf_RightToLeft(string prefix) { // pos = inputSpan.Slice(0, pos).LastIndexOf(prefix); Ldloca(inputSpan); Ldc(0); Ldloc(pos); Call(s_spanSliceIntIntMethod); Ldstr(prefix); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfSpan); Stloc(pos); // if (pos < 0) goto ReturnFalse; Ldloc(pos); Ldc(0); BltFar(returnFalse); // base.runtextpos = pos + prefix.Length; // return true; Ldthis(); Ldloc(pos); Ldc(prefix.Length); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } // Emits a search for a set at a fixed position from the start of the pattern, // and potentially other sets at other fixed positions in the pattern. void EmitFixedSet_LeftToRight() { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? sets = _regexTree.FindOptimizations.FixedDistanceSets; (char[]? Chars, string Set, int Distance, bool CaseInsensitive) primarySet = sets![0]; const int MaxSets = 4; int setsToUse = Math.Min(sets.Count, MaxSets); using RentedLocalBuilder iLocal = RentInt32Local(); using RentedLocalBuilder textSpanLocal = RentReadOnlySpanCharLocal(); // ReadOnlySpan<char> span = inputSpan.Slice(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(textSpanLocal); // If we can use IndexOf{Any}, try to accelerate the skip loop via vectorization to match the first prefix. // We can use it if this is a case-sensitive class with a small number of characters in the class. int setIndex = 0; bool canUseIndexOf = !primarySet.CaseInsensitive && primarySet.Chars is not null; bool needLoop = !canUseIndexOf || setsToUse > 1; Label checkSpanLengthLabel = default; Label charNotInClassLabel = default; Label loopBody = default; if (needLoop) { checkSpanLengthLabel = DefineLabel(); charNotInClassLabel = DefineLabel(); loopBody = DefineLabel(); // for (int i = 0; Ldc(0); Stloc(iLocal); BrFar(checkSpanLengthLabel); MarkLabel(loopBody); } if (canUseIndexOf) { setIndex = 1; if (needLoop) { // slice.Slice(iLocal + primarySet.Distance); Ldloca(textSpanLocal); Ldloc(iLocal); if (primarySet.Distance != 0) { Ldc(primarySet.Distance); Add(); } Call(s_spanSliceIntMethod); } else if (primarySet.Distance != 0) { // slice.Slice(primarySet.Distance) Ldloca(textSpanLocal); Ldc(primarySet.Distance); Call(s_spanSliceIntMethod); } else { // slice Ldloc(textSpanLocal); } switch (primarySet.Chars!.Length) { case 1: // tmp = ...IndexOf(setChars[0]); Ldc(primarySet.Chars[0]); Call(s_spanIndexOfChar); break; case 2: // tmp = ...IndexOfAny(setChars[0], setChars[1]); Ldc(primarySet.Chars[0]); Ldc(primarySet.Chars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: // tmp = ...IndexOfAny(setChars[0], setChars[1], setChars[2]}); Ldc(primarySet.Chars[0]); Ldc(primarySet.Chars[1]); Ldc(primarySet.Chars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(new string(primarySet.Chars)); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } if (needLoop) { // i += tmp; // if (tmp < 0) goto returnFalse; using (RentedLocalBuilder tmp = RentInt32Local()) { Stloc(tmp); Ldloc(iLocal); Ldloc(tmp); Add(); Stloc(iLocal); Ldloc(tmp); Ldc(0); BltFar(returnFalse); } } else { // i = tmp; // if (i < 0) goto returnFalse; Stloc(iLocal); Ldloc(iLocal); Ldc(0); BltFar(returnFalse); } // if (i >= slice.Length - (minRequiredLength - 1)) goto returnFalse; if (sets.Count > 1) { Debug.Assert(needLoop); Ldloca(textSpanLocal); Call(s_spanGetLengthMethod); Ldc(minRequiredLength - 1); Sub(); Ldloc(iLocal); BleFar(returnFalse); } } // if (!CharInClass(slice[i], prefix[0], "...")) continue; // if (!CharInClass(slice[i + 1], prefix[1], "...")) continue; // if (!CharInClass(slice[i + 2], prefix[2], "...")) continue; // ... Debug.Assert(setIndex is 0 or 1); for ( ; setIndex < sets.Count; setIndex++) { Debug.Assert(needLoop); Ldloca(textSpanLocal); Ldloc(iLocal); if (sets[setIndex].Distance != 0) { Ldc(sets[setIndex].Distance); Add(); } Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(sets[setIndex].Set, sets[setIndex].CaseInsensitive); BrfalseFar(charNotInClassLabel); } // base.runtextpos = pos + i; // return true; Ldthis(); Ldloc(pos); Ldloc(iLocal); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); if (needLoop) { MarkLabel(charNotInClassLabel); // for (...; ...; i++) Ldloc(iLocal); Ldc(1); Add(); Stloc(iLocal); // for (...; i < span.Length - (minRequiredLength - 1); ...); MarkLabel(checkSpanLengthLabel); Ldloc(iLocal); Ldloca(textSpanLocal); Call(s_spanGetLengthMethod); if (setsToUse > 1 || primarySet.Distance != 0) { Ldc(minRequiredLength - 1); Sub(); } BltFar(loopBody); // base.runtextpos = inputSpan.Length; // return false; BrFar(returnFalse); } } // Emits a right-to-left search for a set at a fixed position from the start of the pattern. // (Currently that position will always be a distance of 0, meaning the start of the pattern itself.) void EmitFixedSet_RightToLeft() { (char[]? Chars, string Set, int Distance, bool CaseInsensitive) set = _regexTree.FindOptimizations.FixedDistanceSets![0]; Debug.Assert(set.Distance == 0); if (set.Chars is { Length: 1 } && !set.CaseInsensitive) { // pos = inputSpan.Slice(0, pos).LastIndexOf(set.Chars[0]); Ldloca(inputSpan); Ldc(0); Ldloc(pos); Call(s_spanSliceIntIntMethod); Ldc(set.Chars[0]); Call(s_spanLastIndexOfChar); Stloc(pos); // if (pos < 0) goto returnFalse; Ldloc(pos); Ldc(0); BltFar(returnFalse); // base.runtextpos = pos + 1; // return true; Ldthis(); Ldloc(pos); Ldc(1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } else { Label condition = DefineLabel(); // while ((uint)--pos < (uint)inputSpan.Length) MarkLabel(condition); Ldloc(pos); Ldc(1); Sub(); Stloc(pos); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUnFar(returnFalse); // if (!MatchCharacterClass(inputSpan[i], set.Set, set.CaseInsensitive)) goto condition; Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(set.Set, set.CaseInsensitive); Brfalse(condition); // base.runtextpos = pos + 1; // return true; Ldthis(); Ldloc(pos); Ldc(1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } } // Emits a search for a literal following a leading atomic single-character loop. void EmitLiteralAfterAtomicLoop() { Debug.Assert(_regexTree.FindOptimizations.LiteralAfterLoop is not null); (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = _regexTree.FindOptimizations.LiteralAfterLoop.Value; Debug.Assert(target.LoopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(target.LoopNode.N == int.MaxValue); // while (true) Label loopBody = DefineLabel(); Label loopEnd = DefineLabel(); MarkLabel(loopBody); // ReadOnlySpan<char> slice = inputSpan.Slice(pos); using RentedLocalBuilder slice = RentReadOnlySpanCharLocal(); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(slice); // Find the literal. If we can't find it, we're done searching. // int i = slice.IndexOf(literal); // if (i < 0) break; using RentedLocalBuilder i = RentInt32Local(); Ldloc(slice); if (target.Literal.String is string literalString) { Ldstr(literalString); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); } else if (target.Literal.Chars is not char[] literalChars) { Ldc(target.Literal.Char); Call(s_spanIndexOfChar); } else { switch (literalChars.Length) { case 2: Ldc(literalChars[0]); Ldc(literalChars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(literalChars[0]); Ldc(literalChars[1]); Ldc(literalChars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(new string(literalChars)); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } Stloc(i); Ldloc(i); Ldc(0); BltFar(loopEnd); // We found the literal. Walk backwards from it finding as many matches as we can against the loop. // int prev = i; using RentedLocalBuilder prev = RentInt32Local(); Ldloc(i); Stloc(prev); // while ((uint)--prev < (uint)slice.Length) && MatchCharClass(slice[prev])); Label innerLoopBody = DefineLabel(); Label innerLoopEnd = DefineLabel(); MarkLabel(innerLoopBody); Ldloc(prev); Ldc(1); Sub(); Stloc(prev); Ldloc(prev); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUn(innerLoopEnd); Ldloca(slice); Ldloc(prev); Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(target.LoopNode.Str!, caseInsensitive: false); BrtrueFar(innerLoopBody); MarkLabel(innerLoopEnd); if (target.LoopNode.M > 0) { // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. // if ((i - prev - 1) < target.LoopNode.M) // { // pos += i + 1; // continue; // } Label metMinimum = DefineLabel(); Ldloc(i); Ldloc(prev); Sub(); Ldc(1); Sub(); Ldc(target.LoopNode.M); Bge(metMinimum); Ldloc(pos); Ldloc(i); Add(); Ldc(1); Add(); Stloc(pos); BrFar(loopBody); MarkLabel(metMinimum); } // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate i as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. // base.runtextpos = pos + prev + 1; // return true; Ldthis(); Ldloc(pos); Ldloc(prev); Add(); Ldc(1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); // } MarkLabel(loopEnd); // base.runtextpos = inputSpan.Length; // return false; BrFar(returnFalse); } } /// <summary>Generates the implementation for TryMatchAtCurrentPosition.</summary> protected void EmitTryMatchAtCurrentPosition() { // In .NET Framework and up through .NET Core 3.1, the code generated for RegexOptions.Compiled was effectively an unrolled // version of what RegexInterpreter would process. The RegexNode tree would be turned into a series of opcodes via // RegexWriter; the interpreter would then sit in a loop processing those opcodes, and the RegexCompiler iterated through the // opcodes generating code for each equivalent to what the interpreter would do albeit with some decisions made at compile-time // rather than at run-time. This approach, however, lead to complicated code that wasn't pay-for-play (e.g. a big backtracking // jump table that all compilations went through even if there was no backtracking), that didn't factor in the shape of the // tree (e.g. it's difficult to add optimizations based on interactions between nodes in the graph), and that didn't read well // when decompiled from IL to C# or when directly emitted as C# as part of a source generator. // // This implementation is instead based on directly walking the RegexNode tree and outputting code for each node in the graph. // A dedicated for each kind of RegexNode emits the code necessary to handle that node's processing, including recursively // calling the relevant function for any of its children nodes. Backtracking is handled not via a giant jump table, but instead // by emitting direct jumps to each backtracking construct. This is achieved by having all match failures jump to a "done" // label that can be changed by a previous emitter, e.g. before EmitLoop returns, it ensures that "doneLabel" is set to the // label that code should jump back to when backtracking. That way, a subsequent EmitXx function doesn't need to know exactly // where to jump: it simply always jumps to "doneLabel" on match failure, and "doneLabel" is always configured to point to // the right location. In an expression without backtracking, or before any backtracking constructs have been encountered, // "doneLabel" is simply the final return location from the TryMatchAtCurrentPosition method that will undo any captures and exit, signaling to // the calling scan loop that nothing was matched. Debug.Assert(_regexTree != null); _int32LocalsPool?.Clear(); _readOnlySpanCharLocalsPool?.Clear(); // Get the root Capture node of the tree. RegexNode node = _regexTree.Root; Debug.Assert(node.Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); Debug.Assert(node.ChildCount() == 1, "Capture nodes should have one child"); // Skip the Capture node. We handle the implicit root capture specially. node = node.Child(0); // In some limited cases, TryFindNextPossibleStartingPosition will only return true if it successfully matched the whole expression. // We can special case these to do essentially nothing in TryMatchAtCurrentPosition other than emit the capture. switch (node.Kind) { case RegexNodeKind.Multi or RegexNodeKind.Notone or RegexNodeKind.One or RegexNodeKind.Set when !IsCaseInsensitive(node): // This is the case for single and multiple characters, though the whole thing is only guaranteed // to have been validated in TryFindNextPossibleStartingPosition when doing case-sensitive comparison. // base.Capture(0, base.runtextpos, base.runtextpos + node.Str.Length); // base.runtextpos = base.runtextpos + node.Str.Length; // return true; int length = node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1; if ((node.Options & RegexOptions.RightToLeft) != 0) { length = -length; } Ldthis(); Dup(); Ldc(0); Ldthisfld(s_runtextposField); Dup(); Ldc(length); Add(); Call(s_captureMethod); Ldthisfld(s_runtextposField); Ldc(length); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); return; // The source generator special-cases RegexNode.Empty, for purposes of code learning rather than // performance. Since that's not applicable to RegexCompiler, that code isn't mirrored here. } AnalysisResults analysis = RegexTreeAnalyzer.Analyze(_regexTree); // Initialize the main locals used throughout the implementation. LocalBuilder inputSpan = DeclareReadOnlySpanChar(); LocalBuilder originalPos = DeclareInt32(); LocalBuilder pos = DeclareInt32(); LocalBuilder slice = DeclareReadOnlySpanChar(); Label doneLabel = DefineLabel(); Label originalDoneLabel = doneLabel; if (_hasTimeout) { _loopTimeoutCounter = DeclareInt32(); } // CultureInfo culture = CultureInfo.CurrentCulture; // only if the whole expression or any subportion is ignoring case, and we're not using invariant InitializeCultureForTryMatchAtCurrentPositionIfNecessary(analysis); // ReadOnlySpan<char> inputSpan = input; Ldarg_1(); Stloc(inputSpan); // int pos = base.runtextpos; // int originalpos = pos; Ldthisfld(s_runtextposField); Stloc(pos); Ldloc(pos); Stloc(originalPos); // int stackpos = 0; LocalBuilder stackpos = DeclareInt32(); Ldc(0); Stloc(stackpos); // The implementation tries to use const indexes into the span wherever possible, which we can do // for all fixed-length constructs. In such cases (e.g. single chars, repeaters, strings, etc.) // we know at any point in the regex exactly how far into it we are, and we can use that to index // into the span created at the beginning of the routine to begin at exactly where we're starting // in the input. When we encounter a variable-length construct, we transfer the static value to // pos, slicing the inputSpan appropriately, and then zero out the static position. int sliceStaticPos = 0; SliceInputSpan(); // Check whether there are captures anywhere in the expression. If there isn't, we can skip all // the boilerplate logic around uncapturing, as there won't be anything to uncapture. bool expressionHasCaptures = analysis.MayContainCapture(node); // Emit the code for all nodes in the tree. EmitNode(node); // pos += sliceStaticPos; // base.runtextpos = pos; // Capture(0, originalpos, pos); // return true; Ldthis(); Ldloc(pos); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Add(); Stloc(pos); Ldloc(pos); } Stfld(s_runtextposField); Ldthis(); Ldc(0); Ldloc(originalPos); Ldloc(pos); Call(s_captureMethod); Ldc(1); Ret(); // NOTE: The following is a difference from the source generator. The source generator emits: // UncaptureUntil(0); // return false; // at every location where the all-up match is known to fail. In contrast, the compiler currently // emits this uncapture/return code in one place and jumps to it upon match failure. The difference // stems primarily from the return-at-each-location pattern resulting in cleaner / easier to read // source code, which is not an issue for RegexCompiler emitting IL instead of C#. // If the graph contained captures, undo any remaining to handle failed matches. if (expressionHasCaptures) { // while (base.Crawlpos() != 0) base.Uncapture(); Label finalReturnLabel = DefineLabel(); Br(finalReturnLabel); MarkLabel(originalDoneLabel); Label condition = DefineLabel(); Label body = DefineLabel(); Br(condition); MarkLabel(body); Ldthis(); Call(s_uncaptureMethod); MarkLabel(condition); Ldthis(); Call(s_crawlposMethod); Brtrue(body); // Done: MarkLabel(finalReturnLabel); } else { // Done: MarkLabel(originalDoneLabel); } // return false; Ldc(0); Ret(); // Generated code successfully. return; static bool IsCaseInsensitive(RegexNode node) => (node.Options & RegexOptions.IgnoreCase) != 0; // Slices the inputSpan starting at pos until end and stores it into slice. void SliceInputSpan() { // slice = inputSpan.Slice(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(slice); } // Emits the sum of a constant and a value from a local. void EmitSum(int constant, LocalBuilder? local) { if (local == null) { Ldc(constant); } else if (constant == 0) { Ldloc(local); } else { Ldloc(local); Ldc(constant); Add(); } } // Emits a check that the span is large enough at the currently known static position to handle the required additional length. void EmitSpanLengthCheck(int requiredLength, LocalBuilder? dynamicRequiredLength = null) { // if ((uint)(sliceStaticPos + requiredLength + dynamicRequiredLength - 1) >= (uint)slice.Length) goto Done; Debug.Assert(requiredLength > 0); EmitSum(sliceStaticPos + requiredLength - 1, dynamicRequiredLength); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); } // Emits code to get ref slice[sliceStaticPos] void EmitTextSpanOffset() { Ldloc(slice); Call(s_memoryMarshalGetReference); if (sliceStaticPos > 0) { Ldc(sliceStaticPos * sizeof(char)); Add(); } } // Adds the value of sliceStaticPos into the pos local, zeros out sliceStaticPos, // and resets slice to be inputSpan.Slice(pos). void TransferSliceStaticPosToPos(bool forceSliceReload = false) { if (sliceStaticPos > 0) { // pos += sliceStaticPos; // sliceStaticPos = 0; Ldloc(pos); Ldc(sliceStaticPos); Add(); Stloc(pos); sliceStaticPos = 0; // slice = inputSpan.Slice(pos); SliceInputSpan(); } else if (forceSliceReload) { // slice = inputSpan.Slice(pos); SliceInputSpan(); } } // Emits the code for an alternation. void EmitAlternation(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Alternate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); int childCount = node.ChildCount(); Debug.Assert(childCount >= 2); Label originalDoneLabel = doneLabel; // Both atomic and non-atomic are supported. While a parent RegexNode.Atomic node will itself // successfully prevent backtracking into this child node, we can emit better / cheaper code // for an Alternate when it is atomic, so we still take it into account here. Debug.Assert(node.Parent is not null); bool isAtomic = analysis.IsAtomicByAncestor(node); // Label to jump to when any branch completes successfully. Label matchLabel = DefineLabel(); // Save off pos. We'll need to reset this each time a branch fails. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; // We need to be able to undo captures in two situations: // - If a branch of the alternation itself contains captures, then if that branch // fails to match, any captures from that branch until that failure point need to // be uncaptured prior to jumping to the next branch. // - If the expression after the alternation contains captures, then failures // to match in those expressions could trigger backtracking back into the // alternation, and thus we need uncapture any of them. // As such, if the alternation contains captures or if it's not atomic, we need // to grab the current crawl position so we can unwind back to it when necessary. // We can do all of the uncapturing as part of falling through to the next branch. // If we fail in a branch, then such uncapturing will unwind back to the position // at the start of the alternation. If we fail after the alternation, and the // matched branch didn't contain any backtracking, then the failure will end up // jumping to the next branch, which will unwind the captures. And if we fail after // the alternation and the matched branch did contain backtracking, that backtracking // construct is responsible for unwinding back to its starting crawl position. If // it eventually ends up failing, that failure will result in jumping to the next branch // of the alternation, which will again dutifully unwind the remaining captures until // what they were at the start of the alternation. Of course, if there are no captures // anywhere in the regex, we don't have to do any of that. LocalBuilder? startingCapturePos = null; if (expressionHasCaptures && (analysis.MayContainCapture(node) || !isAtomic)) { // startingCapturePos = base.Crawlpos(); startingCapturePos = DeclareInt32(); Ldthis(); Call(s_crawlposMethod); Stloc(startingCapturePos); } // After executing the alternation, subsequent matching may fail, at which point execution // will need to backtrack to the alternation. We emit a branching table at the end of the // alternation, with a label that will be left as the "doneLabel" upon exiting emitting the // alternation. The branch table is populated with an entry for each branch of the alternation, // containing either the label for the last backtracking construct in the branch if such a construct // existed (in which case the doneLabel upon emitting that node will be different from before it) // or the label for the next branch. var labelMap = new Label[childCount]; Label backtrackLabel = DefineLabel(); for (int i = 0; i < childCount; i++) { bool isLastBranch = i == childCount - 1; Label nextBranch = default; if (!isLastBranch) { // Failure to match any branch other than the last one should result // in jumping to process the next branch. nextBranch = DefineLabel(); doneLabel = nextBranch; } else { // Failure to match the last branch is equivalent to failing to match // the whole alternation, which means those failures should jump to // what "doneLabel" was defined as when starting the alternation. doneLabel = originalDoneLabel; } // Emit the code for each branch. EmitNode(node.Child(i)); // Add this branch to the backtracking table. At this point, either the child // had backtracking constructs, in which case doneLabel points to the last one // and that's where we'll want to jump to, or it doesn't, in which case doneLabel // still points to the nextBranch, which similarly is where we'll want to jump to. if (!isAtomic) { // if (stackpos + 3 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = i; // base.runstack[stackpos++] = startingCapturePos; // base.runstack[stackpos++] = startingPos; EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldc(i)); if (startingCapturePos is not null) { EmitStackPush(() => Ldloc(startingCapturePos)); } EmitStackPush(() => Ldloc(startingPos)); } labelMap[i] = doneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. // pos += sliceStaticPos; // sliceStaticPos = 0; // goto matchLabel; TransferSliceStaticPosToPos(); BrFar(matchLabel); // Reset state for next branch and loop around to generate it. This includes // setting pos back to what it was at the beginning of the alternation, // updating slice to be the full length it was, and if there's a capture that // needs to be reset, uncapturing it. if (!isLastBranch) { // NextBranch: // pos = startingPos; // slice = inputSpan.Slice(pos); // while (base.Crawlpos() > startingCapturePos) base.Uncapture(); MarkLabel(nextBranch); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } } } // We should never fall through to this location in the generated code. Either // a branch succeeded in matching and jumped to the end, or a branch failed in // matching and jumped to the next branch location. We only get to this code // if backtracking occurs and the code explicitly jumps here based on our setting // "doneLabel" to the label for this section. Thus, we only need to emit it if // something can backtrack to us, which can't happen if we're inside of an atomic // node. Thus, emit the backtracking section only if we're non-atomic. if (isAtomic) { doneLabel = originalDoneLabel; } else { doneLabel = backtrackLabel; MarkLabel(backtrackLabel); // startingPos = base.runstack[--stackpos]; // startingCapturePos = base.runstack[--stackpos]; // switch (base.runstack[--stackpos]) { ... } // branch number EmitStackPop(); Stloc(startingPos); if (startingCapturePos is not null) { EmitStackPop(); Stloc(startingCapturePos); } EmitStackPop(); Switch(labelMap); } // Successfully completed the alternate. MarkLabel(matchLabel); Debug.Assert(sliceStaticPos == 0); } // Emits the code to handle a backreference. void EmitBackreference(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Backreference, $"Unexpected type: {node.Kind}"); int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; TransferSliceStaticPosToPos(); Label backreferenceEnd = DefineLabel(); // if (!base.IsMatched(capnum)) goto (ecmascript ? end : doneLabel); Ldthis(); Ldc(capnum); Call(s_isMatchedMethod); BrfalseFar((node.Options & RegexOptions.ECMAScript) == 0 ? doneLabel : backreferenceEnd); using RentedLocalBuilder matchLength = RentInt32Local(); using RentedLocalBuilder matchIndex = RentInt32Local(); using RentedLocalBuilder i = RentInt32Local(); // int matchLength = base.MatchLength(capnum); Ldthis(); Ldc(capnum); Call(s_matchLengthMethod); Stloc(matchLength); if (!rtl) { // if (slice.Length < matchLength) goto doneLabel; Ldloca(slice); Call(s_spanGetLengthMethod); } else { // if (pos < matchLength) goto doneLabel; Ldloc(pos); } Ldloc(matchLength); BltFar(doneLabel); // int matchIndex = base.MatchIndex(capnum); Ldthis(); Ldc(capnum); Call(s_matchIndexMethod); Stloc(matchIndex); Label condition = DefineLabel(); Label body = DefineLabel(); // for (int i = 0; ...) Ldc(0); Stloc(i); Br(condition); MarkLabel(body); // if (inputSpan[matchIndex + i] != slice[i]) goto doneLabel; // for rtl, instead of slice[i] using inputSpan[pos - matchLength + i] Ldloca(inputSpan); Ldloc(matchIndex); Ldloc(i); Add(); Call(s_spanGetItemMethod); LdindU2(); if (IsCaseInsensitive(node)) { CallToLower(); } if (!rtl) { Ldloca(slice); Ldloc(i); } else { Ldloca(inputSpan); Ldloc(pos); Ldloc(matchLength); Sub(); Ldloc(i); Add(); } Call(s_spanGetItemMethod); LdindU2(); if (IsCaseInsensitive(node)) { CallToLower(); } BneFar(doneLabel); // for (...; ...; i++) Ldloc(i); Ldc(1); Add(); Stloc(i); // for (...; i < matchLength; ...) MarkLabel(condition); Ldloc(i); Ldloc(matchLength); Blt(body); // pos += matchLength; // or -= for rtl Ldloc(pos); Ldloc(matchLength); if (!rtl) { Add(); } else { Sub(); } Stloc(pos); if (!rtl) { SliceInputSpan(); } MarkLabel(backreferenceEnd); } // Emits the code for an if(backreference)-then-else conditional. void EmitBackreferenceConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.BackreferenceConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 2, $"Expected 2 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // Get the capture number to test. int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(0); RegexNode? noBranch = node.Child(1) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; Label originalDoneLabel = doneLabel; Label refNotMatched = DefineLabel(); Label endConditional = DefineLabel(); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the conditional needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. LocalBuilder resumeAt = DeclareInt32(); // if (!base.IsMatched(capnum)) goto refNotMatched; Ldthis(); Ldc(capnum); Call(s_isMatchedMethod); BrfalseFar(refNotMatched); // The specified capture was captured. Run the "yes" branch. // If it successfully matches, jump to the end. EmitNode(yesBranch); TransferSliceStaticPosToPos(); Label postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 0; Ldc(0); Stloc(resumeAt); } bool needsEndConditional = postYesDoneLabel != originalDoneLabel || noBranch is not null; if (needsEndConditional) { // goto endConditional; BrFar(endConditional); } MarkLabel(refNotMatched); Label postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { // resumeAt = 1; Ldc(1); Stloc(resumeAt); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 2; Ldc(2); Stloc(resumeAt); } } if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { // We're atomic by our parent, so even if either child branch has backtracking constructs, // we don't need to emit any backtracking logic in support, as nothing will backtrack in. // Instead, we just ensure we revert back to the original done label so that any backtracking // skips over this node. doneLabel = originalDoneLabel; if (needsEndConditional) { MarkLabel(endConditional); } } else { // Subsequent expressions might try to backtrack to here, so output a backtracking map based on resumeAt. // Skip the backtracking section // goto endConditional; Debug.Assert(needsEndConditional); Br(endConditional); // Backtrack section Label backtrack = DefineLabel(); doneLabel = backtrack; MarkLabel(backtrack); // Pop from the stack the branch that was used and jump back to its backtracking location. // resumeAt = base.runstack[--stackpos]; EmitStackPop(); Stloc(resumeAt); if (postYesDoneLabel != originalDoneLabel) { // if (resumeAt == 0) goto postIfDoneLabel; Ldloc(resumeAt); Ldc(0); BeqFar(postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { // if (resumeAt == 1) goto postNoDoneLabel; Ldloc(resumeAt); Ldc(1); BeqFar(postNoDoneLabel); } // goto originalDoneLabel; BrFar(originalDoneLabel); if (needsEndConditional) { MarkLabel(endConditional); } // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = resumeAt; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(resumeAt)); } } // Emits the code for an if(expression)-then-else conditional. void EmitExpressionConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.ExpressionConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 3, $"Expected 3 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // The first child node is the condition expression. If this matches, then we branch to the "yes" branch. // If it doesn't match, then we branch to the optional "no" branch if it exists, or simply skip the "yes" // branch, otherwise. The condition is treated as a positive lookaround. RegexNode condition = node.Child(0); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(1); RegexNode? noBranch = node.Child(2) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; Label originalDoneLabel = doneLabel; Label expressionNotMatched = DefineLabel(); Label endConditional = DefineLabel(); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the condition needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. LocalBuilder? resumeAt = null; if (!isAtomic) { resumeAt = DeclareInt32(); } // If the condition expression has captures, we'll need to uncapture them in the case of no match. LocalBuilder? startingCapturePos = null; if (analysis.MayContainCapture(condition)) { // int startingCapturePos = base.Crawlpos(); startingCapturePos = DeclareInt32(); Ldthis(); Call(s_crawlposMethod); Stloc(startingCapturePos); } // Emit the condition expression. Route any failures to after the yes branch. This code is almost // the same as for a positive lookaround; however, a positive lookaround only needs to reset the position // on a successful match, as a failed match fails the whole expression; here, we need to reset the // position on completion, regardless of whether the match is successful or not. doneLabel = expressionNotMatched; // Save off pos. We'll need to reset this upon successful completion of the lookaround. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingSliceStaticPos = sliceStaticPos; // Emit the child. The condition expression is a zero-width assertion, which is atomic, // so prevent backtracking into it. EmitNode(condition); doneLabel = originalDoneLabel; // After the condition completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. // pos = startingPos; // slice = inputSpan.Slice(pos); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingSliceStaticPos; // The expression matched. Run the "yes" branch. If it successfully matches, jump to the end. EmitNode(yesBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch Label postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 0; Ldc(0); Stloc(resumeAt!); } // goto endConditional; BrFar(endConditional); // After the condition completes unsuccessfully, reset the text positions // _and_ reset captures, which should not persist when the whole expression failed. // pos = startingPos; MarkLabel(expressionNotMatched); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } Label postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { // resumeAt = 1; Ldc(1); Stloc(resumeAt!); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 2; Ldc(2); Stloc(resumeAt!); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { // EndConditional: doneLabel = originalDoneLabel; MarkLabel(endConditional); } else { Debug.Assert(resumeAt is not null); // Skip the backtracking section. BrFar(endConditional); Label backtrack = DefineLabel(); doneLabel = backtrack; MarkLabel(backtrack); // resumeAt = StackPop(); EmitStackPop(); Stloc(resumeAt); if (postYesDoneLabel != originalDoneLabel) { // if (resumeAt == 0) goto postYesDoneLabel; Ldloc(resumeAt); Ldc(0); BeqFar(postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { // if (resumeAt == 1) goto postNoDoneLabel; Ldloc(resumeAt); Ldc(1); BeqFar(postNoDoneLabel); } // goto postConditionalDoneLabel; BrFar(originalDoneLabel); // EndConditional: MarkLabel(endConditional); // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = resumeAt; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(resumeAt!)); } } // Emits the code for a Capture node. void EmitCapture(RegexNode node, RegexNode? subsequent = null) { Debug.Assert(node.Kind is RegexNodeKind.Capture, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); int uncapnum = RegexParser.MapCaptureNumber(node.N, _regexTree.CaptureNumberSparseMapping); bool isAtomic = analysis.IsAtomicByAncestor(node); // pos += sliceStaticPos; // slice = slice.Slice(sliceStaticPos); // startingPos = pos; TransferSliceStaticPosToPos(); LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); RegexNode child = node.Child(0); if (uncapnum != -1) { // if (!IsMatched(uncapnum)) goto doneLabel; Ldthis(); Ldc(uncapnum); Call(s_isMatchedMethod); BrfalseFar(doneLabel); } // Emit child node. Label originalDoneLabel = doneLabel; EmitNode(child, subsequent); bool childBacktracks = doneLabel != originalDoneLabel; // pos += sliceStaticPos; // slice = slice.Slice(sliceStaticPos); TransferSliceStaticPosToPos(); if (uncapnum == -1) { // Capture(capnum, startingPos, pos); Ldthis(); Ldc(capnum); Ldloc(startingPos); Ldloc(pos); Call(s_captureMethod); } else { // TransferCapture(capnum, uncapnum, startingPos, pos); Ldthis(); Ldc(capnum); Ldc(uncapnum); Ldloc(startingPos); Ldloc(pos); Call(s_transferCaptureMethod); } if (isAtomic || !childBacktracks) { // If the capture is atomic and nothing can backtrack into it, we're done. // Similarly, even if the capture isn't atomic, if the captured expression // doesn't do any backtracking, we're done. doneLabel = originalDoneLabel; } else { // We're not atomic and the child node backtracks. When it does, we need // to ensure that the starting position for the capture is appropriately // reset to what it was initially (it could have changed as part of being // in a loop or similar). So, we emit a backtracking section that // pushes/pops the starting position before falling through. // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = startingPos; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(startingPos)); // Skip past the backtracking section // goto backtrackingEnd; Label backtrackingEnd = DefineLabel(); Br(backtrackingEnd); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } // Emits code to unwind the capture stack until the crawl position specified in the provided local. void EmitUncaptureUntil(LocalBuilder startingCapturePos) { Debug.Assert(startingCapturePos != null); // while (base.Crawlpos() > startingCapturePos) base.Uncapture(); Label condition = DefineLabel(); Label body = DefineLabel(); Br(condition); MarkLabel(body); Ldthis(); Call(s_uncaptureMethod); MarkLabel(condition); Ldthis(); Call(s_crawlposMethod); Ldloc(startingCapturePos); Bgt(body); } // Emits the code to handle a positive lookaround assertion. This is a positive lookahead // for left-to-right and a positive lookbehind for right-to-left. void EmitPositiveLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.PositiveLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } // Save off pos. We'll need to reset this upon successful completion of the lookaround. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // After the child completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. // pos = startingPos; // slice = inputSpan.Slice(pos); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; } // Emits the code to handle a negative lookaround assertion. This is a negative lookahead // for left-to-right and a negative lookbehind for right-to-left. void EmitNegativeLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } Label originalDoneLabel = doneLabel; // Save off pos. We'll need to reset this upon successful completion of the lookaround. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; Label negativeLookaheadDoneLabel = DefineLabel(); doneLabel = negativeLookaheadDoneLabel; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // If the generated code ends up here, it matched the lookaround, which actually // means failure for a _negative_ lookaround, so we need to jump to the original done. // goto originalDoneLabel; BrFar(originalDoneLabel); // Failures (success for a negative lookaround) jump here. MarkLabel(negativeLookaheadDoneLabel); if (doneLabel == negativeLookaheadDoneLabel) { doneLabel = originalDoneLabel; } // After the child completes in failure (success for negative lookaround), reset the text positions. // pos = startingPos; Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; doneLabel = originalDoneLabel; } // Emits the code for the node. void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(EmitNode, node, subsequent, emitLengthChecksIfRequired); return; } // RightToLeft doesn't take advantage of static positions. While RightToLeft won't update static // positions, a previous operation may have left us with a non-zero one. Make sure it's zero'd out // such that pos and slice are up-to-date. Note that RightToLeft also shouldn't use the slice span, // as it's not kept up-to-date; any RightToLeft implementation that wants to use it must first update // it from pos. if ((node.Options & RegexOptions.RightToLeft) != 0) { TransferSliceStaticPosToPos(); } switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: case RegexNodeKind.Bol: case RegexNodeKind.Eol: case RegexNodeKind.End: case RegexNodeKind.EndZ: EmitAnchors(node); break; case RegexNodeKind.Boundary: case RegexNodeKind.NonBoundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.NonECMABoundary: EmitBoundary(node); break; case RegexNodeKind.Multi: EmitMultiChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: EmitSingleChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: EmitSingleCharLoop(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: EmitSingleCharLazy(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: EmitSingleCharAtomicLoop(node); break; case RegexNodeKind.Loop: EmitLoop(node); break; case RegexNodeKind.Lazyloop: EmitLazy(node); break; case RegexNodeKind.Alternate: EmitAlternation(node); break; case RegexNodeKind.Concatenate: EmitConcatenation(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Atomic: EmitAtomic(node, subsequent); break; case RegexNodeKind.Backreference: EmitBackreference(node); break; case RegexNodeKind.BackreferenceConditional: EmitBackreferenceConditional(node); break; case RegexNodeKind.ExpressionConditional: EmitExpressionConditional(node); break; case RegexNodeKind.Capture: EmitCapture(node, subsequent); break; case RegexNodeKind.PositiveLookaround: EmitPositiveLookaroundAssertion(node); break; case RegexNodeKind.NegativeLookaround: EmitNegativeLookaroundAssertion(node); break; case RegexNodeKind.Nothing: BrFar(doneLabel); break; case RegexNodeKind.Empty: // Emit nothing. break; case RegexNodeKind.UpdateBumpalong: EmitUpdateBumpalong(node); break; default: Debug.Fail($"Unexpected node type: {node.Kind}"); break; } } // Emits the node for an atomic. void EmitAtomic(RegexNode node, RegexNode? subsequent) { Debug.Assert(node.Kind is RegexNodeKind.Atomic or RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); RegexNode child = node.Child(0); if (!analysis.MayBacktrack(child)) { // If the child has no backtracking, the atomic is a nop and we can just skip it. // Note that the source generator equivalent for this is in the top-level EmitNode, in order to avoid // outputting some extra comments and scopes. As such formatting isn't a concern for the compiler, // the logic is instead here in EmitAtomic. EmitNode(child, subsequent); return; } // Grab the current done label and the current backtracking position. The purpose of the atomic node // is to ensure that nodes after it that might backtrack skip over the atomic, which means after // rendering the atomic's child, we need to reset the label so that subsequent backtracking doesn't // see any label left set by the atomic's child. We also need to reset the backtracking stack position // so that the state on the stack remains consistent. Label originalDoneLabel = doneLabel; // int startingStackpos = stackpos; using RentedLocalBuilder startingStackpos = RentInt32Local(); Ldloc(stackpos); Stloc(startingStackpos); // Emit the child. EmitNode(child, subsequent); // Reset the stack position and done label. // stackpos = startingStackpos; Ldloc(startingStackpos); Stloc(stackpos); doneLabel = originalDoneLabel; } // Emits the code to handle updating base.runtextpos to pos in response to // an UpdateBumpalong node. This is used when we want to inform the scan loop that // it should bump from this location rather than from the original location. void EmitUpdateBumpalong(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.UpdateBumpalong, $"Unexpected type: {node.Kind}"); // if (base.runtextpos < pos) // { // base.runtextpos = pos; // } TransferSliceStaticPosToPos(); Ldthisfld(s_runtextposField); Ldloc(pos); Label skipUpdate = DefineLabel(); Bge(skipUpdate); Ldthis(); Ldloc(pos); Stfld(s_runtextposField); MarkLabel(skipUpdate); } // Emits code for a concatenation void EmitConcatenation(RegexNode node, RegexNode? subsequent, bool emitLengthChecksIfRequired) { Debug.Assert(node.Kind is RegexNodeKind.Concatenate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // Emit the code for each child one after the other. int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { // If we can find a subsequence of fixed-length children, we can emit a length check once for that sequence // and then skip the individual length checks for each. if (!rtl && emitLengthChecksIfRequired && node.TryGetJoinableLengthCheckChildRange(i, out int requiredLength, out int exclusiveEnd)) { EmitSpanLengthCheck(requiredLength); for (; i < exclusiveEnd; i++) { EmitNode(node.Child(i), GetSubsequent(i, node, subsequent), emitLengthChecksIfRequired: false); } i--; continue; } EmitNode(node.Child(i), GetSubsequent(i, node, subsequent)); } // Gets the node to treat as the subsequent one to node.Child(index) static RegexNode? GetSubsequent(int index, RegexNode node, RegexNode? subsequent) { int childCount = node.ChildCount(); for (int i = index + 1; i < childCount; i++) { RegexNode next = node.Child(i); if (next.Kind is not RegexNodeKind.UpdateBumpalong) // skip node types that don't have a semantic impact { return next; } } return subsequent; } } // Emits the code to handle a single-character match. void EmitSingleChar(RegexNode node, bool emitLengthCheck = true, LocalBuilder? offset = null) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; Debug.Assert(!rtl || offset is null); if (emitLengthCheck) { if (!rtl) { // if ((uint)(sliceStaticPos + offset) >= slice.Length) goto Done; EmitSpanLengthCheck(1, offset); } else { // if ((uint)(pos - 1) >= inputSpan.Length) goto Done; Ldloc(pos); Ldc(1); Sub(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); } } if (!rtl) { // slice[staticPos + offset] Ldloca(slice); EmitSum(sliceStaticPos, offset); } else { // inputSpan[pos - 1] Ldloca(inputSpan); EmitSum(-1, pos); } Call(s_spanGetItemMethod); LdindU2(); // if (loadedChar != ch) goto doneLabel; if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(doneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(doneLabel); } else // IsNotoneFamily { BeqFar(doneLabel); } } if (!rtl) { sliceStaticPos++; } else { // pos--; Ldloc(pos); Ldc(1); Sub(); Stloc(pos); } } // Emits the code to handle a boundary check on a character. void EmitBoundary(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Boundary or RegexNodeKind.NonBoundary or RegexNodeKind.ECMABoundary or RegexNodeKind.NonECMABoundary, $"Unexpected type: {node.Kind}"); if ((node.Options & RegexOptions.RightToLeft) != 0) { // RightToLeft doesn't use static position. This ensures it's 0. TransferSliceStaticPosToPos(); } // if (!IsBoundary(inputSpan, pos + sliceStaticPos)) goto doneLabel; Ldthis(); Ldloc(inputSpan); Ldloc(pos); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Add(); } switch (node.Kind) { case RegexNodeKind.Boundary: Call(s_isBoundaryMethod); BrfalseFar(doneLabel); break; case RegexNodeKind.NonBoundary: Call(s_isBoundaryMethod); BrtrueFar(doneLabel); break; case RegexNodeKind.ECMABoundary: Call(s_isECMABoundaryMethod); BrfalseFar(doneLabel); break; default: Debug.Assert(node.Kind == RegexNodeKind.NonECMABoundary); Call(s_isECMABoundaryMethod); BrtrueFar(doneLabel); break; } } // Emits the code to handle various anchors. void EmitAnchors(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.Bol or RegexNodeKind.End or RegexNodeKind.EndZ or RegexNodeKind.Eol, $"Unexpected type: {node.Kind}"); Debug.Assert((node.Options & RegexOptions.RightToLeft) == 0 || sliceStaticPos == 0); Debug.Assert(sliceStaticPos >= 0); Debug.Assert(sliceStaticPos >= 0); switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: if (sliceStaticPos > 0) { // If we statically know we've already matched part of the regex, there's no way we're at the // beginning or start, as we've already progressed past it. BrFar(doneLabel); } else { // if (pos > 0/start) goto doneLabel; Ldloc(pos); if (node.Kind == RegexNodeKind.Beginning) { Ldc(0); } else { Ldthisfld(s_runtextstartField); } BneFar(doneLabel); } break; case RegexNodeKind.Bol: if (sliceStaticPos > 0) { // if (slice[sliceStaticPos - 1] != '\n') goto doneLabel; Ldloca(slice); Ldc(sliceStaticPos - 1); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); } else { // We can't use our slice in this case, because we'd need to access slice[-1], so we access the inputSpan directly: // if (pos > 0 && inputSpan[pos - 1] != '\n') goto doneLabel; Label success = DefineLabel(); Ldloc(pos); Ldc(0); Ble(success); Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } break; case RegexNodeKind.End: if (sliceStaticPos > 0) { // if (sliceStaticPos < slice.Length) goto doneLabel; Ldc(sliceStaticPos); Ldloca(slice); } else { // if (pos < inputSpan.Length) goto doneLabel; Ldloc(pos); Ldloca(inputSpan); } Call(s_spanGetLengthMethod); BltUnFar(doneLabel); break; case RegexNodeKind.EndZ: if (sliceStaticPos > 0) { // if (sliceStaticPos < slice.Length - 1) goto doneLabel; Ldc(sliceStaticPos); Ldloca(slice); } else { // if (pos < inputSpan.Length - 1) goto doneLabel Ldloc(pos); Ldloca(inputSpan); } Call(s_spanGetLengthMethod); Ldc(1); Sub(); BltFar(doneLabel); goto case RegexNodeKind.Eol; case RegexNodeKind.Eol: if (sliceStaticPos > 0) { // if (sliceStaticPos < slice.Length && slice[sliceStaticPos] != '\n') goto doneLabel; Label success = DefineLabel(); Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUn(success); Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } else { // if ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\n') goto doneLabel; Label success = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUn(success); Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } break; } } // Emits the code to handle a multiple-character match. void EmitMultiChar(RegexNode node, bool emitLengthCheck) { Debug.Assert(node.Kind is RegexNodeKind.Multi, $"Unexpected type: {node.Kind}"); EmitMultiCharString(node.Str!, IsCaseInsensitive(node), emitLengthCheck, (node.Options & RegexOptions.RightToLeft) != 0); } void EmitMultiCharString(string str, bool caseInsensitive, bool emitLengthCheck, bool rightToLeft) { Debug.Assert(str.Length >= 2); if (rightToLeft) { Debug.Assert(emitLengthCheck); TransferSliceStaticPosToPos(); // if ((uint)(pos - str.Length) >= inputSpan.Length) goto doneLabel; Ldloc(pos); Ldc(str.Length); Sub(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); for (int i = str.Length - 1; i >= 0; i--) { // if (inputSpan[--pos] != str[str.Length - 1 - i]) goto doneLabel Ldloc(pos); Ldc(1); Sub(); Stloc(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); if (caseInsensitive) { CallToLower(); } Ldc(str[i]); BneFar(doneLabel); } return; } if (caseInsensitive) // StartsWith(..., XxIgnoreCase) won't necessarily be the same as char-by-char comparison { // This case should be relatively rare. It will only occur with IgnoreCase and a series of non-ASCII characters. if (emitLengthCheck) { EmitSpanLengthCheck(str.Length); } foreach (char c in str) { // if (c != slice[sliceStaticPos++]) goto doneLabel; EmitTextSpanOffset(); sliceStaticPos++; LdindU2(); CallToLower(); Ldc(c); BneFar(doneLabel); } } else { // if (!slice.Slice(sliceStaticPos).StartsWith("...") goto doneLabel; Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); Ldstr(str); Call(s_stringAsSpanMethod); Call(s_spanStartsWith); BrfalseFar(doneLabel); sliceStaticPos += str.Length; } } // Emits the code to handle a backtracking, single-character loop. void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop, $"Unexpected type: {node.Kind}"); // If this is actually atomic based on its parent, emit it as atomic instead; no backtracking necessary. if (analysis.IsAtomicByAncestor(node)) { EmitSingleCharAtomicLoop(node); return; } // If this is actually a repeater, emit that instead; no backtracking necessary. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // Emit backtracking around an atomic single char loop. We can then implement the backtracking // as an afterthought, since we know exactly how many characters are accepted by each iteration // of the wrapped loop (1) and that there's nothing captured by the loop. Debug.Assert(node.M < node.N); Label backtrackingLabel = DefineLabel(); Label endLoop = DefineLabel(); LocalBuilder startingPos = DeclareInt32(); LocalBuilder endingPos = DeclareInt32(); LocalBuilder? capturepos = expressionHasCaptures ? DeclareInt32() : null; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // Grab the current position, then emit the loop as atomic, and then // grab the current position again. Even though we emit the loop without // knowledge of backtracking, we can layer it on top by just walking back // through the individual characters (a benefit of the loop matching exactly // one character per iteration, no possible captures within the loop, etc.) // int startingPos = pos; Ldloc(pos); Stloc(startingPos); EmitSingleCharAtomicLoop(node); // int endingPos = pos; TransferSliceStaticPosToPos(); Ldloc(pos); Stloc(endingPos); // int capturepos = base.Crawlpos(); if (capturepos is not null) { Ldthis(); Call(s_crawlposMethod); Stloc(capturepos); } // startingPos += node.M; // or -= for rtl if (node.M > 0) { Ldloc(startingPos); Ldc(!rtl ? node.M : -node.M); Add(); Stloc(startingPos); } // goto endLoop; BrFar(endLoop); // Backtracking section. Subsequent failures will jump to here, at which // point we decrement the matched count as long as it's above the minimum // required, and try again by flowing to everything that comes after this. MarkLabel(backtrackingLabel); if (capturepos is not null) { // capturepos = base.runstack[--stackpos]; // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitStackPop(); Stloc(capturepos); EmitUncaptureUntil(capturepos); } // endingPos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(endingPos); EmitStackPop(); Stloc(startingPos); // if (startingPos >= endingPos) goto doneLabel; // or <= for rtl Ldloc(startingPos); Ldloc(endingPos); if (!rtl) { BgeFar(doneLabel); } else { BleFar(doneLabel); } if (!rtl && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal) { // endingPos = inputSpan.Slice(startingPos, Math.Min(inputSpan.Length, endingPos + literal.Length - 1) - startingPos).LastIndexOf(literal); // if (endingPos < 0) // { // goto doneLabel; // } Ldloca(inputSpan); Ldloc(startingPos); if (literal.Item2 is not null) { Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldloc(endingPos); Ldc(literal.Item2.Length - 1); Add(); Call(s_mathMinIntInt); Ldloc(startingPos); Sub(); Call(s_spanSliceIntIntMethod); Ldstr(literal.Item2); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfSpan); } else { Ldloc(endingPos); Ldloc(startingPos); Sub(); Call(s_spanSliceIntIntMethod); if (literal.Item3 is not null) { switch (literal.Item3.Length) { case 2: Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Call(s_spanLastIndexOfAnyCharChar); break; case 3: Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Ldc(literal.Item3[2]); Call(s_spanLastIndexOfAnyCharCharChar); break; default: Ldstr(literal.Item3); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfAnySpan); break; } } else { Ldc(literal.Item1); Call(s_spanLastIndexOfChar); } } Stloc(endingPos); Ldloc(endingPos); Ldc(0); BltFar(doneLabel); // endingPos += startingPos; Ldloc(endingPos); Ldloc(startingPos); Add(); Stloc(endingPos); } else { // endingPos--; // or ++ for rtl Ldloc(endingPos); Ldc(!rtl ? 1 : -1); Sub(); Stloc(endingPos); } // pos = endingPos; Ldloc(endingPos); Stloc(pos); if (!rtl) { // slice = inputSpan.Slice(pos); SliceInputSpan(); } MarkLabel(endLoop); EmitStackResizeIfNeeded(expressionHasCaptures ? 3 : 2); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(endingPos)); if (capturepos is not null) { EmitStackPush(() => Ldloc(capturepos!)); } doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes } void EmitSingleCharLazy(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy, $"Unexpected type: {node.Kind}"); // Emit the min iterations as a repeater. Any failures here don't necessitate backtracking, // as the lazy itself failed to match, and there's no backtracking possible by the individual // characters/iterations themselves. if (node.M > 0) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); } // If the whole thing was actually that repeater, we're done. Similarly, if this is actually an atomic // lazy loop, nothing will ever backtrack into this node, so we never need to iterate more than the minimum. if (node.M == node.N || analysis.IsAtomicByAncestor(node)) { return; } Debug.Assert(node.M < node.N); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // We now need to match one character at a time, each time allowing the remainder of the expression // to try to match, and only matching another character if the subsequent expression fails to match. // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // If the loop isn't unbounded, track the number of iterations and the max number to allow. LocalBuilder? iterationCount = null; int? maxIterations = null; if (node.N != int.MaxValue) { maxIterations = node.N - node.M; // int iterationCount = 0; iterationCount = DeclareInt32(); Ldc(0); Stloc(iterationCount); } // Track the current crawl position. Upon backtracking, we'll unwind any captures beyond this point. LocalBuilder? capturepos = expressionHasCaptures ? DeclareInt32() : null; // Track the current pos. Each time we backtrack, we'll reset to the stored position, which // is also incremented each time we match another character in the loop. // int startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); // Skip the backtracking section for the initial subsequent matching. We've already matched the // minimum number of iterations, which means we can successfully match with zero additional iterations. // goto endLoopLabel; Label endLoopLabel = DefineLabel(); BrFar(endLoopLabel); // Backtracking section. Subsequent failures will jump to here. Label backtrackingLabel = DefineLabel(); MarkLabel(backtrackingLabel); // Uncapture any captures if the expression has any. It's possible the captures it has // are before this node, in which case this is wasted effort, but still functionally correct. if (capturepos is not null) { // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitUncaptureUntil(capturepos); } // If there's a max number of iterations, see if we've exceeded the maximum number of characters // to match. If we haven't, increment the iteration count. if (maxIterations is not null) { // if (iterationCount >= maxIterations) goto doneLabel; Ldloc(iterationCount!); Ldc(maxIterations.Value); BgeFar(doneLabel); // iterationCount++; Ldloc(iterationCount!); Ldc(1); Add(); Stloc(iterationCount!); } // Now match the next item in the lazy loop. We need to reset the pos to the position // just after the last character in this loop was matched, and we need to store the resulting position // for the next time we backtrack. // pos = startingPos; // Match single char; Ldloc(startingPos); Stloc(pos); SliceInputSpan(); EmitSingleChar(node); TransferSliceStaticPosToPos(); // Now that we've appropriately advanced by one character and are set for what comes after the loop, // see if we can skip ahead more iterations by doing a search for a following literal. if (!rtl && iterationCount is null && node.Kind is RegexNodeKind.Notonelazy && !IsCaseInsensitive(node) && subsequent?.FindStartingLiteral(4) is ValueTuple<char, string?, string?> literal && // 5 == max optimized by IndexOfAny, and we need to reserve 1 for node.Ch (literal.Item3 is not null ? !literal.Item3.Contains(node.Ch) : (literal.Item2?[0] ?? literal.Item1) != node.Ch)) // no overlap between node.Ch and the start of the literal { // e.g. "<[^>]*?>" // This lazy loop will consume all characters other than node.Ch until the subsequent literal. // We can implement it to search for either that char or the literal, whichever comes first. // If it ends up being that node.Ch, the loop fails (we're only here if we're backtracking). // startingPos = slice.IndexOfAny(node.Ch, literal); Ldloc(slice); if (literal.Item3 is not null) { switch (literal.Item3.Length) { case 2: Ldc(node.Ch); Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(node.Ch + literal.Item3); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } else { Ldc(node.Ch); Ldc(literal.Item2?[0] ?? literal.Item1); Call(s_spanIndexOfAnyCharChar); } Stloc(startingPos); // if ((uint)startingPos >= (uint)slice.Length) goto doneLabel; Ldloc(startingPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); // if (slice[startingPos] == node.Ch) goto doneLabel; Ldloca(slice); Ldloc(startingPos); Call(s_spanGetItemMethod); LdindU2(); Ldc(node.Ch); BeqFar(doneLabel); // pos += startingPos; // slice = inputSpace.Slice(pos); Ldloc(pos); Ldloc(startingPos); Add(); Stloc(pos); SliceInputSpan(); } else if (!rtl && iterationCount is null && node.Kind is RegexNodeKind.Setlazy && node.Str == RegexCharClass.AnyClass && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal2) { // e.g. ".*?string" with RegexOptions.Singleline // This lazy loop will consume all characters until the subsequent literal. If the subsequent literal // isn't found, the loop fails. We can implement it to just search for that literal. // startingPos = slice.IndexOf(literal); Ldloc(slice); if (literal2.Item2 is not null) { Ldstr(literal2.Item2); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); } else if (literal2.Item3 is not null) { switch (literal2.Item3.Length) { case 2: Ldc(literal2.Item3[0]); Ldc(literal2.Item3[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(literal2.Item3[0]); Ldc(literal2.Item3[1]); Ldc(literal2.Item3[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(literal2.Item3); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } else { Ldc(literal2.Item1); Call(s_spanIndexOfChar); } Stloc(startingPos); // if (startingPos < 0) goto doneLabel; Ldloc(startingPos); Ldc(0); BltFar(doneLabel); // pos += startingPos; // slice = inputSpace.Slice(pos); Ldloc(pos); Ldloc(startingPos); Add(); Stloc(pos); SliceInputSpan(); } // Store the position we've left off at in case we need to iterate again. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Update the done label for everything that comes after this node. This is done after we emit the single char // matching, as that failing indicates the loop itself has failed to match. Label originalDoneLabel = doneLabel; doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes MarkLabel(endLoopLabel); if (capturepos is not null) { // capturepos = base.CrawlPos(); Ldthis(); Call(s_crawlposMethod); Stloc(capturepos); } if (node.IsInLoop()) { // Store the loop's state // base.runstack[stackpos++] = startingPos; // base.runstack[stackpos++] = capturepos; // base.runstack[stackpos++] = iterationCount; EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); if (capturepos is not null) { EmitStackPush(() => Ldloc(capturepos)); } if (iterationCount is not null) { EmitStackPush(() => Ldloc(iterationCount)); } // Skip past the backtracking section Label backtrackingEnd = DefineLabel(); BrFar(backtrackingEnd); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // iterationCount = base.runstack[--stackpos]; // capturepos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; if (iterationCount is not null) { EmitStackPop(); Stloc(iterationCount); } if (capturepos is not null) { EmitStackPop(); Stloc(capturepos); } EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } void EmitLazy(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; Label originalDoneLabel = doneLabel; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually an atomic lazy loop, we need to output just the minimum number of iterations, // as nothing will backtrack into the lazy loop to get it progress further. if (isAtomic) { switch (minIterations) { case 0: // Atomic lazy with a min count of 0: nop. return; case 1: // Atomic lazy with a min count of 1: just output the child, no looping required. EmitNode(node.Child(0)); return; } } // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); LocalBuilder startingPos = DeclareInt32(); LocalBuilder iterationCount = DeclareInt32(); LocalBuilder sawEmpty = DeclareInt32(); Label body = DefineLabel(); Label endLoop = DefineLabel(); // iterationCount = 0; // startingPos = pos; // sawEmpty = 0; // false Ldc(0); Stloc(iterationCount); Ldloc(pos); Stloc(startingPos); Ldc(0); Stloc(sawEmpty); // If the min count is 0, start out by jumping right to what's after the loop. Backtracking // will then bring us back in to do further iterations. if (minIterations == 0) { // goto endLoop; BrFar(endLoop); } // Iteration body MarkLabel(body); EmitTimeoutCheck(); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. // base.runstack[stackpos++] = base.Crawlpos(); // base.runstack[stackpos++] = startingPos; // base.runstack[stackpos++] = pos; // base.runstack[stackpos++] = sawEmpty; EmitStackResizeIfNeeded(3); if (expressionHasCaptures) { EmitStackPush(() => { Ldthis(); Call(s_crawlposMethod); }); } EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(pos)); EmitStackPush(() => Ldloc(sawEmpty)); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. // iterationCount++; Ldloc(iterationCount); Ldc(1); Add(); Stloc(iterationCount); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. Label iterationFailedLabel = DefineLabel(); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 if (doneLabel == iterationFailedLabel) { doneLabel = originalDoneLabel; } // Loop condition. Continue iterating if we've not yet reached the minimum. if (minIterations > 0) { // if (iterationCount < minIterations) goto body; Ldloc(iterationCount); Ldc(minIterations); BltFar(body); } // If the last iteration was empty, we need to prevent further iteration from this point // unless we backtrack out of this iteration. We can do that easily just by pretending // we reached the max iteration count. // if (pos == startingPos) sawEmpty = 1; // true Label skipSawEmptySet = DefineLabel(); Ldloc(pos); Ldloc(startingPos); Bne(skipSawEmptySet); Ldc(1); Stloc(sawEmpty); MarkLabel(skipSawEmptySet); // We matched the next iteration. Jump to the subsequent code. // goto endLoop; BrFar(endLoop); // Now handle what happens when an iteration fails. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel); // iterationCount--; Ldloc(iterationCount); Ldc(1); Sub(); Stloc(iterationCount); // if (iterationCount < 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BltFar(originalDoneLabel); // sawEmpty = base.runstack[--stackpos]; // pos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; // capturepos = base.runstack[--stackpos]; // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitStackPop(); Stloc(sawEmpty); EmitStackPop(); Stloc(pos); EmitStackPop(); Stloc(startingPos); if (expressionHasCaptures) { using RentedLocalBuilder poppedCrawlPos = RentInt32Local(); EmitStackPop(); Stloc(poppedCrawlPos); EmitUncaptureUntil(poppedCrawlPos); } SliceInputSpan(); if (doneLabel == originalDoneLabel) { // goto originalDoneLabel; BrFar(originalDoneLabel); } else { // if (iterationCount == 0) goto originalDoneLabel; // goto doneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); BrFar(doneLabel); } MarkLabel(endLoop); if (!isAtomic) { // Store the capture's state and skip the backtracking section EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(iterationCount)); EmitStackPush(() => Ldloc(sawEmpty)); Label skipBacktrack = DefineLabel(); BrFar(skipBacktrack); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // sawEmpty = base.runstack[--stackpos]; // iterationCount = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(sawEmpty); EmitStackPop(); Stloc(iterationCount); EmitStackPop(); Stloc(startingPos); if (maxIterations == int.MaxValue) { // if (sawEmpty != 0) goto doneLabel; Ldloc(sawEmpty); Ldc(0); BneFar(doneLabel); } else { // if (iterationCount >= maxIterations || sawEmpty != 0) goto doneLabel; Ldloc(iterationCount); Ldc(maxIterations); BgeFar(doneLabel); Ldloc(sawEmpty); Ldc(0); BneFar(doneLabel); } // goto body; BrFar(body); doneLabel = backtrack; MarkLabel(skipBacktrack); } } // Emits the code to handle a loop (repeater) with a fixed number of iterations. // RegexNode.M is used for the number of iterations (RegexNode.N is ignored), as this // might be used to implement the required iterations of other kinds of loops. void EmitSingleCharRepeater(RegexNode node, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); int iterations = node.M; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; switch (iterations) { case 0: // No iterations, nothing to do. return; case 1: // Just match the individual item EmitSingleChar(node, emitLengthChecksIfRequired); return; case <= RegexNode.MultiVsRepeaterLimit when node.IsOneFamily && !IsCaseInsensitive(node): // This is a repeated case-sensitive character; emit it as a multi in order to get all the optimizations // afforded to a multi, e.g. unrolling the loop with multi-char reads/comparisons at a time. EmitMultiCharString(new string(node.Ch, iterations), caseInsensitive: false, emitLengthChecksIfRequired, rtl); return; } if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position with rtl Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); // for (int i = 0; ...) using RentedLocalBuilder iterationLocal = RentInt32Local(); Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); // TimeoutCheck(); // HandleSingleChar(); MarkLabel(bodyLabel); EmitTimeoutCheck(); EmitSingleChar(node); // for (...; ...; i++) Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); // for (...; i < iterations; ...) MarkLabel(conditionLabel); Ldloc(iterationLocal); Ldc(iterations); BltFar(bodyLabel); return; } // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length) goto doneLabel; if (emitLengthChecksIfRequired) { EmitSpanLengthCheck(iterations); } // Arbitrary limit for unrolling vs creating a loop. We want to balance size in the generated // code with other costs, like the (small) overhead of slicing to create the temp span to iterate. const int MaxUnrollSize = 16; if (iterations <= MaxUnrollSize) { // if (slice[sliceStaticPos] != c1 || // slice[sliceStaticPos + 1] != c2 || // ...) // goto doneLabel; for (int i = 0; i < iterations; i++) { EmitSingleChar(node, emitLengthCheck: false); } } else { // ReadOnlySpan<char> tmp = slice.Slice(sliceStaticPos, iterations); // for (int i = 0; i < tmp.Length; i++) // { // TimeoutCheck(); // if (tmp[i] != ch) goto Done; // } // sliceStaticPos += iterations; Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); using RentedLocalBuilder spanLocal = RentReadOnlySpanCharLocal(); Ldloca(slice); Ldc(sliceStaticPos); Ldc(iterations); Call(s_spanSliceIntIntMethod); Stloc(spanLocal); using RentedLocalBuilder iterationLocal = RentInt32Local(); Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); MarkLabel(bodyLabel); EmitTimeoutCheck(); LocalBuilder tmpTextSpanLocal = slice; // we want EmitSingleChar to refer to this temporary int tmpTextSpanPos = sliceStaticPos; slice = spanLocal; sliceStaticPos = 0; EmitSingleChar(node, emitLengthCheck: false, offset: iterationLocal); slice = tmpTextSpanLocal; sliceStaticPos = tmpTextSpanPos; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); MarkLabel(conditionLabel); Ldloc(iterationLocal); Ldloca(spanLocal); Call(s_spanGetLengthMethod); BltFar(bodyLabel); sliceStaticPos += iterations; } } // Emits the code to handle a non-backtracking, variable-length loop around a single character comparison. void EmitSingleCharAtomicLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); // If this is actually a repeater, emit that instead. if (node.M == node.N) { EmitSingleCharRepeater(node); return; } // If this is actually an optional single char, emit that instead. if (node.M == 0 && node.N == 1) { EmitAtomicSingleCharZeroOrOne(node); return; } Debug.Assert(node.N > node.M); int minIterations = node.M; int maxIterations = node.N; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; using RentedLocalBuilder iterationLocal = RentInt32Local(); Label atomicLoopDoneLabel = DefineLabel(); Span<char> setChars = stackalloc char[5]; // max optimized by IndexOfAny today int numSetChars = 0; if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position for rtl Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); // int i = 0; Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); // Body: // TimeoutCheck(); MarkLabel(bodyLabel); EmitTimeoutCheck(); // if (pos <= iterationLocal) goto atomicLoopDoneLabel; Ldloc(pos); Ldloc(iterationLocal); BleFar(atomicLoopDoneLabel); // if (inputSpan[pos - i - 1] != ch) goto atomicLoopDoneLabel; Ldloca(inputSpan); Ldloc(pos); Ldloc(iterationLocal); Sub(); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(atomicLoopDoneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(atomicLoopDoneLabel); } else // IsNotoneFamily { BeqFar(atomicLoopDoneLabel); } } // i++; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); // if (i >= maxIterations) goto atomicLoopDoneLabel; MarkLabel(conditionLabel); if (maxIterations != int.MaxValue) { Ldloc(iterationLocal); Ldc(maxIterations); BltFar(bodyLabel); } else { BrFar(bodyLabel); } } else if (node.IsNotoneFamily && maxIterations == int.MaxValue && (!IsCaseInsensitive(node))) { // For Notone, we're looking for a specific character, as everything until we find // it is consumed by the loop. If we're unbounded, such as with ".*" and if we're case-sensitive, // we can use the vectorized IndexOf to do the search, rather than open-coding it. The unbounded // restriction is purely for simplicity; it could be removed in the future with additional code to // handle the unbounded case. // int i = slice.Slice(sliceStaticPos).IndexOf(char); if (sliceStaticPos > 0) { Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); } else { Ldloc(slice); } Ldc(node.Ch); Call(s_spanIndexOfChar); Stloc(iterationLocal); // if (i >= 0) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldc(0); BgeFar(atomicLoopDoneLabel); // i = slice.Length - sliceStaticPos; Ldloca(slice); Call(s_spanGetLengthMethod); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Sub(); } Stloc(iterationLocal); } else if (node.IsSetFamily && maxIterations == int.MaxValue && !IsCaseInsensitive(node) && (numSetChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0 && RegexCharClass.IsNegated(node.Str!)) { // If the set is negated and contains only a few characters (if it contained 1 and was negated, it would // have been reduced to a Notone), we can use an IndexOfAny to find any of the target characters. // As with the notoneloopatomic above, the unbounded constraint is purely for simplicity. Debug.Assert(numSetChars > 1); // int i = slice.Slice(sliceStaticPos).IndexOfAny(ch1, ch2, ...); if (sliceStaticPos > 0) { Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); } else { Ldloc(slice); } switch (numSetChars) { case 2: Ldc(setChars[0]); Ldc(setChars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(setChars[0]); Ldc(setChars[1]); Ldc(setChars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(setChars.Slice(0, numSetChars).ToString()); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } Stloc(iterationLocal); // if (i >= 0) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldc(0); BgeFar(atomicLoopDoneLabel); // i = slice.Length - sliceStaticPos; Ldloca(slice); Call(s_spanGetLengthMethod); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Sub(); } Stloc(iterationLocal); } else if (node.IsSetFamily && maxIterations == int.MaxValue && node.Str == RegexCharClass.AnyClass) { // .* was used with RegexOptions.Singleline, which means it'll consume everything. Just jump to the end. // The unbounded constraint is the same as in the Notone case above, done purely for simplicity. // int i = inputSpan.Length - pos; TransferSliceStaticPosToPos(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldloc(pos); Sub(); Stloc(iterationLocal); } else { // For everything else, do a normal loop. // Transfer sliceStaticPos to pos to help with bounds check elimination on the loop. TransferSliceStaticPosToPos(); Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); // int i = 0; Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); // Body: // TimeoutCheck(); MarkLabel(bodyLabel); EmitTimeoutCheck(); // if ((uint)i >= (uint)slice.Length) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(atomicLoopDoneLabel); // if (slice[i] != ch) goto atomicLoopDoneLabel; Ldloca(slice); Ldloc(iterationLocal); Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(atomicLoopDoneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(atomicLoopDoneLabel); } else // IsNotoneFamily { BeqFar(atomicLoopDoneLabel); } } // i++; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); // if (i >= maxIterations) goto atomicLoopDoneLabel; MarkLabel(conditionLabel); if (maxIterations != int.MaxValue) { Ldloc(iterationLocal); Ldc(maxIterations); BltFar(bodyLabel); } else { BrFar(bodyLabel); } } // Done: MarkLabel(atomicLoopDoneLabel); // Check to ensure we've found at least min iterations. if (minIterations > 0) { Ldloc(iterationLocal); Ldc(minIterations); BltFar(doneLabel); } // Now that we've completed our optional iterations, advance the text span // and pos by the number of iterations completed. if (!rtl) { // slice = slice.Slice(i); Ldloca(slice); Ldloc(iterationLocal); Call(s_spanSliceIntMethod); Stloc(slice); // pos += i; Ldloc(pos); Ldloc(iterationLocal); Add(); Stloc(pos); } else { // pos -= i; Ldloc(pos); Ldloc(iterationLocal); Sub(); Stloc(pos); } } // Emits the code to handle a non-backtracking optional zero-or-one loop. void EmitAtomicSingleCharZeroOrOne(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M == 0 && node.N == 1); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; if (rtl) { TransferSliceStaticPosToPos(); // we don't use static pos for rtl } Label skipUpdatesLabel = DefineLabel(); if (!rtl) { // if ((uint)sliceStaticPos >= (uint)slice.Length) goto skipUpdatesLabel; Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(skipUpdatesLabel); } else { // if (pos == 0) goto skipUpdatesLabel; Ldloc(pos); Ldc(0); BeqFar(skipUpdatesLabel); } if (!rtl) { // if (slice[sliceStaticPos] != ch) goto skipUpdatesLabel; Ldloca(slice); Ldc(sliceStaticPos); } else { // if (inputSpan[pos - 1] != ch) goto skipUpdatesLabel; Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); } Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(skipUpdatesLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(skipUpdatesLabel); } else // IsNotoneFamily { BeqFar(skipUpdatesLabel); } } if (!rtl) { // slice = slice.Slice(1); Ldloca(slice); Ldc(1); Call(s_spanSliceIntMethod); Stloc(slice); // pos++; Ldloc(pos); Ldc(1); Add(); Stloc(pos); } else { // pos--; Ldloc(pos); Ldc(1); Sub(); Stloc(pos); } MarkLabel(skipUpdatesLabel); } void EmitNonBacktrackingRepeater(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.M == node.N, $"Unexpected M={node.M} == N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(!analysis.MayBacktrack(node.Child(0)), $"Expected non-backtracking node {node.Kind}"); // Ensure every iteration of the loop sees a consistent value. TransferSliceStaticPosToPos(); // Loop M==N times to match the child exactly that numbers of times. Label condition = DefineLabel(); Label body = DefineLabel(); // for (int i = 0; ...) using RentedLocalBuilder i = RentInt32Local(); Ldc(0); Stloc(i); BrFar(condition); MarkLabel(body); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // make sure static the static position remains at 0 for subsequent constructs // for (...; ...; i++) Ldloc(i); Ldc(1); Add(); Stloc(i); // for (...; i < node.M; ...) MarkLabel(condition); Ldloc(i); Ldc(node.M); BltFar(body); } void EmitLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); Label originalDoneLabel = doneLabel; LocalBuilder startingPos = DeclareInt32(); LocalBuilder iterationCount = DeclareInt32(); Label body = DefineLabel(); Label endLoop = DefineLabel(); // iterationCount = 0; // startingPos = 0; Ldc(0); Stloc(iterationCount); Ldc(0); Stloc(startingPos); // Iteration body MarkLabel(body); EmitTimeoutCheck(); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackResizeIfNeeded(3); if (expressionHasCaptures) { // base.runstack[stackpos++] = base.Crawlpos(); EmitStackPush(() => { Ldthis(); Call(s_crawlposMethod); }); } EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(pos)); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. // iterationCount++; Ldloc(iterationCount); Ldc(1); Add(); Stloc(iterationCount); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. Label iterationFailedLabel = DefineLabel(); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 bool childBacktracks = doneLabel != iterationFailedLabel; // Loop condition. Continue iterating greedily if we've not yet reached the maximum. We also need to stop // iterating if the iteration matched empty and we already hit the minimum number of iterations. Otherwise, // we've matched as many iterations as we can with this configuration. Jump to what comes after the loop. switch ((minIterations > 0, maxIterations == int.MaxValue)) { case (true, true): // if (pos != startingPos || iterationCount < minIterations) goto body; // goto endLoop; Ldloc(pos); Ldloc(startingPos); BneFar(body); Ldloc(iterationCount); Ldc(minIterations); BltFar(body); BrFar(endLoop); break; case (true, false): // if ((pos != startingPos || iterationCount < minIterations) && iterationCount < maxIterations) goto body; // goto endLoop; Ldloc(iterationCount); Ldc(maxIterations); BgeFar(endLoop); Ldloc(pos); Ldloc(startingPos); BneFar(body); Ldloc(iterationCount); Ldc(minIterations); BltFar(body); BrFar(endLoop); break; case (false, true): // if (pos != startingPos) goto body; // goto endLoop; Ldloc(pos); Ldloc(startingPos); BneFar(body); BrFar(endLoop); break; case (false, false): // if (pos == startingPos || iterationCount >= maxIterations) goto endLoop; // goto body; Ldloc(pos); Ldloc(startingPos); BeqFar(endLoop); Ldloc(iterationCount); Ldc(maxIterations); BgeFar(endLoop); BrFar(body); break; } // Now handle what happens when an iteration fails, which could be an initial failure or it // could be while backtracking. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel); // iterationCount--; Ldloc(iterationCount); Ldc(1); Sub(); Stloc(iterationCount); // if (iterationCount < 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BltFar(originalDoneLabel); // pos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(pos); EmitStackPop(); Stloc(startingPos); if (expressionHasCaptures) { // int poppedCrawlPos = base.runstack[--stackpos]; // while (base.Crawlpos() > poppedCrawlPos) base.Uncapture(); using RentedLocalBuilder poppedCrawlPos = RentInt32Local(); EmitStackPop(); Stloc(poppedCrawlPos); EmitUncaptureUntil(poppedCrawlPos); } SliceInputSpan(); if (minIterations > 0) { // if (iterationCount == 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); // if (iterationCount < minIterations) goto doneLabel/originalDoneLabel; Ldloc(iterationCount); Ldc(minIterations); BltFar(childBacktracks ? doneLabel : originalDoneLabel); } if (isAtomic) { doneLabel = originalDoneLabel; MarkLabel(endLoop); } else { if (childBacktracks) { // goto endLoop; BrFar(endLoop); // Backtrack: Label backtrack = DefineLabel(); MarkLabel(backtrack); // if (iterationCount == 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; } MarkLabel(endLoop); if (node.IsInLoop()) { // Store the loop's state EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(iterationCount)); // Skip past the backtracking section // goto backtrackingEnd; Label backtrackingEnd = DefineLabel(); BrFar(backtrackingEnd); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // iterationCount = base.runstack[--runstack]; // startingPos = base.runstack[--runstack]; EmitStackPop(); Stloc(iterationCount); EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } } void EmitStackResizeIfNeeded(int count) { Debug.Assert(count >= 1); // if (stackpos >= base.runstack!.Length - (count - 1)) // { // Array.Resize(ref base.runstack, base.runstack.Length * 2); // } Label skipResize = DefineLabel(); Ldloc(stackpos); Ldthisfld(s_runstackField); Ldlen(); if (count > 1) { Ldc(count - 1); Sub(); } Blt(skipResize); Ldthis(); _ilg!.Emit(OpCodes.Ldflda, s_runstackField); Ldthisfld(s_runstackField); Ldlen(); Ldc(2); Mul(); Call(s_arrayResize); MarkLabel(skipResize); } void EmitStackPush(Action load) { // base.runstack[stackpos] = load(); Ldthisfld(s_runstackField); Ldloc(stackpos); load(); StelemI4(); // stackpos++; Ldloc(stackpos); Ldc(1); Add(); Stloc(stackpos); } void EmitStackPop() { // ... = base.runstack[--stackpos]; Ldthisfld(s_runstackField); Ldloc(stackpos); Ldc(1); Sub(); Stloc(stackpos); Ldloc(stackpos); LdelemI4(); } } protected void EmitScan(RegexOptions options, DynamicMethod tryFindNextStartingPositionMethod, DynamicMethod tryMatchAtCurrentPositionMethod) { bool rtl = (options & RegexOptions.RightToLeft) != 0; Label returnLabel = DefineLabel(); // while (TryFindNextPossibleStartingPosition(text)) Label whileLoopBody = DefineLabel(); MarkLabel(whileLoopBody); Ldthis(); Ldarg_1(); Call(tryFindNextStartingPositionMethod); BrfalseFar(returnLabel); if (_hasTimeout) { // CheckTimeout(); Ldthis(); Call(s_checkTimeoutMethod); } // if (TryMatchAtCurrentPosition(text) || runtextpos == text.length) // or == 0 for rtl // return; Ldthis(); Ldarg_1(); Call(tryMatchAtCurrentPositionMethod); BrtrueFar(returnLabel); Ldthisfld(s_runtextposField); if (!rtl) { Ldarga_s(1); Call(s_spanGetLengthMethod); } else { Ldc(0); } Ceq(); BrtrueFar(returnLabel); // runtextpos += 1 // or -1 for rtl Ldthis(); Ldthisfld(s_runtextposField); Ldc(!rtl ? 1 : -1); Add(); Stfld(s_runtextposField); // End loop body. BrFar(whileLoopBody); // return; MarkLabel(returnLabel); Ret(); } private void InitializeCultureForTryMatchAtCurrentPositionIfNecessary(AnalysisResults analysis) { _textInfo = null; if (analysis.HasIgnoreCase && (_options & RegexOptions.CultureInvariant) == 0) { // cache CultureInfo in local variable which saves excessive thread local storage accesses _textInfo = DeclareTextInfo(); InitLocalCultureInfo(); } } /// <summary>Emits a a check for whether the character is in the specified character class.</summary> /// <remarks>The character to be checked has already been loaded onto the stack.</remarks> private void EmitMatchCharacterClass(string charClass, bool caseInsensitive) { // We need to perform the equivalent of calling RegexRunner.CharInClass(ch, charClass), // but that call is relatively expensive. Before we fall back to it, we try to optimize // some common cases for which we can do much better, such as known character classes // for which we can call a dedicated method, or a fast-path for ASCII using a lookup table. // First, see if the char class is a built-in one for which there's a better function // we can just call directly. Everything in this section must work correctly for both // case-sensitive and case-insensitive modes, regardless of culture. switch (charClass) { case RegexCharClass.AnyClass: // true Pop(); Ldc(1); return; case RegexCharClass.DigitClass: // char.IsDigit(ch) Call(s_charIsDigitMethod); return; case RegexCharClass.NotDigitClass: // !char.IsDigit(ch) Call(s_charIsDigitMethod); Ldc(0); Ceq(); return; case RegexCharClass.SpaceClass: // char.IsWhiteSpace(ch) Call(s_charIsWhiteSpaceMethod); return; case RegexCharClass.NotSpaceClass: // !char.IsWhiteSpace(ch) Call(s_charIsWhiteSpaceMethod); Ldc(0); Ceq(); return; case RegexCharClass.WordClass: // RegexRunner.IsWordChar(ch) Call(s_isWordCharMethod); return; case RegexCharClass.NotWordClass: // !RegexRunner.IsWordChar(ch) Call(s_isWordCharMethod); Ldc(0); Ceq(); return; } // If we're meant to be doing a case-insensitive lookup, and if we're not using the invariant culture, // lowercase the input. If we're using the invariant culture, we may still end up calling ToLower later // on, but we may also be able to avoid it, in particular in the case of our lookup table, where we can // generate the lookup table already factoring in the invariant case sensitivity. There are multiple // special-code paths between here and the lookup table, but we only take those if invariant is false; // if it were true, they'd need to use CallToLower(). bool invariant = false; if (caseInsensitive) { invariant = UseToLowerInvariant; if (!invariant) { CallToLower(); } } // Next, handle simple sets of one range, e.g. [A-Z], [0-9], etc. This includes some built-in classes, like ECMADigitClass. if (!invariant && RegexCharClass.TryGetSingleRange(charClass, out char lowInclusive, out char highInclusive)) { if (lowInclusive == highInclusive) { // ch == charClass[3] Ldc(lowInclusive); Ceq(); } else { // (uint)ch - lowInclusive < highInclusive - lowInclusive + 1 Ldc(lowInclusive); Sub(); Ldc(highInclusive - lowInclusive + 1); CltUn(); } // Negate the answer if the negation flag was set if (RegexCharClass.IsNegated(charClass)) { Ldc(0); Ceq(); } return; } // Next if the character class contains nothing but a single Unicode category, we can calle char.GetUnicodeCategory and // compare against it. It has a fast-lookup path for ASCII, so is as good or better than any lookup we'd generate (plus // we get smaller code), and it's what we'd do for the fallback (which we get to avoid generating) as part of CharInClass. if (!invariant && RegexCharClass.TryGetSingleUnicodeCategory(charClass, out UnicodeCategory category, out bool negated)) { // char.GetUnicodeCategory(ch) == category Call(s_charGetUnicodeInfo); Ldc((int)category); Ceq(); if (negated) { Ldc(0); Ceq(); } return; } // All checks after this point require reading the input character multiple times, // so we store it into a temporary local. using RentedLocalBuilder tempLocal = RentInt32Local(); Stloc(tempLocal); // Next, if there's only 2 or 3 chars in the set (fairly common due to the sets we create for prefixes), // it's cheaper and smaller to compare against each than it is to use a lookup table. if (!invariant && !RegexCharClass.IsNegated(charClass)) { Span<char> setChars = stackalloc char[3]; int numChars = RegexCharClass.GetSetChars(charClass, setChars); if (numChars is 2 or 3) { if (RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out int mask)) // special-case common case of an upper and lowercase ASCII letter combination { // ((ch | mask) == setChars[1]) Ldloc(tempLocal); Ldc(mask); Or(); Ldc(setChars[1] | mask); Ceq(); } else { // (ch == setChars[0]) | (ch == setChars[1]) Ldloc(tempLocal); Ldc(setChars[0]); Ceq(); Ldloc(tempLocal); Ldc(setChars[1]); Ceq(); Or(); } // | (ch == setChars[2]) if (numChars == 3) { Ldloc(tempLocal); Ldc(setChars[2]); Ceq(); Or(); } return; } } using RentedLocalBuilder resultLocal = RentInt32Local(); // Analyze the character set more to determine what code to generate. RegexCharClass.CharClassAnalysisResults analysis = RegexCharClass.Analyze(charClass); // Helper method that emits a call to RegexRunner.CharInClass(ch{.ToLowerInvariant()}, charClass) void EmitCharInClass() { Ldloc(tempLocal); if (invariant) { CallToLower(); } Ldstr(charClass); Call(s_charInClassMethod); Stloc(resultLocal); } Label doneLabel = DefineLabel(); Label comparisonLabel = DefineLabel(); if (!invariant) // if we're being asked to do a case insensitive, invariant comparison, use the lookup table { if (analysis.ContainsNoAscii) { // We determined that the character class contains only non-ASCII, // for example if the class were [\p{IsGreek}\p{IsGreekExtended}], which is // the same as [\u0370-\u03FF\u1F00-1FFF]. (In the future, we could possibly // extend the analysis to produce a known lower-bound and compare against // that rather than always using 128 as the pivot point.) // ch >= 128 && RegexRunner.CharInClass(ch, "...") Ldloc(tempLocal); Ldc(128); Blt(comparisonLabel); EmitCharInClass(); Br(doneLabel); MarkLabel(comparisonLabel); Ldc(0); Stloc(resultLocal); MarkLabel(doneLabel); Ldloc(resultLocal); return; } if (analysis.AllAsciiContained) { // We determined that every ASCII character is in the class, for example // if the class were the negated example from case 1 above: // [^\p{IsGreek}\p{IsGreekExtended}]. // ch < 128 || RegexRunner.CharInClass(ch, "...") Ldloc(tempLocal); Ldc(128); Blt(comparisonLabel); EmitCharInClass(); Br(doneLabel); MarkLabel(comparisonLabel); Ldc(1); Stloc(resultLocal); MarkLabel(doneLabel); Ldloc(resultLocal); return; } } // Now, our big hammer is to generate a lookup table that lets us quickly index by character into a yes/no // answer as to whether the character is in the target character class. However, we don't want to store // a lookup table for every possible character for every character class in the regular expression; at one // bit for each of 65K characters, that would be an 8K bitmap per character class. Instead, we handle the // common case of ASCII input via such a lookup table, which at one bit for each of 128 characters is only // 16 bytes per character class. We of course still need to be able to handle inputs that aren't ASCII, so // we check the input against 128, and have a fallback if the input is >= to it. Determining the right // fallback could itself be expensive. For example, if it's possible that a value >= 128 could match the // character class, we output a call to RegexRunner.CharInClass, but we don't want to have to enumerate the // entire character class evaluating every character against it, just to determine whether it's a match. // Instead, we employ some quick heuristics that will always ensure we provide a correct answer even if // we could have sometimes generated better code to give that answer. // Generate the lookup table to store 128 answers as bits. We use a const string instead of a byte[] / static // data property because it lets IL emit handle all the details for us. string bitVectorString = string.Create(8, (charClass, invariant), static (dest, state) => // String length is 8 chars == 16 bytes == 128 bits. { for (int i = 0; i < 128; i++) { char c = (char)i; bool isSet = state.invariant ? RegexCharClass.CharInClass(char.ToLowerInvariant(c), state.charClass) : RegexCharClass.CharInClass(c, state.charClass); if (isSet) { dest[i >> 4] |= (char)(1 << (i & 0xF)); } } }); // We determined that the character class may contain ASCII, so we // output the lookup against the lookup table. // ch < 128 ? (bitVectorString[ch >> 4] & (1 << (ch & 0xF))) != 0 : Ldloc(tempLocal); Ldc(128); Bge(comparisonLabel); Ldstr(bitVectorString); Ldloc(tempLocal); Ldc(4); Shr(); Call(s_stringGetCharsMethod); Ldc(1); Ldloc(tempLocal); Ldc(15); And(); Ldc(31); And(); Shl(); And(); Ldc(0); CgtUn(); Stloc(resultLocal); Br(doneLabel); MarkLabel(comparisonLabel); if (analysis.ContainsOnlyAscii) { // We know that all inputs that could match are ASCII, for example if the // character class were [A-Za-z0-9], so since the ch is now known to be >= 128, we // can just fail the comparison. Ldc(0); Stloc(resultLocal); } else if (analysis.AllNonAsciiContained) { // We know that all non-ASCII inputs match, for example if the character // class were [^\r\n], so since we just determined the ch to be >= 128, we can just // give back success. Ldc(1); Stloc(resultLocal); } else { // We know that the whole class wasn't ASCII, and we don't know anything about the non-ASCII // characters other than that some might be included, for example if the character class // were [\w\d], so since ch >= 128, we need to fall back to calling CharInClass. EmitCharInClass(); } MarkLabel(doneLabel); Ldloc(resultLocal); } /// <summary>Emits a timeout check.</summary> private void EmitTimeoutCheck() { if (!_hasTimeout) { return; } Debug.Assert(_loopTimeoutCounter != null); // Increment counter for each loop iteration. Ldloc(_loopTimeoutCounter); Ldc(1); Add(); Stloc(_loopTimeoutCounter); // Emit code to check the timeout every 2048th iteration. Label label = DefineLabel(); Ldloc(_loopTimeoutCounter); Ldc(LoopTimeoutCheckCount); RemUn(); Brtrue(label); Ldthis(); Call(s_checkTimeoutMethod); MarkLabel(label); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices; using System.Threading; namespace System.Text.RegularExpressions { /// <summary> /// RegexCompiler translates a block of RegexCode to MSIL, and creates a subclass of the RegexRunner type. /// </summary> internal abstract class RegexCompiler { private static readonly FieldInfo s_runtextstartField = RegexRunnerField("runtextstart"); private static readonly FieldInfo s_runtextposField = RegexRunnerField("runtextpos"); private static readonly FieldInfo s_runstackField = RegexRunnerField("runstack"); private static readonly MethodInfo s_captureMethod = RegexRunnerMethod("Capture"); private static readonly MethodInfo s_transferCaptureMethod = RegexRunnerMethod("TransferCapture"); private static readonly MethodInfo s_uncaptureMethod = RegexRunnerMethod("Uncapture"); private static readonly MethodInfo s_isMatchedMethod = RegexRunnerMethod("IsMatched"); private static readonly MethodInfo s_matchLengthMethod = RegexRunnerMethod("MatchLength"); private static readonly MethodInfo s_matchIndexMethod = RegexRunnerMethod("MatchIndex"); private static readonly MethodInfo s_isBoundaryMethod = typeof(RegexRunner).GetMethod("IsBoundary", BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(ReadOnlySpan<char>), typeof(int) })!; private static readonly MethodInfo s_isWordCharMethod = RegexRunnerMethod("IsWordChar"); private static readonly MethodInfo s_isECMABoundaryMethod = typeof(RegexRunner).GetMethod("IsECMABoundary", BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(ReadOnlySpan<char>), typeof(int) })!; private static readonly MethodInfo s_crawlposMethod = RegexRunnerMethod("Crawlpos"); private static readonly MethodInfo s_charInClassMethod = RegexRunnerMethod("CharInClass"); private static readonly MethodInfo s_checkTimeoutMethod = RegexRunnerMethod("CheckTimeout"); private static readonly MethodInfo s_charIsDigitMethod = typeof(char).GetMethod("IsDigit", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charIsWhiteSpaceMethod = typeof(char).GetMethod("IsWhiteSpace", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charGetUnicodeInfo = typeof(char).GetMethod("GetUnicodeCategory", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charToLowerInvariantMethod = typeof(char).GetMethod("ToLowerInvariant", new Type[] { typeof(char) })!; private static readonly MethodInfo s_cultureInfoGetCurrentCultureMethod = typeof(CultureInfo).GetMethod("get_CurrentCulture")!; private static readonly MethodInfo s_cultureInfoGetTextInfoMethod = typeof(CultureInfo).GetMethod("get_TextInfo")!; private static readonly MethodInfo s_spanGetItemMethod = typeof(ReadOnlySpan<char>).GetMethod("get_Item", new Type[] { typeof(int) })!; private static readonly MethodInfo s_spanGetLengthMethod = typeof(ReadOnlySpan<char>).GetMethod("get_Length")!; private static readonly MethodInfo s_memoryMarshalGetReference = typeof(MemoryMarshal).GetMethod("GetReference", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfChar = typeof(MemoryExtensions).GetMethod("IndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfSpan = typeof(MemoryExtensions).GetMethod("IndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnyCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnyCharCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnySpan = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfChar = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnyCharChar = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnyCharCharChar = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnySpan = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfSpan = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanSliceIntMethod = typeof(ReadOnlySpan<char>).GetMethod("Slice", new Type[] { typeof(int) })!; private static readonly MethodInfo s_spanSliceIntIntMethod = typeof(ReadOnlySpan<char>).GetMethod("Slice", new Type[] { typeof(int), typeof(int) })!; private static readonly MethodInfo s_spanStartsWithSpan = typeof(MemoryExtensions).GetMethod("StartsWith", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanStartsWithSpanComparison = typeof(MemoryExtensions).GetMethod("StartsWith", new Type[] { typeof(ReadOnlySpan<char>), typeof(ReadOnlySpan<char>), typeof(StringComparison) })!; private static readonly MethodInfo s_stringAsSpanMethod = typeof(MemoryExtensions).GetMethod("AsSpan", new Type[] { typeof(string) })!; private static readonly MethodInfo s_stringGetCharsMethod = typeof(string).GetMethod("get_Chars", new Type[] { typeof(int) })!; private static readonly MethodInfo s_textInfoToLowerMethod = typeof(TextInfo).GetMethod("ToLower", new Type[] { typeof(char) })!; private static readonly MethodInfo s_arrayResize = typeof(Array).GetMethod("Resize")!.MakeGenericMethod(typeof(int)); private static readonly MethodInfo s_mathMinIntInt = typeof(Math).GetMethod("Min", new Type[] { typeof(int), typeof(int) })!; /// <summary>The ILGenerator currently in use.</summary> protected ILGenerator? _ilg; /// <summary>The options for the expression.</summary> protected RegexOptions _options; /// <summary>The <see cref="RegexTree"/> written for the expression.</summary> protected RegexTree? _regexTree; /// <summary>Whether this expression has a non-infinite timeout.</summary> protected bool _hasTimeout; /// <summary>Pool of Int32 LocalBuilders.</summary> private Stack<LocalBuilder>? _int32LocalsPool; /// <summary>Pool of ReadOnlySpan of char locals.</summary> private Stack<LocalBuilder>? _readOnlySpanCharLocalsPool; /// <summary>Local representing a cached TextInfo for the culture to use for all case-insensitive operations.</summary> private LocalBuilder? _textInfo; /// <summary>Local representing a timeout counter for loops (set loops and node loops).</summary> private LocalBuilder? _loopTimeoutCounter; /// <summary>A frequency with which the timeout should be validated.</summary> private const int LoopTimeoutCheckCount = 2048; private static FieldInfo RegexRunnerField(string fieldname) => typeof(RegexRunner).GetField(fieldname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)!; private static MethodInfo RegexRunnerMethod(string methname) => typeof(RegexRunner).GetMethod(methname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)!; /// <summary> /// Entry point to dynamically compile a regular expression. The expression is compiled to /// an in-memory assembly. /// </summary> internal static RegexRunnerFactory? Compile(string pattern, RegexTree regexTree, RegexOptions options, bool hasTimeout) => new RegexLWCGCompiler().FactoryInstanceFromCode(pattern, regexTree, options, hasTimeout); /// <summary>A macro for _ilg.DefineLabel</summary> private Label DefineLabel() => _ilg!.DefineLabel(); /// <summary>A macro for _ilg.MarkLabel</summary> private void MarkLabel(Label l) => _ilg!.MarkLabel(l); /// <summary>A macro for _ilg.Emit(Opcodes.Ldstr, str)</summary> protected void Ldstr(string str) => _ilg!.Emit(OpCodes.Ldstr, str); /// <summary>A macro for the various forms of Ldc.</summary> protected void Ldc(int i) => _ilg!.Emit(OpCodes.Ldc_I4, i); /// <summary>A macro for _ilg.Emit(OpCodes.Ldc_I8).</summary> protected void LdcI8(long i) => _ilg!.Emit(OpCodes.Ldc_I8, i); /// <summary>A macro for _ilg.Emit(OpCodes.Ret).</summary> protected void Ret() => _ilg!.Emit(OpCodes.Ret); /// <summary>A macro for _ilg.Emit(OpCodes.Dup).</summary> protected void Dup() => _ilg!.Emit(OpCodes.Dup); /// <summary>A macro for _ilg.Emit(OpCodes.Rem_Un).</summary> private void RemUn() => _ilg!.Emit(OpCodes.Rem_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Ceq).</summary> private void Ceq() => _ilg!.Emit(OpCodes.Ceq); /// <summary>A macro for _ilg.Emit(OpCodes.Cgt_Un).</summary> private void CgtUn() => _ilg!.Emit(OpCodes.Cgt_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Clt_Un).</summary> private void CltUn() => _ilg!.Emit(OpCodes.Clt_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Pop).</summary> private void Pop() => _ilg!.Emit(OpCodes.Pop); /// <summary>A macro for _ilg.Emit(OpCodes.Add).</summary> private void Add() => _ilg!.Emit(OpCodes.Add); /// <summary>A macro for _ilg.Emit(OpCodes.Sub).</summary> private void Sub() => _ilg!.Emit(OpCodes.Sub); /// <summary>A macro for _ilg.Emit(OpCodes.Mul).</summary> private void Mul() => _ilg!.Emit(OpCodes.Mul); /// <summary>A macro for _ilg.Emit(OpCodes.And).</summary> private void And() => _ilg!.Emit(OpCodes.And); /// <summary>A macro for _ilg.Emit(OpCodes.Or).</summary> private void Or() => _ilg!.Emit(OpCodes.Or); /// <summary>A macro for _ilg.Emit(OpCodes.Shl).</summary> private void Shl() => _ilg!.Emit(OpCodes.Shl); /// <summary>A macro for _ilg.Emit(OpCodes.Shr).</summary> private void Shr() => _ilg!.Emit(OpCodes.Shr); /// <summary>A macro for _ilg.Emit(OpCodes.Ldloc).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Ldloc(LocalBuilder lt) => _ilg!.Emit(OpCodes.Ldloc, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldloca).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Ldloca(LocalBuilder lt) => _ilg!.Emit(OpCodes.Ldloca, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_U2).</summary> private void LdindU2() => _ilg!.Emit(OpCodes.Ldind_U2); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_I4).</summary> private void LdindI4() => _ilg!.Emit(OpCodes.Ldind_I4); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_I8).</summary> private void LdindI8() => _ilg!.Emit(OpCodes.Ldind_I8); /// <summary>A macro for _ilg.Emit(OpCodes.Unaligned).</summary> private void Unaligned(byte alignment) => _ilg!.Emit(OpCodes.Unaligned, alignment); /// <summary>A macro for _ilg.Emit(OpCodes.Stloc).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Stloc(LocalBuilder lt) => _ilg!.Emit(OpCodes.Stloc, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldarg_0).</summary> protected void Ldthis() => _ilg!.Emit(OpCodes.Ldarg_0); /// <summary>A macro for _ilgEmit(OpCodes.Ldarg_1) </summary> private void Ldarg_1() => _ilg!.Emit(OpCodes.Ldarg_1); /// <summary>A macro for Ldthis(); Ldfld();</summary> protected void Ldthisfld(FieldInfo ft) { Ldthis(); _ilg!.Emit(OpCodes.Ldfld, ft); } /// <summary>Fetches the address of argument in passed in <paramref name="position"/></summary> /// <param name="position">The position of the argument which address needs to be fetched.</param> private void Ldarga_s(int position) => _ilg!.Emit(OpCodes.Ldarga_S, position); /// <summary>A macro for Ldthis(); Ldfld(); Stloc();</summary> private void Mvfldloc(FieldInfo ft, LocalBuilder lt) { Ldthisfld(ft); Stloc(lt); } /// <summary>A macro for _ilg.Emit(OpCodes.Stfld).</summary> protected void Stfld(FieldInfo ft) => _ilg!.Emit(OpCodes.Stfld, ft); /// <summary>A macro for _ilg.Emit(OpCodes.Callvirt, mt).</summary> protected void Callvirt(MethodInfo mt) => _ilg!.Emit(OpCodes.Callvirt, mt); /// <summary>A macro for _ilg.Emit(OpCodes.Call, mt).</summary> protected void Call(MethodInfo mt) => _ilg!.Emit(OpCodes.Call, mt); /// <summary>A macro for _ilg.Emit(OpCodes.Brfalse) (short jump).</summary> private void Brfalse(Label l) => _ilg!.Emit(OpCodes.Brfalse_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brfalse) (long form).</summary> private void BrfalseFar(Label l) => _ilg!.Emit(OpCodes.Brfalse, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brtrue) (long form).</summary> private void BrtrueFar(Label l) => _ilg!.Emit(OpCodes.Brtrue, l); /// <summary>A macro for _ilg.Emit(OpCodes.Br) (long form).</summary> private void BrFar(Label l) => _ilg!.Emit(OpCodes.Br, l); /// <summary>A macro for _ilg.Emit(OpCodes.Ble) (long form).</summary> private void BleFar(Label l) => _ilg!.Emit(OpCodes.Ble, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt) (long form).</summary> private void BltFar(Label l) => _ilg!.Emit(OpCodes.Blt, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt_Un) (long form).</summary> private void BltUnFar(Label l) => _ilg!.Emit(OpCodes.Blt_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge) (long form).</summary> private void BgeFar(Label l) => _ilg!.Emit(OpCodes.Bge, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_Un) (long form).</summary> private void BgeUnFar(Label l) => _ilg!.Emit(OpCodes.Bge_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bne) (long form).</summary> private void BneFar(Label l) => _ilg!.Emit(OpCodes.Bne_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Beq) (long form).</summary> private void BeqFar(Label l) => _ilg!.Emit(OpCodes.Beq, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brtrue_S) (short jump).</summary> private void Brtrue(Label l) => _ilg!.Emit(OpCodes.Brtrue_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Br_S) (short jump).</summary> private void Br(Label l) => _ilg!.Emit(OpCodes.Br_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Ble_S) (short jump).</summary> private void Ble(Label l) => _ilg!.Emit(OpCodes.Ble_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt_S) (short jump).</summary> private void Blt(Label l) => _ilg!.Emit(OpCodes.Blt_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_S) (short jump).</summary> private void Bge(Label l) => _ilg!.Emit(OpCodes.Bge_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_Un_S) (short jump).</summary> private void BgeUn(Label l) => _ilg!.Emit(OpCodes.Bge_Un_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bgt_S) (short jump).</summary> private void Bgt(Label l) => _ilg!.Emit(OpCodes.Bgt_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bne_S) (short jump).</summary> private void Bne(Label l) => _ilg!.Emit(OpCodes.Bne_Un_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Beq_S) (short jump).</summary> private void Beq(Label l) => _ilg!.Emit(OpCodes.Beq_S, l); /// <summary>A macro for the Ldlen instruction.</summary> private void Ldlen() => _ilg!.Emit(OpCodes.Ldlen); /// <summary>A macro for the Ldelem_I4 instruction.</summary> private void LdelemI4() => _ilg!.Emit(OpCodes.Ldelem_I4); /// <summary>A macro for the Stelem_I4 instruction.</summary> private void StelemI4() => _ilg!.Emit(OpCodes.Stelem_I4); private void Switch(Label[] table) => _ilg!.Emit(OpCodes.Switch, table); /// <summary>Declares a local bool.</summary> private LocalBuilder DeclareBool() => _ilg!.DeclareLocal(typeof(bool)); /// <summary>Declares a local int.</summary> private LocalBuilder DeclareInt32() => _ilg!.DeclareLocal(typeof(int)); /// <summary>Declares a local CultureInfo.</summary> private LocalBuilder? DeclareTextInfo() => _ilg!.DeclareLocal(typeof(TextInfo)); /// <summary>Declares a local string.</summary> private LocalBuilder DeclareString() => _ilg!.DeclareLocal(typeof(string)); private LocalBuilder DeclareReadOnlySpanChar() => _ilg!.DeclareLocal(typeof(ReadOnlySpan<char>)); /// <summary>Rents an Int32 local variable slot from the pool of locals.</summary> /// <remarks> /// Care must be taken to Dispose of the returned <see cref="RentedLocalBuilder"/> when it's no longer needed, /// and also not to jump into the middle of a block involving a rented local from outside of that block. /// </remarks> private RentedLocalBuilder RentInt32Local() => new RentedLocalBuilder( _int32LocalsPool ??= new Stack<LocalBuilder>(), _int32LocalsPool.TryPop(out LocalBuilder? iterationLocal) ? iterationLocal : DeclareInt32()); /// <summary>Rents a ReadOnlySpan(char) local variable slot from the pool of locals.</summary> /// <remarks> /// Care must be taken to Dispose of the returned <see cref="RentedLocalBuilder"/> when it's no longer needed, /// and also not to jump into the middle of a block involving a rented local from outside of that block. /// </remarks> private RentedLocalBuilder RentReadOnlySpanCharLocal() => new RentedLocalBuilder( _readOnlySpanCharLocalsPool ??= new Stack<LocalBuilder>(1), // capacity == 1 as we currently don't expect overlapping instances _readOnlySpanCharLocalsPool.TryPop(out LocalBuilder? iterationLocal) ? iterationLocal : DeclareReadOnlySpanChar()); /// <summary>Returned a rented local to the pool.</summary> private struct RentedLocalBuilder : IDisposable { private readonly Stack<LocalBuilder> _pool; private readonly LocalBuilder _local; internal RentedLocalBuilder(Stack<LocalBuilder> pool, LocalBuilder local) { _local = local; _pool = pool; } public static implicit operator LocalBuilder(RentedLocalBuilder local) => local._local; public void Dispose() { Debug.Assert(_pool != null); Debug.Assert(_local != null); Debug.Assert(!_pool.Contains(_local)); _pool.Push(_local); this = default; } } /// <summary>Sets the culture local to CultureInfo.CurrentCulture.</summary> private void InitLocalCultureInfo() { Debug.Assert(_textInfo != null); Call(s_cultureInfoGetCurrentCultureMethod); Callvirt(s_cultureInfoGetTextInfoMethod); Stloc(_textInfo); } /// <summary>Whether ToLower operations should be performed with the invariant culture as opposed to the one in <see cref="_textInfo"/>.</summary> private bool UseToLowerInvariant => _textInfo == null || (_options & RegexOptions.CultureInvariant) != 0; /// <summary>Invokes either char.ToLowerInvariant(c) or _textInfo.ToLower(c).</summary> private void CallToLower() { if (UseToLowerInvariant) { Call(s_charToLowerInvariantMethod); } else { using RentedLocalBuilder currentCharLocal = RentInt32Local(); Stloc(currentCharLocal); Ldloc(_textInfo!); Ldloc(currentCharLocal); Callvirt(s_textInfoToLowerMethod); } } /// <summary>Generates the implementation for TryFindNextPossibleStartingPosition.</summary> protected void EmitTryFindNextPossibleStartingPosition() { Debug.Assert(_regexTree != null); _int32LocalsPool?.Clear(); _readOnlySpanCharLocalsPool?.Clear(); LocalBuilder inputSpan = DeclareReadOnlySpanChar(); LocalBuilder pos = DeclareInt32(); bool rtl = (_options & RegexOptions.RightToLeft) != 0; _textInfo = null; if ((_options & RegexOptions.CultureInvariant) == 0) { bool needsCulture = _regexTree.FindOptimizations.FindMode switch { FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive => true, _ when _regexTree.FindOptimizations.FixedDistanceSets is List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets => sets.Exists(set => set.CaseInsensitive), _ => false, }; if (needsCulture) { _textInfo = DeclareTextInfo(); InitLocalCultureInfo(); } } // Load necessary locals // int pos = base.runtextpos; // ReadOnlySpan<char> inputSpan = dynamicMethodArg; // TODO: We can reference the arg directly rather than using another local. Mvfldloc(s_runtextposField, pos); Ldarg_1(); Stloc(inputSpan); // Generate length check. If the input isn't long enough to possibly match, fail quickly. // It's rare for min required length to be 0, so we don't bother special-casing the check, // especially since we want the "return false" code regardless. int minRequiredLength = _regexTree.FindOptimizations.MinRequiredLength; Debug.Assert(minRequiredLength >= 0); Label returnFalse = DefineLabel(); Label finishedLengthCheck = DefineLabel(); // if (pos > inputSpan.Length - minRequiredLength) // or pos < minRequiredLength for rtl // { // base.runtextpos = inputSpan.Length; // or 0 for rtl // return false; // } Ldloc(pos); if (!rtl) { Ldloca(inputSpan); Call(s_spanGetLengthMethod); if (minRequiredLength > 0) { Ldc(minRequiredLength); Sub(); } Ble(finishedLengthCheck); } else { Ldc(minRequiredLength); Bge(finishedLengthCheck); } MarkLabel(returnFalse); Ldthis(); if (!rtl) { Ldloca(inputSpan); Call(s_spanGetLengthMethod); } else { Ldc(0); } Stfld(s_runtextposField); Ldc(0); Ret(); MarkLabel(finishedLengthCheck); // Emit any anchors. if (EmitAnchors()) { return; } // Either anchors weren't specified, or they don't completely root all matches to a specific location. switch (_regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_LeftToRight(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_RightToLeft(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: Debug.Assert(_regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_LeftToRight(); break; case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive: Debug.Assert(_regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_RightToLeft(); break; case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: Debug.Assert(_regexTree.FindOptimizations.LiteralAfterLoop is not null); EmitLiteralAfterAtomicLoop(); break; default: Debug.Fail($"Unexpected mode: {_regexTree.FindOptimizations.FindMode}"); goto case FindNextStartingPositionMode.NoSearch; case FindNextStartingPositionMode.NoSearch: // return true; Ldc(1); Ret(); break; } // Emits any anchors. Returns true if the anchor roots any match to a specific location and thus no further // searching is required; otherwise, false. bool EmitAnchors() { Label label; // Anchors that fully implement TryFindNextPossibleStartingPosition, with a check that leads to immediate success or failure determination. switch (_regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: // if (pos != 0) goto returnFalse; // return true; Ldloc(pos); Ldc(0); Bne(returnFalse); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start: // if (pos != base.runtextstart) goto returnFalse; // return true; Ldloc(pos); Ldthisfld(s_runtextstartField); Bne(returnFalse); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: // if (pos < inputSpan.Length - 1) base.runtextpos = inputSpan.Length - 1; // return true; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: // if (pos < inputSpan.Length) base.runtextpos = inputSpan.Length; // return true; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning: // if (pos != 0) base.runtextpos = 0; // return true; label = DefineLabel(); Ldloc(pos); Ldc(0); Beq(label); Ldthis(); Ldc(0); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ: // if (pos < inputSpan.Length - 1 || ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\n') goto returnFalse; // return true; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Blt(returnFalse); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUn(label); Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); Bne(returnFalse); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End: // if (pos < inputSpan.Length) goto returnFalse; // return true; Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Blt(returnFalse); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: // Jump to the end, minus the min required length, which in this case is actually the fixed length. { int extraNewlineBump = _regexTree.FindOptimizations.FindMode == FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ ? 1 : 0; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(_regexTree.FindOptimizations.MinRequiredLength + extraNewlineBump); Sub(); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(_regexTree.FindOptimizations.MinRequiredLength + extraNewlineBump); Sub(); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; } } // Now handle anchors that boost the position but don't determine immediate success or failure. if (!rtl) // we haven't done the work to validate these optimizations for RightToLeft { switch (_regexTree.FindOptimizations.LeadingAnchor) { case RegexNodeKind.Bol: { // Optimize the handling of a Beginning-Of-Line (BOL) anchor. BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any prefix or char class searches. label = DefineLabel(); // if (pos > 0... Ldloc(pos!); Ldc(0); Ble(label); // ... && inputSpan[pos - 1] != '\n') { ... } Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); Beq(label); // int tmp = inputSpan.Slice(pos).IndexOf('\n'); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Ldc('\n'); Call(s_spanIndexOfChar); using (RentedLocalBuilder newlinePos = RentInt32Local()) { Stloc(newlinePos); // if (newlinePos < 0 || newlinePos + pos + 1 > inputSpan.Length) // { // base.runtextpos = inputSpan.Length; // return false; // } Ldloc(newlinePos); Ldc(0); Blt(returnFalse); Ldloc(newlinePos); Ldloc(pos); Add(); Ldc(1); Add(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Bgt(returnFalse); // pos += newlinePos + 1; Ldloc(pos); Ldloc(newlinePos); Add(); Ldc(1); Add(); Stloc(pos); // We've updated the position. Make sure there's still enough room in the input for a possible match. // if (pos > inputSpan.Length - minRequiredLength) returnFalse; Ldloca(inputSpan); Call(s_spanGetLengthMethod); if (minRequiredLength != 0) { Ldc(minRequiredLength); Sub(); } Ldloc(pos); BltFar(returnFalse); } MarkLabel(label); } break; } switch (_regexTree.FindOptimizations.TrailingAnchor) { case RegexNodeKind.End or RegexNodeKind.EndZ when _regexTree.FindOptimizations.MaxPossibleLength is int maxLength: // Jump to the end, minus the max allowed length. { int extraNewlineBump = _regexTree.FindOptimizations.FindMode == FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ ? 1 : 0; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(maxLength + extraNewlineBump); Sub(); Bge(label); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(maxLength + extraNewlineBump); Sub(); Stloc(pos); MarkLabel(label); break; } } } return false; } // Emits a case-sensitive prefix search for a string at the beginning of the pattern. void EmitIndexOf_LeftToRight(string prefix) { using RentedLocalBuilder i = RentInt32Local(); // int i = inputSpan.Slice(pos).IndexOf(prefix); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Ldstr(prefix); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); Stloc(i); // if (i < 0) goto ReturnFalse; Ldloc(i); Ldc(0); BltFar(returnFalse); // base.runtextpos = pos + i; // return true; Ldthis(); Ldloc(pos); Ldloc(i); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } // Emits a case-sensitive right-to-left prefix search for a string at the beginning of the pattern. void EmitIndexOf_RightToLeft(string prefix) { // pos = inputSpan.Slice(0, pos).LastIndexOf(prefix); Ldloca(inputSpan); Ldc(0); Ldloc(pos); Call(s_spanSliceIntIntMethod); Ldstr(prefix); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfSpan); Stloc(pos); // if (pos < 0) goto ReturnFalse; Ldloc(pos); Ldc(0); BltFar(returnFalse); // base.runtextpos = pos + prefix.Length; // return true; Ldthis(); Ldloc(pos); Ldc(prefix.Length); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } // Emits a search for a set at a fixed position from the start of the pattern, // and potentially other sets at other fixed positions in the pattern. void EmitFixedSet_LeftToRight() { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? sets = _regexTree.FindOptimizations.FixedDistanceSets; (char[]? Chars, string Set, int Distance, bool CaseInsensitive) primarySet = sets![0]; const int MaxSets = 4; int setsToUse = Math.Min(sets.Count, MaxSets); using RentedLocalBuilder iLocal = RentInt32Local(); using RentedLocalBuilder textSpanLocal = RentReadOnlySpanCharLocal(); // ReadOnlySpan<char> span = inputSpan.Slice(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(textSpanLocal); // If we can use IndexOf{Any}, try to accelerate the skip loop via vectorization to match the first prefix. // We can use it if this is a case-sensitive class with a small number of characters in the class. int setIndex = 0; bool canUseIndexOf = !primarySet.CaseInsensitive && primarySet.Chars is not null; bool needLoop = !canUseIndexOf || setsToUse > 1; Label checkSpanLengthLabel = default; Label charNotInClassLabel = default; Label loopBody = default; if (needLoop) { checkSpanLengthLabel = DefineLabel(); charNotInClassLabel = DefineLabel(); loopBody = DefineLabel(); // for (int i = 0; Ldc(0); Stloc(iLocal); BrFar(checkSpanLengthLabel); MarkLabel(loopBody); } if (canUseIndexOf) { setIndex = 1; if (needLoop) { // slice.Slice(iLocal + primarySet.Distance); Ldloca(textSpanLocal); Ldloc(iLocal); if (primarySet.Distance != 0) { Ldc(primarySet.Distance); Add(); } Call(s_spanSliceIntMethod); } else if (primarySet.Distance != 0) { // slice.Slice(primarySet.Distance) Ldloca(textSpanLocal); Ldc(primarySet.Distance); Call(s_spanSliceIntMethod); } else { // slice Ldloc(textSpanLocal); } switch (primarySet.Chars!.Length) { case 1: // tmp = ...IndexOf(setChars[0]); Ldc(primarySet.Chars[0]); Call(s_spanIndexOfChar); break; case 2: // tmp = ...IndexOfAny(setChars[0], setChars[1]); Ldc(primarySet.Chars[0]); Ldc(primarySet.Chars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: // tmp = ...IndexOfAny(setChars[0], setChars[1], setChars[2]}); Ldc(primarySet.Chars[0]); Ldc(primarySet.Chars[1]); Ldc(primarySet.Chars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(new string(primarySet.Chars)); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } if (needLoop) { // i += tmp; // if (tmp < 0) goto returnFalse; using (RentedLocalBuilder tmp = RentInt32Local()) { Stloc(tmp); Ldloc(iLocal); Ldloc(tmp); Add(); Stloc(iLocal); Ldloc(tmp); Ldc(0); BltFar(returnFalse); } } else { // i = tmp; // if (i < 0) goto returnFalse; Stloc(iLocal); Ldloc(iLocal); Ldc(0); BltFar(returnFalse); } // if (i >= slice.Length - (minRequiredLength - 1)) goto returnFalse; if (sets.Count > 1) { Debug.Assert(needLoop); Ldloca(textSpanLocal); Call(s_spanGetLengthMethod); Ldc(minRequiredLength - 1); Sub(); Ldloc(iLocal); BleFar(returnFalse); } } // if (!CharInClass(slice[i], prefix[0], "...")) continue; // if (!CharInClass(slice[i + 1], prefix[1], "...")) continue; // if (!CharInClass(slice[i + 2], prefix[2], "...")) continue; // ... Debug.Assert(setIndex is 0 or 1); for ( ; setIndex < sets.Count; setIndex++) { Debug.Assert(needLoop); Ldloca(textSpanLocal); Ldloc(iLocal); if (sets[setIndex].Distance != 0) { Ldc(sets[setIndex].Distance); Add(); } Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(sets[setIndex].Set, sets[setIndex].CaseInsensitive); BrfalseFar(charNotInClassLabel); } // base.runtextpos = pos + i; // return true; Ldthis(); Ldloc(pos); Ldloc(iLocal); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); if (needLoop) { MarkLabel(charNotInClassLabel); // for (...; ...; i++) Ldloc(iLocal); Ldc(1); Add(); Stloc(iLocal); // for (...; i < span.Length - (minRequiredLength - 1); ...); MarkLabel(checkSpanLengthLabel); Ldloc(iLocal); Ldloca(textSpanLocal); Call(s_spanGetLengthMethod); if (setsToUse > 1 || primarySet.Distance != 0) { Ldc(minRequiredLength - 1); Sub(); } BltFar(loopBody); // base.runtextpos = inputSpan.Length; // return false; BrFar(returnFalse); } } // Emits a right-to-left search for a set at a fixed position from the start of the pattern. // (Currently that position will always be a distance of 0, meaning the start of the pattern itself.) void EmitFixedSet_RightToLeft() { (char[]? Chars, string Set, int Distance, bool CaseInsensitive) set = _regexTree.FindOptimizations.FixedDistanceSets![0]; Debug.Assert(set.Distance == 0); if (set.Chars is { Length: 1 } && !set.CaseInsensitive) { // pos = inputSpan.Slice(0, pos).LastIndexOf(set.Chars[0]); Ldloca(inputSpan); Ldc(0); Ldloc(pos); Call(s_spanSliceIntIntMethod); Ldc(set.Chars[0]); Call(s_spanLastIndexOfChar); Stloc(pos); // if (pos < 0) goto returnFalse; Ldloc(pos); Ldc(0); BltFar(returnFalse); // base.runtextpos = pos + 1; // return true; Ldthis(); Ldloc(pos); Ldc(1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } else { Label condition = DefineLabel(); // while ((uint)--pos < (uint)inputSpan.Length) MarkLabel(condition); Ldloc(pos); Ldc(1); Sub(); Stloc(pos); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUnFar(returnFalse); // if (!MatchCharacterClass(inputSpan[i], set.Set, set.CaseInsensitive)) goto condition; Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(set.Set, set.CaseInsensitive); Brfalse(condition); // base.runtextpos = pos + 1; // return true; Ldthis(); Ldloc(pos); Ldc(1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } } // Emits a search for a literal following a leading atomic single-character loop. void EmitLiteralAfterAtomicLoop() { Debug.Assert(_regexTree.FindOptimizations.LiteralAfterLoop is not null); (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = _regexTree.FindOptimizations.LiteralAfterLoop.Value; Debug.Assert(target.LoopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(target.LoopNode.N == int.MaxValue); // while (true) Label loopBody = DefineLabel(); Label loopEnd = DefineLabel(); MarkLabel(loopBody); // ReadOnlySpan<char> slice = inputSpan.Slice(pos); using RentedLocalBuilder slice = RentReadOnlySpanCharLocal(); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(slice); // Find the literal. If we can't find it, we're done searching. // int i = slice.IndexOf(literal); // if (i < 0) break; using RentedLocalBuilder i = RentInt32Local(); Ldloc(slice); if (target.Literal.String is string literalString) { Ldstr(literalString); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); } else if (target.Literal.Chars is not char[] literalChars) { Ldc(target.Literal.Char); Call(s_spanIndexOfChar); } else { switch (literalChars.Length) { case 2: Ldc(literalChars[0]); Ldc(literalChars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(literalChars[0]); Ldc(literalChars[1]); Ldc(literalChars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(new string(literalChars)); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } Stloc(i); Ldloc(i); Ldc(0); BltFar(loopEnd); // We found the literal. Walk backwards from it finding as many matches as we can against the loop. // int prev = i; using RentedLocalBuilder prev = RentInt32Local(); Ldloc(i); Stloc(prev); // while ((uint)--prev < (uint)slice.Length) && MatchCharClass(slice[prev])); Label innerLoopBody = DefineLabel(); Label innerLoopEnd = DefineLabel(); MarkLabel(innerLoopBody); Ldloc(prev); Ldc(1); Sub(); Stloc(prev); Ldloc(prev); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUn(innerLoopEnd); Ldloca(slice); Ldloc(prev); Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(target.LoopNode.Str!, caseInsensitive: false); BrtrueFar(innerLoopBody); MarkLabel(innerLoopEnd); if (target.LoopNode.M > 0) { // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. // if ((i - prev - 1) < target.LoopNode.M) // { // pos += i + 1; // continue; // } Label metMinimum = DefineLabel(); Ldloc(i); Ldloc(prev); Sub(); Ldc(1); Sub(); Ldc(target.LoopNode.M); Bge(metMinimum); Ldloc(pos); Ldloc(i); Add(); Ldc(1); Add(); Stloc(pos); BrFar(loopBody); MarkLabel(metMinimum); } // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate i as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. // base.runtextpos = pos + prev + 1; // return true; Ldthis(); Ldloc(pos); Ldloc(prev); Add(); Ldc(1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); // } MarkLabel(loopEnd); // base.runtextpos = inputSpan.Length; // return false; BrFar(returnFalse); } } /// <summary>Generates the implementation for TryMatchAtCurrentPosition.</summary> protected void EmitTryMatchAtCurrentPosition() { // In .NET Framework and up through .NET Core 3.1, the code generated for RegexOptions.Compiled was effectively an unrolled // version of what RegexInterpreter would process. The RegexNode tree would be turned into a series of opcodes via // RegexWriter; the interpreter would then sit in a loop processing those opcodes, and the RegexCompiler iterated through the // opcodes generating code for each equivalent to what the interpreter would do albeit with some decisions made at compile-time // rather than at run-time. This approach, however, lead to complicated code that wasn't pay-for-play (e.g. a big backtracking // jump table that all compilations went through even if there was no backtracking), that didn't factor in the shape of the // tree (e.g. it's difficult to add optimizations based on interactions between nodes in the graph), and that didn't read well // when decompiled from IL to C# or when directly emitted as C# as part of a source generator. // // This implementation is instead based on directly walking the RegexNode tree and outputting code for each node in the graph. // A dedicated for each kind of RegexNode emits the code necessary to handle that node's processing, including recursively // calling the relevant function for any of its children nodes. Backtracking is handled not via a giant jump table, but instead // by emitting direct jumps to each backtracking construct. This is achieved by having all match failures jump to a "done" // label that can be changed by a previous emitter, e.g. before EmitLoop returns, it ensures that "doneLabel" is set to the // label that code should jump back to when backtracking. That way, a subsequent EmitXx function doesn't need to know exactly // where to jump: it simply always jumps to "doneLabel" on match failure, and "doneLabel" is always configured to point to // the right location. In an expression without backtracking, or before any backtracking constructs have been encountered, // "doneLabel" is simply the final return location from the TryMatchAtCurrentPosition method that will undo any captures and exit, signaling to // the calling scan loop that nothing was matched. Debug.Assert(_regexTree != null); _int32LocalsPool?.Clear(); _readOnlySpanCharLocalsPool?.Clear(); // Get the root Capture node of the tree. RegexNode node = _regexTree.Root; Debug.Assert(node.Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); Debug.Assert(node.ChildCount() == 1, "Capture nodes should have one child"); // Skip the Capture node. We handle the implicit root capture specially. node = node.Child(0); // In some limited cases, TryFindNextPossibleStartingPosition will only return true if it successfully matched the whole expression. // We can special case these to do essentially nothing in TryMatchAtCurrentPosition other than emit the capture. switch (node.Kind) { case RegexNodeKind.Multi or RegexNodeKind.Notone or RegexNodeKind.One or RegexNodeKind.Set when !IsCaseInsensitive(node): // This is the case for single and multiple characters, though the whole thing is only guaranteed // to have been validated in TryFindNextPossibleStartingPosition when doing case-sensitive comparison. // base.Capture(0, base.runtextpos, base.runtextpos + node.Str.Length); // base.runtextpos = base.runtextpos + node.Str.Length; // return true; int length = node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1; if ((node.Options & RegexOptions.RightToLeft) != 0) { length = -length; } Ldthis(); Dup(); Ldc(0); Ldthisfld(s_runtextposField); Dup(); Ldc(length); Add(); Call(s_captureMethod); Ldthisfld(s_runtextposField); Ldc(length); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); return; // The source generator special-cases RegexNode.Empty, for purposes of code learning rather than // performance. Since that's not applicable to RegexCompiler, that code isn't mirrored here. } AnalysisResults analysis = RegexTreeAnalyzer.Analyze(_regexTree); // Initialize the main locals used throughout the implementation. LocalBuilder inputSpan = DeclareReadOnlySpanChar(); LocalBuilder originalPos = DeclareInt32(); LocalBuilder pos = DeclareInt32(); LocalBuilder slice = DeclareReadOnlySpanChar(); Label doneLabel = DefineLabel(); Label originalDoneLabel = doneLabel; if (_hasTimeout) { _loopTimeoutCounter = DeclareInt32(); } // CultureInfo culture = CultureInfo.CurrentCulture; // only if the whole expression or any subportion is ignoring case, and we're not using invariant InitializeCultureForTryMatchAtCurrentPositionIfNecessary(analysis); // ReadOnlySpan<char> inputSpan = input; Ldarg_1(); Stloc(inputSpan); // int pos = base.runtextpos; // int originalpos = pos; Ldthisfld(s_runtextposField); Stloc(pos); Ldloc(pos); Stloc(originalPos); // int stackpos = 0; LocalBuilder stackpos = DeclareInt32(); Ldc(0); Stloc(stackpos); // The implementation tries to use const indexes into the span wherever possible, which we can do // for all fixed-length constructs. In such cases (e.g. single chars, repeaters, strings, etc.) // we know at any point in the regex exactly how far into it we are, and we can use that to index // into the span created at the beginning of the routine to begin at exactly where we're starting // in the input. When we encounter a variable-length construct, we transfer the static value to // pos, slicing the inputSpan appropriately, and then zero out the static position. int sliceStaticPos = 0; SliceInputSpan(); // Check whether there are captures anywhere in the expression. If there isn't, we can skip all // the boilerplate logic around uncapturing, as there won't be anything to uncapture. bool expressionHasCaptures = analysis.MayContainCapture(node); // Emit the code for all nodes in the tree. EmitNode(node); // pos += sliceStaticPos; // base.runtextpos = pos; // Capture(0, originalpos, pos); // return true; Ldthis(); Ldloc(pos); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Add(); Stloc(pos); Ldloc(pos); } Stfld(s_runtextposField); Ldthis(); Ldc(0); Ldloc(originalPos); Ldloc(pos); Call(s_captureMethod); Ldc(1); Ret(); // NOTE: The following is a difference from the source generator. The source generator emits: // UncaptureUntil(0); // return false; // at every location where the all-up match is known to fail. In contrast, the compiler currently // emits this uncapture/return code in one place and jumps to it upon match failure. The difference // stems primarily from the return-at-each-location pattern resulting in cleaner / easier to read // source code, which is not an issue for RegexCompiler emitting IL instead of C#. // If the graph contained captures, undo any remaining to handle failed matches. if (expressionHasCaptures) { // while (base.Crawlpos() != 0) base.Uncapture(); Label finalReturnLabel = DefineLabel(); Br(finalReturnLabel); MarkLabel(originalDoneLabel); Label condition = DefineLabel(); Label body = DefineLabel(); Br(condition); MarkLabel(body); Ldthis(); Call(s_uncaptureMethod); MarkLabel(condition); Ldthis(); Call(s_crawlposMethod); Brtrue(body); // Done: MarkLabel(finalReturnLabel); } else { // Done: MarkLabel(originalDoneLabel); } // return false; Ldc(0); Ret(); // Generated code successfully. return; // Whether the node has RegexOptions.IgnoreCase set. // TODO: https://github.com/dotnet/runtime/issues/61048. We should be able to delete this and all usage sites once // IgnoreCase is erradicated from the tree. The only place it should possibly be left after that work is in a Backreference, // and that can do this check directly as needed. static bool IsCaseInsensitive(RegexNode node) => (node.Options & RegexOptions.IgnoreCase) != 0; // Slices the inputSpan starting at pos until end and stores it into slice. void SliceInputSpan() { // slice = inputSpan.Slice(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(slice); } // Emits the sum of a constant and a value from a local. void EmitSum(int constant, LocalBuilder? local) { if (local == null) { Ldc(constant); } else if (constant == 0) { Ldloc(local); } else { Ldloc(local); Ldc(constant); Add(); } } // Emits a check that the span is large enough at the currently known static position to handle the required additional length. void EmitSpanLengthCheck(int requiredLength, LocalBuilder? dynamicRequiredLength = null) { // if ((uint)(sliceStaticPos + requiredLength + dynamicRequiredLength - 1) >= (uint)slice.Length) goto Done; Debug.Assert(requiredLength > 0); EmitSum(sliceStaticPos + requiredLength - 1, dynamicRequiredLength); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); } // Emits code to get ref slice[sliceStaticPos] void EmitTextSpanOffset() { Ldloc(slice); Call(s_memoryMarshalGetReference); if (sliceStaticPos > 0) { Ldc(sliceStaticPos * sizeof(char)); Add(); } } // Adds the value of sliceStaticPos into the pos local, zeros out sliceStaticPos, // and resets slice to be inputSpan.Slice(pos). void TransferSliceStaticPosToPos(bool forceSliceReload = false) { if (sliceStaticPos > 0) { // pos += sliceStaticPos; // sliceStaticPos = 0; Ldloc(pos); Ldc(sliceStaticPos); Add(); Stloc(pos); sliceStaticPos = 0; // slice = inputSpan.Slice(pos); SliceInputSpan(); } else if (forceSliceReload) { // slice = inputSpan.Slice(pos); SliceInputSpan(); } } // Emits the code for an alternation. void EmitAlternation(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Alternate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); int childCount = node.ChildCount(); Debug.Assert(childCount >= 2); Label originalDoneLabel = doneLabel; // Both atomic and non-atomic are supported. While a parent RegexNode.Atomic node will itself // successfully prevent backtracking into this child node, we can emit better / cheaper code // for an Alternate when it is atomic, so we still take it into account here. Debug.Assert(node.Parent is not null); bool isAtomic = analysis.IsAtomicByAncestor(node); // Label to jump to when any branch completes successfully. Label matchLabel = DefineLabel(); // Save off pos. We'll need to reset this each time a branch fails. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; // We need to be able to undo captures in two situations: // - If a branch of the alternation itself contains captures, then if that branch // fails to match, any captures from that branch until that failure point need to // be uncaptured prior to jumping to the next branch. // - If the expression after the alternation contains captures, then failures // to match in those expressions could trigger backtracking back into the // alternation, and thus we need uncapture any of them. // As such, if the alternation contains captures or if it's not atomic, we need // to grab the current crawl position so we can unwind back to it when necessary. // We can do all of the uncapturing as part of falling through to the next branch. // If we fail in a branch, then such uncapturing will unwind back to the position // at the start of the alternation. If we fail after the alternation, and the // matched branch didn't contain any backtracking, then the failure will end up // jumping to the next branch, which will unwind the captures. And if we fail after // the alternation and the matched branch did contain backtracking, that backtracking // construct is responsible for unwinding back to its starting crawl position. If // it eventually ends up failing, that failure will result in jumping to the next branch // of the alternation, which will again dutifully unwind the remaining captures until // what they were at the start of the alternation. Of course, if there are no captures // anywhere in the regex, we don't have to do any of that. LocalBuilder? startingCapturePos = null; if (expressionHasCaptures && (analysis.MayContainCapture(node) || !isAtomic)) { // startingCapturePos = base.Crawlpos(); startingCapturePos = DeclareInt32(); Ldthis(); Call(s_crawlposMethod); Stloc(startingCapturePos); } // After executing the alternation, subsequent matching may fail, at which point execution // will need to backtrack to the alternation. We emit a branching table at the end of the // alternation, with a label that will be left as the "doneLabel" upon exiting emitting the // alternation. The branch table is populated with an entry for each branch of the alternation, // containing either the label for the last backtracking construct in the branch if such a construct // existed (in which case the doneLabel upon emitting that node will be different from before it) // or the label for the next branch. var labelMap = new Label[childCount]; Label backtrackLabel = DefineLabel(); for (int i = 0; i < childCount; i++) { bool isLastBranch = i == childCount - 1; Label nextBranch = default; if (!isLastBranch) { // Failure to match any branch other than the last one should result // in jumping to process the next branch. nextBranch = DefineLabel(); doneLabel = nextBranch; } else { // Failure to match the last branch is equivalent to failing to match // the whole alternation, which means those failures should jump to // what "doneLabel" was defined as when starting the alternation. doneLabel = originalDoneLabel; } // Emit the code for each branch. EmitNode(node.Child(i)); // Add this branch to the backtracking table. At this point, either the child // had backtracking constructs, in which case doneLabel points to the last one // and that's where we'll want to jump to, or it doesn't, in which case doneLabel // still points to the nextBranch, which similarly is where we'll want to jump to. if (!isAtomic) { // if (stackpos + 3 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = i; // base.runstack[stackpos++] = startingCapturePos; // base.runstack[stackpos++] = startingPos; EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldc(i)); if (startingCapturePos is not null) { EmitStackPush(() => Ldloc(startingCapturePos)); } EmitStackPush(() => Ldloc(startingPos)); } labelMap[i] = doneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. // pos += sliceStaticPos; // sliceStaticPos = 0; // goto matchLabel; TransferSliceStaticPosToPos(); BrFar(matchLabel); // Reset state for next branch and loop around to generate it. This includes // setting pos back to what it was at the beginning of the alternation, // updating slice to be the full length it was, and if there's a capture that // needs to be reset, uncapturing it. if (!isLastBranch) { // NextBranch: // pos = startingPos; // slice = inputSpan.Slice(pos); // while (base.Crawlpos() > startingCapturePos) base.Uncapture(); MarkLabel(nextBranch); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } } } // We should never fall through to this location in the generated code. Either // a branch succeeded in matching and jumped to the end, or a branch failed in // matching and jumped to the next branch location. We only get to this code // if backtracking occurs and the code explicitly jumps here based on our setting // "doneLabel" to the label for this section. Thus, we only need to emit it if // something can backtrack to us, which can't happen if we're inside of an atomic // node. Thus, emit the backtracking section only if we're non-atomic. if (isAtomic) { doneLabel = originalDoneLabel; } else { doneLabel = backtrackLabel; MarkLabel(backtrackLabel); // startingPos = base.runstack[--stackpos]; // startingCapturePos = base.runstack[--stackpos]; // switch (base.runstack[--stackpos]) { ... } // branch number EmitStackPop(); Stloc(startingPos); if (startingCapturePos is not null) { EmitStackPop(); Stloc(startingCapturePos); } EmitStackPop(); Switch(labelMap); } // Successfully completed the alternate. MarkLabel(matchLabel); Debug.Assert(sliceStaticPos == 0); } // Emits the code to handle a backreference. void EmitBackreference(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Backreference, $"Unexpected type: {node.Kind}"); int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; TransferSliceStaticPosToPos(); Label backreferenceEnd = DefineLabel(); // if (!base.IsMatched(capnum)) goto (ecmascript ? end : doneLabel); Ldthis(); Ldc(capnum); Call(s_isMatchedMethod); BrfalseFar((node.Options & RegexOptions.ECMAScript) == 0 ? doneLabel : backreferenceEnd); using RentedLocalBuilder matchLength = RentInt32Local(); using RentedLocalBuilder matchIndex = RentInt32Local(); using RentedLocalBuilder i = RentInt32Local(); // int matchLength = base.MatchLength(capnum); Ldthis(); Ldc(capnum); Call(s_matchLengthMethod); Stloc(matchLength); if (!rtl) { // if (slice.Length < matchLength) goto doneLabel; Ldloca(slice); Call(s_spanGetLengthMethod); } else { // if (pos < matchLength) goto doneLabel; Ldloc(pos); } Ldloc(matchLength); BltFar(doneLabel); // int matchIndex = base.MatchIndex(capnum); Ldthis(); Ldc(capnum); Call(s_matchIndexMethod); Stloc(matchIndex); Label condition = DefineLabel(); Label body = DefineLabel(); // for (int i = 0; ...) Ldc(0); Stloc(i); Br(condition); MarkLabel(body); // if (inputSpan[matchIndex + i] != slice[i]) goto doneLabel; // for rtl, instead of slice[i] using inputSpan[pos - matchLength + i] Ldloca(inputSpan); Ldloc(matchIndex); Ldloc(i); Add(); Call(s_spanGetItemMethod); LdindU2(); if (IsCaseInsensitive(node)) { CallToLower(); } if (!rtl) { Ldloca(slice); Ldloc(i); } else { Ldloca(inputSpan); Ldloc(pos); Ldloc(matchLength); Sub(); Ldloc(i); Add(); } Call(s_spanGetItemMethod); LdindU2(); if (IsCaseInsensitive(node)) { CallToLower(); } BneFar(doneLabel); // for (...; ...; i++) Ldloc(i); Ldc(1); Add(); Stloc(i); // for (...; i < matchLength; ...) MarkLabel(condition); Ldloc(i); Ldloc(matchLength); Blt(body); // pos += matchLength; // or -= for rtl Ldloc(pos); Ldloc(matchLength); if (!rtl) { Add(); } else { Sub(); } Stloc(pos); if (!rtl) { SliceInputSpan(); } MarkLabel(backreferenceEnd); } // Emits the code for an if(backreference)-then-else conditional. void EmitBackreferenceConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.BackreferenceConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 2, $"Expected 2 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // Get the capture number to test. int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(0); RegexNode? noBranch = node.Child(1) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; Label originalDoneLabel = doneLabel; Label refNotMatched = DefineLabel(); Label endConditional = DefineLabel(); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the conditional needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. LocalBuilder resumeAt = DeclareInt32(); // if (!base.IsMatched(capnum)) goto refNotMatched; Ldthis(); Ldc(capnum); Call(s_isMatchedMethod); BrfalseFar(refNotMatched); // The specified capture was captured. Run the "yes" branch. // If it successfully matches, jump to the end. EmitNode(yesBranch); TransferSliceStaticPosToPos(); Label postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 0; Ldc(0); Stloc(resumeAt); } bool needsEndConditional = postYesDoneLabel != originalDoneLabel || noBranch is not null; if (needsEndConditional) { // goto endConditional; BrFar(endConditional); } MarkLabel(refNotMatched); Label postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { // resumeAt = 1; Ldc(1); Stloc(resumeAt); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 2; Ldc(2); Stloc(resumeAt); } } if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { // We're atomic by our parent, so even if either child branch has backtracking constructs, // we don't need to emit any backtracking logic in support, as nothing will backtrack in. // Instead, we just ensure we revert back to the original done label so that any backtracking // skips over this node. doneLabel = originalDoneLabel; if (needsEndConditional) { MarkLabel(endConditional); } } else { // Subsequent expressions might try to backtrack to here, so output a backtracking map based on resumeAt. // Skip the backtracking section // goto endConditional; Debug.Assert(needsEndConditional); Br(endConditional); // Backtrack section Label backtrack = DefineLabel(); doneLabel = backtrack; MarkLabel(backtrack); // Pop from the stack the branch that was used and jump back to its backtracking location. // resumeAt = base.runstack[--stackpos]; EmitStackPop(); Stloc(resumeAt); if (postYesDoneLabel != originalDoneLabel) { // if (resumeAt == 0) goto postIfDoneLabel; Ldloc(resumeAt); Ldc(0); BeqFar(postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { // if (resumeAt == 1) goto postNoDoneLabel; Ldloc(resumeAt); Ldc(1); BeqFar(postNoDoneLabel); } // goto originalDoneLabel; BrFar(originalDoneLabel); if (needsEndConditional) { MarkLabel(endConditional); } // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = resumeAt; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(resumeAt)); } } // Emits the code for an if(expression)-then-else conditional. void EmitExpressionConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.ExpressionConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 3, $"Expected 3 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // The first child node is the condition expression. If this matches, then we branch to the "yes" branch. // If it doesn't match, then we branch to the optional "no" branch if it exists, or simply skip the "yes" // branch, otherwise. The condition is treated as a positive lookaround. RegexNode condition = node.Child(0); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(1); RegexNode? noBranch = node.Child(2) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; Label originalDoneLabel = doneLabel; Label expressionNotMatched = DefineLabel(); Label endConditional = DefineLabel(); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the condition needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. LocalBuilder? resumeAt = null; if (!isAtomic) { resumeAt = DeclareInt32(); } // If the condition expression has captures, we'll need to uncapture them in the case of no match. LocalBuilder? startingCapturePos = null; if (analysis.MayContainCapture(condition)) { // int startingCapturePos = base.Crawlpos(); startingCapturePos = DeclareInt32(); Ldthis(); Call(s_crawlposMethod); Stloc(startingCapturePos); } // Emit the condition expression. Route any failures to after the yes branch. This code is almost // the same as for a positive lookaround; however, a positive lookaround only needs to reset the position // on a successful match, as a failed match fails the whole expression; here, we need to reset the // position on completion, regardless of whether the match is successful or not. doneLabel = expressionNotMatched; // Save off pos. We'll need to reset this upon successful completion of the lookaround. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingSliceStaticPos = sliceStaticPos; // Emit the child. The condition expression is a zero-width assertion, which is atomic, // so prevent backtracking into it. EmitNode(condition); doneLabel = originalDoneLabel; // After the condition completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. // pos = startingPos; // slice = inputSpan.Slice(pos); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingSliceStaticPos; // The expression matched. Run the "yes" branch. If it successfully matches, jump to the end. EmitNode(yesBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch Label postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 0; Ldc(0); Stloc(resumeAt!); } // goto endConditional; BrFar(endConditional); // After the condition completes unsuccessfully, reset the text positions // _and_ reset captures, which should not persist when the whole expression failed. // pos = startingPos; MarkLabel(expressionNotMatched); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } Label postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { // resumeAt = 1; Ldc(1); Stloc(resumeAt!); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 2; Ldc(2); Stloc(resumeAt!); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { // EndConditional: doneLabel = originalDoneLabel; MarkLabel(endConditional); } else { Debug.Assert(resumeAt is not null); // Skip the backtracking section. BrFar(endConditional); Label backtrack = DefineLabel(); doneLabel = backtrack; MarkLabel(backtrack); // resumeAt = StackPop(); EmitStackPop(); Stloc(resumeAt); if (postYesDoneLabel != originalDoneLabel) { // if (resumeAt == 0) goto postYesDoneLabel; Ldloc(resumeAt); Ldc(0); BeqFar(postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { // if (resumeAt == 1) goto postNoDoneLabel; Ldloc(resumeAt); Ldc(1); BeqFar(postNoDoneLabel); } // goto postConditionalDoneLabel; BrFar(originalDoneLabel); // EndConditional: MarkLabel(endConditional); // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = resumeAt; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(resumeAt!)); } } // Emits the code for a Capture node. void EmitCapture(RegexNode node, RegexNode? subsequent = null) { Debug.Assert(node.Kind is RegexNodeKind.Capture, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); int uncapnum = RegexParser.MapCaptureNumber(node.N, _regexTree.CaptureNumberSparseMapping); bool isAtomic = analysis.IsAtomicByAncestor(node); // pos += sliceStaticPos; // slice = slice.Slice(sliceStaticPos); // startingPos = pos; TransferSliceStaticPosToPos(); LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); RegexNode child = node.Child(0); if (uncapnum != -1) { // if (!IsMatched(uncapnum)) goto doneLabel; Ldthis(); Ldc(uncapnum); Call(s_isMatchedMethod); BrfalseFar(doneLabel); } // Emit child node. Label originalDoneLabel = doneLabel; EmitNode(child, subsequent); bool childBacktracks = doneLabel != originalDoneLabel; // pos += sliceStaticPos; // slice = slice.Slice(sliceStaticPos); TransferSliceStaticPosToPos(); if (uncapnum == -1) { // Capture(capnum, startingPos, pos); Ldthis(); Ldc(capnum); Ldloc(startingPos); Ldloc(pos); Call(s_captureMethod); } else { // TransferCapture(capnum, uncapnum, startingPos, pos); Ldthis(); Ldc(capnum); Ldc(uncapnum); Ldloc(startingPos); Ldloc(pos); Call(s_transferCaptureMethod); } if (isAtomic || !childBacktracks) { // If the capture is atomic and nothing can backtrack into it, we're done. // Similarly, even if the capture isn't atomic, if the captured expression // doesn't do any backtracking, we're done. doneLabel = originalDoneLabel; } else { // We're not atomic and the child node backtracks. When it does, we need // to ensure that the starting position for the capture is appropriately // reset to what it was initially (it could have changed as part of being // in a loop or similar). So, we emit a backtracking section that // pushes/pops the starting position before falling through. // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = startingPos; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(startingPos)); // Skip past the backtracking section // goto backtrackingEnd; Label backtrackingEnd = DefineLabel(); Br(backtrackingEnd); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } // Emits code to unwind the capture stack until the crawl position specified in the provided local. void EmitUncaptureUntil(LocalBuilder startingCapturePos) { Debug.Assert(startingCapturePos != null); // while (base.Crawlpos() > startingCapturePos) base.Uncapture(); Label condition = DefineLabel(); Label body = DefineLabel(); Br(condition); MarkLabel(body); Ldthis(); Call(s_uncaptureMethod); MarkLabel(condition); Ldthis(); Call(s_crawlposMethod); Ldloc(startingCapturePos); Bgt(body); } // Emits the code to handle a positive lookaround assertion. This is a positive lookahead // for left-to-right and a positive lookbehind for right-to-left. void EmitPositiveLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.PositiveLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } // Save off pos. We'll need to reset this upon successful completion of the lookaround. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // After the child completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. // pos = startingPos; // slice = inputSpan.Slice(pos); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; } // Emits the code to handle a negative lookaround assertion. This is a negative lookahead // for left-to-right and a negative lookbehind for right-to-left. void EmitNegativeLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } Label originalDoneLabel = doneLabel; // Save off pos. We'll need to reset this upon successful completion of the lookaround. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; Label negativeLookaheadDoneLabel = DefineLabel(); doneLabel = negativeLookaheadDoneLabel; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // If the generated code ends up here, it matched the lookaround, which actually // means failure for a _negative_ lookaround, so we need to jump to the original done. // goto originalDoneLabel; BrFar(originalDoneLabel); // Failures (success for a negative lookaround) jump here. MarkLabel(negativeLookaheadDoneLabel); if (doneLabel == negativeLookaheadDoneLabel) { doneLabel = originalDoneLabel; } // After the child completes in failure (success for negative lookaround), reset the text positions. // pos = startingPos; Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; doneLabel = originalDoneLabel; } // Emits the code for the node. void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(EmitNode, node, subsequent, emitLengthChecksIfRequired); return; } // RightToLeft doesn't take advantage of static positions. While RightToLeft won't update static // positions, a previous operation may have left us with a non-zero one. Make sure it's zero'd out // such that pos and slice are up-to-date. Note that RightToLeft also shouldn't use the slice span, // as it's not kept up-to-date; any RightToLeft implementation that wants to use it must first update // it from pos. if ((node.Options & RegexOptions.RightToLeft) != 0) { TransferSliceStaticPosToPos(); } switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: case RegexNodeKind.Bol: case RegexNodeKind.Eol: case RegexNodeKind.End: case RegexNodeKind.EndZ: EmitAnchors(node); return; case RegexNodeKind.Boundary: case RegexNodeKind.NonBoundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.NonECMABoundary: EmitBoundary(node); return; case RegexNodeKind.Multi: EmitMultiChar(node, emitLengthChecksIfRequired); return; case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: EmitSingleChar(node, emitLengthChecksIfRequired); return; case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: EmitSingleCharLoop(node, subsequent, emitLengthChecksIfRequired); return; case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: EmitSingleCharLazy(node, subsequent, emitLengthChecksIfRequired); return; case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: EmitSingleCharAtomicLoop(node); return; case RegexNodeKind.Loop: EmitLoop(node); return; case RegexNodeKind.Lazyloop: EmitLazy(node); return; case RegexNodeKind.Alternate: EmitAlternation(node); return; case RegexNodeKind.Concatenate: EmitConcatenation(node, subsequent, emitLengthChecksIfRequired); return; case RegexNodeKind.Atomic: EmitAtomic(node, subsequent); return; case RegexNodeKind.Backreference: EmitBackreference(node); return; case RegexNodeKind.BackreferenceConditional: EmitBackreferenceConditional(node); return; case RegexNodeKind.ExpressionConditional: EmitExpressionConditional(node); return; case RegexNodeKind.Capture: EmitCapture(node, subsequent); return; case RegexNodeKind.PositiveLookaround: EmitPositiveLookaroundAssertion(node); return; case RegexNodeKind.NegativeLookaround: EmitNegativeLookaroundAssertion(node); return; case RegexNodeKind.Nothing: BrFar(doneLabel); return; case RegexNodeKind.Empty: // Emit nothing. return; case RegexNodeKind.UpdateBumpalong: EmitUpdateBumpalong(node); return; } // All nodes should have been handled. Debug.Fail($"Unexpected node type: {node.Kind}"); } // Emits the node for an atomic. void EmitAtomic(RegexNode node, RegexNode? subsequent) { Debug.Assert(node.Kind is RegexNodeKind.Atomic or RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); RegexNode child = node.Child(0); if (!analysis.MayBacktrack(child)) { // If the child has no backtracking, the atomic is a nop and we can just skip it. // Note that the source generator equivalent for this is in the top-level EmitNode, in order to avoid // outputting some extra comments and scopes. As such formatting isn't a concern for the compiler, // the logic is instead here in EmitAtomic. EmitNode(child, subsequent); return; } // Grab the current done label and the current backtracking position. The purpose of the atomic node // is to ensure that nodes after it that might backtrack skip over the atomic, which means after // rendering the atomic's child, we need to reset the label so that subsequent backtracking doesn't // see any label left set by the atomic's child. We also need to reset the backtracking stack position // so that the state on the stack remains consistent. Label originalDoneLabel = doneLabel; // int startingStackpos = stackpos; using RentedLocalBuilder startingStackpos = RentInt32Local(); Ldloc(stackpos); Stloc(startingStackpos); // Emit the child. EmitNode(child, subsequent); // Reset the stack position and done label. // stackpos = startingStackpos; Ldloc(startingStackpos); Stloc(stackpos); doneLabel = originalDoneLabel; } // Emits the code to handle updating base.runtextpos to pos in response to // an UpdateBumpalong node. This is used when we want to inform the scan loop that // it should bump from this location rather than from the original location. void EmitUpdateBumpalong(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.UpdateBumpalong, $"Unexpected type: {node.Kind}"); // if (base.runtextpos < pos) // { // base.runtextpos = pos; // } TransferSliceStaticPosToPos(); Ldthisfld(s_runtextposField); Ldloc(pos); Label skipUpdate = DefineLabel(); Bge(skipUpdate); Ldthis(); Ldloc(pos); Stfld(s_runtextposField); MarkLabel(skipUpdate); } // Emits code for a concatenation void EmitConcatenation(RegexNode node, RegexNode? subsequent, bool emitLengthChecksIfRequired) { Debug.Assert(node.Kind is RegexNodeKind.Concatenate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); // Emit the code for each child one after the other. int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { // If we can find a subsequence of fixed-length children, we can emit a length check once for that sequence // and then skip the individual length checks for each. We can also discover case-insensitive sequences that // can be checked efficiently with methods like StartsWith. if ((node.Options & RegexOptions.RightToLeft) == 0 && emitLengthChecksIfRequired && node.TryGetJoinableLengthCheckChildRange(i, out int requiredLength, out int exclusiveEnd)) { EmitSpanLengthCheck(requiredLength); for (; i < exclusiveEnd; i++) { if (node.TryGetOrdinalCaseInsensitiveString(i, exclusiveEnd, out int nodesConsumed, out string? caseInsensitiveString)) { // if (!sliceSpan.Slice(sliceStaticPause).StartsWith(caseInsensitiveString, StringComparison.OrdinalIgnoreCase)) goto doneLabel; if (sliceStaticPos > 0) { Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); } else { Ldloc(slice); } Ldstr(caseInsensitiveString); Call(s_stringAsSpanMethod); Ldc((int)StringComparison.OrdinalIgnoreCase); Call(s_spanStartsWithSpanComparison); BrfalseFar(doneLabel); sliceStaticPos += caseInsensitiveString.Length; i += nodesConsumed - 1; continue; } EmitNode(node.Child(i), GetSubsequent(i, node, subsequent), emitLengthChecksIfRequired: false); } i--; continue; } EmitNode(node.Child(i), GetSubsequent(i, node, subsequent)); } // Gets the node to treat as the subsequent one to node.Child(index) static RegexNode? GetSubsequent(int index, RegexNode node, RegexNode? subsequent) { int childCount = node.ChildCount(); for (int i = index + 1; i < childCount; i++) { RegexNode next = node.Child(i); if (next.Kind is not RegexNodeKind.UpdateBumpalong) // skip node types that don't have a semantic impact { return next; } } return subsequent; } } // Emits the code to handle a single-character match. void EmitSingleChar(RegexNode node, bool emitLengthCheck = true, LocalBuilder? offset = null) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; Debug.Assert(!rtl || offset is null); if (emitLengthCheck) { if (!rtl) { // if ((uint)(sliceStaticPos + offset) >= slice.Length) goto Done; EmitSpanLengthCheck(1, offset); } else { // if ((uint)(pos - 1) >= inputSpan.Length) goto Done; Ldloc(pos); Ldc(1); Sub(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); } } if (!rtl) { // slice[staticPos + offset] Ldloca(slice); EmitSum(sliceStaticPos, offset); } else { // inputSpan[pos - 1] Ldloca(inputSpan); EmitSum(-1, pos); } Call(s_spanGetItemMethod); LdindU2(); // if (loadedChar != ch) goto doneLabel; if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(doneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(doneLabel); } else // IsNotoneFamily { BeqFar(doneLabel); } } if (!rtl) { sliceStaticPos++; } else { // pos--; Ldloc(pos); Ldc(1); Sub(); Stloc(pos); } } // Emits the code to handle a boundary check on a character. void EmitBoundary(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Boundary or RegexNodeKind.NonBoundary or RegexNodeKind.ECMABoundary or RegexNodeKind.NonECMABoundary, $"Unexpected type: {node.Kind}"); if ((node.Options & RegexOptions.RightToLeft) != 0) { // RightToLeft doesn't use static position. This ensures it's 0. TransferSliceStaticPosToPos(); } // if (!IsBoundary(inputSpan, pos + sliceStaticPos)) goto doneLabel; Ldthis(); Ldloc(inputSpan); Ldloc(pos); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Add(); } switch (node.Kind) { case RegexNodeKind.Boundary: Call(s_isBoundaryMethod); BrfalseFar(doneLabel); break; case RegexNodeKind.NonBoundary: Call(s_isBoundaryMethod); BrtrueFar(doneLabel); break; case RegexNodeKind.ECMABoundary: Call(s_isECMABoundaryMethod); BrfalseFar(doneLabel); break; default: Debug.Assert(node.Kind == RegexNodeKind.NonECMABoundary); Call(s_isECMABoundaryMethod); BrtrueFar(doneLabel); break; } } // Emits the code to handle various anchors. void EmitAnchors(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.Bol or RegexNodeKind.End or RegexNodeKind.EndZ or RegexNodeKind.Eol, $"Unexpected type: {node.Kind}"); Debug.Assert((node.Options & RegexOptions.RightToLeft) == 0 || sliceStaticPos == 0); Debug.Assert(sliceStaticPos >= 0); Debug.Assert(sliceStaticPos >= 0); switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: if (sliceStaticPos > 0) { // If we statically know we've already matched part of the regex, there's no way we're at the // beginning or start, as we've already progressed past it. BrFar(doneLabel); } else { // if (pos > 0/start) goto doneLabel; Ldloc(pos); if (node.Kind == RegexNodeKind.Beginning) { Ldc(0); } else { Ldthisfld(s_runtextstartField); } BneFar(doneLabel); } break; case RegexNodeKind.Bol: if (sliceStaticPos > 0) { // if (slice[sliceStaticPos - 1] != '\n') goto doneLabel; Ldloca(slice); Ldc(sliceStaticPos - 1); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); } else { // We can't use our slice in this case, because we'd need to access slice[-1], so we access the inputSpan directly: // if (pos > 0 && inputSpan[pos - 1] != '\n') goto doneLabel; Label success = DefineLabel(); Ldloc(pos); Ldc(0); Ble(success); Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } break; case RegexNodeKind.End: if (sliceStaticPos > 0) { // if (sliceStaticPos < slice.Length) goto doneLabel; Ldc(sliceStaticPos); Ldloca(slice); } else { // if (pos < inputSpan.Length) goto doneLabel; Ldloc(pos); Ldloca(inputSpan); } Call(s_spanGetLengthMethod); BltUnFar(doneLabel); break; case RegexNodeKind.EndZ: if (sliceStaticPos > 0) { // if (sliceStaticPos < slice.Length - 1) goto doneLabel; Ldc(sliceStaticPos); Ldloca(slice); } else { // if (pos < inputSpan.Length - 1) goto doneLabel Ldloc(pos); Ldloca(inputSpan); } Call(s_spanGetLengthMethod); Ldc(1); Sub(); BltFar(doneLabel); goto case RegexNodeKind.Eol; case RegexNodeKind.Eol: if (sliceStaticPos > 0) { // if (sliceStaticPos < slice.Length && slice[sliceStaticPos] != '\n') goto doneLabel; Label success = DefineLabel(); Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUn(success); Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } else { // if ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\n') goto doneLabel; Label success = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUn(success); Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } break; } } // Emits the code to handle a multiple-character match. void EmitMultiChar(RegexNode node, bool emitLengthCheck) { Debug.Assert(node.Kind is RegexNodeKind.Multi, $"Unexpected type: {node.Kind}"); EmitMultiCharString(node.Str!, IsCaseInsensitive(node), emitLengthCheck, (node.Options & RegexOptions.RightToLeft) != 0); } void EmitMultiCharString(string str, bool caseInsensitive, bool emitLengthCheck, bool rightToLeft) { Debug.Assert(str.Length >= 2); if (rightToLeft) { Debug.Assert(emitLengthCheck); TransferSliceStaticPosToPos(); // if ((uint)(pos - str.Length) >= inputSpan.Length) goto doneLabel; Ldloc(pos); Ldc(str.Length); Sub(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); for (int i = str.Length - 1; i >= 0; i--) { // if (inputSpan[--pos] != str[str.Length - 1 - i]) goto doneLabel Ldloc(pos); Ldc(1); Sub(); Stloc(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); if (caseInsensitive) { CallToLower(); } Ldc(str[i]); BneFar(doneLabel); } return; } if (caseInsensitive) // StartsWith(..., XxIgnoreCase) won't necessarily be the same as char-by-char comparison { // This case should be relatively rare. It will only occur with IgnoreCase and a series of non-ASCII characters. if (emitLengthCheck) { EmitSpanLengthCheck(str.Length); } foreach (char c in str) { // if (c != slice[sliceStaticPos++]) goto doneLabel; EmitTextSpanOffset(); sliceStaticPos++; LdindU2(); CallToLower(); Ldc(c); BneFar(doneLabel); } } else { // if (!slice.Slice(sliceStaticPos).StartsWith("...") goto doneLabel; Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); Ldstr(str); Call(s_stringAsSpanMethod); Call(s_spanStartsWithSpan); BrfalseFar(doneLabel); sliceStaticPos += str.Length; } } // Emits the code to handle a backtracking, single-character loop. void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop, $"Unexpected type: {node.Kind}"); // If this is actually atomic based on its parent, emit it as atomic instead; no backtracking necessary. if (analysis.IsAtomicByAncestor(node)) { EmitSingleCharAtomicLoop(node); return; } // If this is actually a repeater, emit that instead; no backtracking necessary. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // Emit backtracking around an atomic single char loop. We can then implement the backtracking // as an afterthought, since we know exactly how many characters are accepted by each iteration // of the wrapped loop (1) and that there's nothing captured by the loop. Debug.Assert(node.M < node.N); Label backtrackingLabel = DefineLabel(); Label endLoop = DefineLabel(); LocalBuilder startingPos = DeclareInt32(); LocalBuilder endingPos = DeclareInt32(); LocalBuilder? capturepos = expressionHasCaptures ? DeclareInt32() : null; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // Grab the current position, then emit the loop as atomic, and then // grab the current position again. Even though we emit the loop without // knowledge of backtracking, we can layer it on top by just walking back // through the individual characters (a benefit of the loop matching exactly // one character per iteration, no possible captures within the loop, etc.) // int startingPos = pos; Ldloc(pos); Stloc(startingPos); EmitSingleCharAtomicLoop(node); // int endingPos = pos; TransferSliceStaticPosToPos(); Ldloc(pos); Stloc(endingPos); // int capturepos = base.Crawlpos(); if (capturepos is not null) { Ldthis(); Call(s_crawlposMethod); Stloc(capturepos); } // startingPos += node.M; // or -= for rtl if (node.M > 0) { Ldloc(startingPos); Ldc(!rtl ? node.M : -node.M); Add(); Stloc(startingPos); } // goto endLoop; BrFar(endLoop); // Backtracking section. Subsequent failures will jump to here, at which // point we decrement the matched count as long as it's above the minimum // required, and try again by flowing to everything that comes after this. MarkLabel(backtrackingLabel); if (capturepos is not null) { // capturepos = base.runstack[--stackpos]; // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitStackPop(); Stloc(capturepos); EmitUncaptureUntil(capturepos); } // endingPos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(endingPos); EmitStackPop(); Stloc(startingPos); // if (startingPos >= endingPos) goto doneLabel; // or <= for rtl Ldloc(startingPos); Ldloc(endingPos); if (!rtl) { BgeFar(doneLabel); } else { BleFar(doneLabel); } if (!rtl && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal) { // endingPos = inputSpan.Slice(startingPos, Math.Min(inputSpan.Length, endingPos + literal.Length - 1) - startingPos).LastIndexOf(literal); // if (endingPos < 0) // { // goto doneLabel; // } Ldloca(inputSpan); Ldloc(startingPos); if (literal.Item2 is not null) { Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldloc(endingPos); Ldc(literal.Item2.Length - 1); Add(); Call(s_mathMinIntInt); Ldloc(startingPos); Sub(); Call(s_spanSliceIntIntMethod); Ldstr(literal.Item2); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfSpan); } else { Ldloc(endingPos); Ldloc(startingPos); Sub(); Call(s_spanSliceIntIntMethod); if (literal.Item3 is not null) { switch (literal.Item3.Length) { case 2: Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Call(s_spanLastIndexOfAnyCharChar); break; case 3: Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Ldc(literal.Item3[2]); Call(s_spanLastIndexOfAnyCharCharChar); break; default: Ldstr(literal.Item3); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfAnySpan); break; } } else { Ldc(literal.Item1); Call(s_spanLastIndexOfChar); } } Stloc(endingPos); Ldloc(endingPos); Ldc(0); BltFar(doneLabel); // endingPos += startingPos; Ldloc(endingPos); Ldloc(startingPos); Add(); Stloc(endingPos); } else { // endingPos--; // or ++ for rtl Ldloc(endingPos); Ldc(!rtl ? 1 : -1); Sub(); Stloc(endingPos); } // pos = endingPos; Ldloc(endingPos); Stloc(pos); if (!rtl) { // slice = inputSpan.Slice(pos); SliceInputSpan(); } MarkLabel(endLoop); EmitStackResizeIfNeeded(expressionHasCaptures ? 3 : 2); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(endingPos)); if (capturepos is not null) { EmitStackPush(() => Ldloc(capturepos!)); } doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes } void EmitSingleCharLazy(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy, $"Unexpected type: {node.Kind}"); // Emit the min iterations as a repeater. Any failures here don't necessitate backtracking, // as the lazy itself failed to match, and there's no backtracking possible by the individual // characters/iterations themselves. if (node.M > 0) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); } // If the whole thing was actually that repeater, we're done. Similarly, if this is actually an atomic // lazy loop, nothing will ever backtrack into this node, so we never need to iterate more than the minimum. if (node.M == node.N || analysis.IsAtomicByAncestor(node)) { return; } Debug.Assert(node.M < node.N); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // We now need to match one character at a time, each time allowing the remainder of the expression // to try to match, and only matching another character if the subsequent expression fails to match. // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // If the loop isn't unbounded, track the number of iterations and the max number to allow. LocalBuilder? iterationCount = null; int? maxIterations = null; if (node.N != int.MaxValue) { maxIterations = node.N - node.M; // int iterationCount = 0; iterationCount = DeclareInt32(); Ldc(0); Stloc(iterationCount); } // Track the current crawl position. Upon backtracking, we'll unwind any captures beyond this point. LocalBuilder? capturepos = expressionHasCaptures ? DeclareInt32() : null; // Track the current pos. Each time we backtrack, we'll reset to the stored position, which // is also incremented each time we match another character in the loop. // int startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); // Skip the backtracking section for the initial subsequent matching. We've already matched the // minimum number of iterations, which means we can successfully match with zero additional iterations. // goto endLoopLabel; Label endLoopLabel = DefineLabel(); BrFar(endLoopLabel); // Backtracking section. Subsequent failures will jump to here. Label backtrackingLabel = DefineLabel(); MarkLabel(backtrackingLabel); // Uncapture any captures if the expression has any. It's possible the captures it has // are before this node, in which case this is wasted effort, but still functionally correct. if (capturepos is not null) { // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitUncaptureUntil(capturepos); } // If there's a max number of iterations, see if we've exceeded the maximum number of characters // to match. If we haven't, increment the iteration count. if (maxIterations is not null) { // if (iterationCount >= maxIterations) goto doneLabel; Ldloc(iterationCount!); Ldc(maxIterations.Value); BgeFar(doneLabel); // iterationCount++; Ldloc(iterationCount!); Ldc(1); Add(); Stloc(iterationCount!); } // Now match the next item in the lazy loop. We need to reset the pos to the position // just after the last character in this loop was matched, and we need to store the resulting position // for the next time we backtrack. // pos = startingPos; // Match single char; Ldloc(startingPos); Stloc(pos); SliceInputSpan(); EmitSingleChar(node); TransferSliceStaticPosToPos(); // Now that we've appropriately advanced by one character and are set for what comes after the loop, // see if we can skip ahead more iterations by doing a search for a following literal. if (!rtl && iterationCount is null && node.Kind is RegexNodeKind.Notonelazy && !IsCaseInsensitive(node) && subsequent?.FindStartingLiteral(4) is ValueTuple<char, string?, string?> literal && // 5 == max optimized by IndexOfAny, and we need to reserve 1 for node.Ch (literal.Item3 is not null ? !literal.Item3.Contains(node.Ch) : (literal.Item2?[0] ?? literal.Item1) != node.Ch)) // no overlap between node.Ch and the start of the literal { // e.g. "<[^>]*?>" // This lazy loop will consume all characters other than node.Ch until the subsequent literal. // We can implement it to search for either that char or the literal, whichever comes first. // If it ends up being that node.Ch, the loop fails (we're only here if we're backtracking). // startingPos = slice.IndexOfAny(node.Ch, literal); Ldloc(slice); if (literal.Item3 is not null) { switch (literal.Item3.Length) { case 2: Ldc(node.Ch); Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(node.Ch + literal.Item3); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } else { Ldc(node.Ch); Ldc(literal.Item2?[0] ?? literal.Item1); Call(s_spanIndexOfAnyCharChar); } Stloc(startingPos); // if ((uint)startingPos >= (uint)slice.Length) goto doneLabel; Ldloc(startingPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); // if (slice[startingPos] == node.Ch) goto doneLabel; Ldloca(slice); Ldloc(startingPos); Call(s_spanGetItemMethod); LdindU2(); Ldc(node.Ch); BeqFar(doneLabel); // pos += startingPos; // slice = inputSpace.Slice(pos); Ldloc(pos); Ldloc(startingPos); Add(); Stloc(pos); SliceInputSpan(); } else if (!rtl && iterationCount is null && node.Kind is RegexNodeKind.Setlazy && node.Str == RegexCharClass.AnyClass && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal2) { // e.g. ".*?string" with RegexOptions.Singleline // This lazy loop will consume all characters until the subsequent literal. If the subsequent literal // isn't found, the loop fails. We can implement it to just search for that literal. // startingPos = slice.IndexOf(literal); Ldloc(slice); if (literal2.Item2 is not null) { Ldstr(literal2.Item2); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); } else if (literal2.Item3 is not null) { switch (literal2.Item3.Length) { case 2: Ldc(literal2.Item3[0]); Ldc(literal2.Item3[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(literal2.Item3[0]); Ldc(literal2.Item3[1]); Ldc(literal2.Item3[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(literal2.Item3); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } else { Ldc(literal2.Item1); Call(s_spanIndexOfChar); } Stloc(startingPos); // if (startingPos < 0) goto doneLabel; Ldloc(startingPos); Ldc(0); BltFar(doneLabel); // pos += startingPos; // slice = inputSpace.Slice(pos); Ldloc(pos); Ldloc(startingPos); Add(); Stloc(pos); SliceInputSpan(); } // Store the position we've left off at in case we need to iterate again. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Update the done label for everything that comes after this node. This is done after we emit the single char // matching, as that failing indicates the loop itself has failed to match. Label originalDoneLabel = doneLabel; doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes MarkLabel(endLoopLabel); if (capturepos is not null) { // capturepos = base.CrawlPos(); Ldthis(); Call(s_crawlposMethod); Stloc(capturepos); } if (node.IsInLoop()) { // Store the loop's state // base.runstack[stackpos++] = startingPos; // base.runstack[stackpos++] = capturepos; // base.runstack[stackpos++] = iterationCount; EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); if (capturepos is not null) { EmitStackPush(() => Ldloc(capturepos)); } if (iterationCount is not null) { EmitStackPush(() => Ldloc(iterationCount)); } // Skip past the backtracking section Label backtrackingEnd = DefineLabel(); BrFar(backtrackingEnd); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // iterationCount = base.runstack[--stackpos]; // capturepos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; if (iterationCount is not null) { EmitStackPop(); Stloc(iterationCount); } if (capturepos is not null) { EmitStackPop(); Stloc(capturepos); } EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } void EmitLazy(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; Label originalDoneLabel = doneLabel; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually an atomic lazy loop, we need to output just the minimum number of iterations, // as nothing will backtrack into the lazy loop to get it progress further. if (isAtomic) { switch (minIterations) { case 0: // Atomic lazy with a min count of 0: nop. return; case 1: // Atomic lazy with a min count of 1: just output the child, no looping required. EmitNode(node.Child(0)); return; } } // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); LocalBuilder startingPos = DeclareInt32(); LocalBuilder iterationCount = DeclareInt32(); LocalBuilder sawEmpty = DeclareInt32(); Label body = DefineLabel(); Label endLoop = DefineLabel(); // iterationCount = 0; // startingPos = pos; // sawEmpty = 0; // false Ldc(0); Stloc(iterationCount); Ldloc(pos); Stloc(startingPos); Ldc(0); Stloc(sawEmpty); // If the min count is 0, start out by jumping right to what's after the loop. Backtracking // will then bring us back in to do further iterations. if (minIterations == 0) { // goto endLoop; BrFar(endLoop); } // Iteration body MarkLabel(body); EmitTimeoutCheck(); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. // base.runstack[stackpos++] = base.Crawlpos(); // base.runstack[stackpos++] = startingPos; // base.runstack[stackpos++] = pos; // base.runstack[stackpos++] = sawEmpty; EmitStackResizeIfNeeded(3); if (expressionHasCaptures) { EmitStackPush(() => { Ldthis(); Call(s_crawlposMethod); }); } EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(pos)); EmitStackPush(() => Ldloc(sawEmpty)); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. // iterationCount++; Ldloc(iterationCount); Ldc(1); Add(); Stloc(iterationCount); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. Label iterationFailedLabel = DefineLabel(); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 if (doneLabel == iterationFailedLabel) { doneLabel = originalDoneLabel; } // Loop condition. Continue iterating if we've not yet reached the minimum. if (minIterations > 0) { // if (iterationCount < minIterations) goto body; Ldloc(iterationCount); Ldc(minIterations); BltFar(body); } // If the last iteration was empty, we need to prevent further iteration from this point // unless we backtrack out of this iteration. We can do that easily just by pretending // we reached the max iteration count. // if (pos == startingPos) sawEmpty = 1; // true Label skipSawEmptySet = DefineLabel(); Ldloc(pos); Ldloc(startingPos); Bne(skipSawEmptySet); Ldc(1); Stloc(sawEmpty); MarkLabel(skipSawEmptySet); // We matched the next iteration. Jump to the subsequent code. // goto endLoop; BrFar(endLoop); // Now handle what happens when an iteration fails. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel); // iterationCount--; Ldloc(iterationCount); Ldc(1); Sub(); Stloc(iterationCount); // if (iterationCount < 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BltFar(originalDoneLabel); // sawEmpty = base.runstack[--stackpos]; // pos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; // capturepos = base.runstack[--stackpos]; // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitStackPop(); Stloc(sawEmpty); EmitStackPop(); Stloc(pos); EmitStackPop(); Stloc(startingPos); if (expressionHasCaptures) { using RentedLocalBuilder poppedCrawlPos = RentInt32Local(); EmitStackPop(); Stloc(poppedCrawlPos); EmitUncaptureUntil(poppedCrawlPos); } SliceInputSpan(); if (doneLabel == originalDoneLabel) { // goto originalDoneLabel; BrFar(originalDoneLabel); } else { // if (iterationCount == 0) goto originalDoneLabel; // goto doneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); BrFar(doneLabel); } MarkLabel(endLoop); if (!isAtomic) { // Store the capture's state and skip the backtracking section EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(iterationCount)); EmitStackPush(() => Ldloc(sawEmpty)); Label skipBacktrack = DefineLabel(); BrFar(skipBacktrack); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // sawEmpty = base.runstack[--stackpos]; // iterationCount = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(sawEmpty); EmitStackPop(); Stloc(iterationCount); EmitStackPop(); Stloc(startingPos); if (maxIterations == int.MaxValue) { // if (sawEmpty != 0) goto doneLabel; Ldloc(sawEmpty); Ldc(0); BneFar(doneLabel); } else { // if (iterationCount >= maxIterations || sawEmpty != 0) goto doneLabel; Ldloc(iterationCount); Ldc(maxIterations); BgeFar(doneLabel); Ldloc(sawEmpty); Ldc(0); BneFar(doneLabel); } // goto body; BrFar(body); doneLabel = backtrack; MarkLabel(skipBacktrack); } } // Emits the code to handle a loop (repeater) with a fixed number of iterations. // RegexNode.M is used for the number of iterations (RegexNode.N is ignored), as this // might be used to implement the required iterations of other kinds of loops. void EmitSingleCharRepeater(RegexNode node, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); int iterations = node.M; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; switch (iterations) { case 0: // No iterations, nothing to do. return; case 1: // Just match the individual item EmitSingleChar(node, emitLengthChecksIfRequired); return; case <= RegexNode.MultiVsRepeaterLimit when node.IsOneFamily && !IsCaseInsensitive(node): // This is a repeated case-sensitive character; emit it as a multi in order to get all the optimizations // afforded to a multi, e.g. unrolling the loop with multi-char reads/comparisons at a time. EmitMultiCharString(new string(node.Ch, iterations), caseInsensitive: false, emitLengthChecksIfRequired, rtl); return; } if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position with rtl Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); // for (int i = 0; ...) using RentedLocalBuilder iterationLocal = RentInt32Local(); Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); // TimeoutCheck(); // HandleSingleChar(); MarkLabel(bodyLabel); EmitTimeoutCheck(); EmitSingleChar(node); // for (...; ...; i++) Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); // for (...; i < iterations; ...) MarkLabel(conditionLabel); Ldloc(iterationLocal); Ldc(iterations); BltFar(bodyLabel); return; } // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length) goto doneLabel; if (emitLengthChecksIfRequired) { EmitSpanLengthCheck(iterations); } // Arbitrary limit for unrolling vs creating a loop. We want to balance size in the generated // code with other costs, like the (small) overhead of slicing to create the temp span to iterate. const int MaxUnrollSize = 16; if (iterations <= MaxUnrollSize) { // if (slice[sliceStaticPos] != c1 || // slice[sliceStaticPos + 1] != c2 || // ...) // goto doneLabel; for (int i = 0; i < iterations; i++) { EmitSingleChar(node, emitLengthCheck: false); } } else { // ReadOnlySpan<char> tmp = slice.Slice(sliceStaticPos, iterations); // for (int i = 0; i < tmp.Length; i++) // { // TimeoutCheck(); // if (tmp[i] != ch) goto Done; // } // sliceStaticPos += iterations; Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); using RentedLocalBuilder spanLocal = RentReadOnlySpanCharLocal(); Ldloca(slice); Ldc(sliceStaticPos); Ldc(iterations); Call(s_spanSliceIntIntMethod); Stloc(spanLocal); using RentedLocalBuilder iterationLocal = RentInt32Local(); Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); MarkLabel(bodyLabel); EmitTimeoutCheck(); LocalBuilder tmpTextSpanLocal = slice; // we want EmitSingleChar to refer to this temporary int tmpTextSpanPos = sliceStaticPos; slice = spanLocal; sliceStaticPos = 0; EmitSingleChar(node, emitLengthCheck: false, offset: iterationLocal); slice = tmpTextSpanLocal; sliceStaticPos = tmpTextSpanPos; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); MarkLabel(conditionLabel); Ldloc(iterationLocal); Ldloca(spanLocal); Call(s_spanGetLengthMethod); BltFar(bodyLabel); sliceStaticPos += iterations; } } // Emits the code to handle a non-backtracking, variable-length loop around a single character comparison. void EmitSingleCharAtomicLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); // If this is actually a repeater, emit that instead. if (node.M == node.N) { EmitSingleCharRepeater(node); return; } // If this is actually an optional single char, emit that instead. if (node.M == 0 && node.N == 1) { EmitAtomicSingleCharZeroOrOne(node); return; } Debug.Assert(node.N > node.M); int minIterations = node.M; int maxIterations = node.N; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; using RentedLocalBuilder iterationLocal = RentInt32Local(); Label atomicLoopDoneLabel = DefineLabel(); Span<char> setChars = stackalloc char[5]; // max optimized by IndexOfAny today int numSetChars = 0; if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position for rtl Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); // int i = 0; Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); // Body: // TimeoutCheck(); MarkLabel(bodyLabel); EmitTimeoutCheck(); // if (pos <= iterationLocal) goto atomicLoopDoneLabel; Ldloc(pos); Ldloc(iterationLocal); BleFar(atomicLoopDoneLabel); // if (inputSpan[pos - i - 1] != ch) goto atomicLoopDoneLabel; Ldloca(inputSpan); Ldloc(pos); Ldloc(iterationLocal); Sub(); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(atomicLoopDoneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(atomicLoopDoneLabel); } else // IsNotoneFamily { BeqFar(atomicLoopDoneLabel); } } // i++; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); // if (i >= maxIterations) goto atomicLoopDoneLabel; MarkLabel(conditionLabel); if (maxIterations != int.MaxValue) { Ldloc(iterationLocal); Ldc(maxIterations); BltFar(bodyLabel); } else { BrFar(bodyLabel); } } else if (node.IsNotoneFamily && maxIterations == int.MaxValue && (!IsCaseInsensitive(node))) { // For Notone, we're looking for a specific character, as everything until we find // it is consumed by the loop. If we're unbounded, such as with ".*" and if we're case-sensitive, // we can use the vectorized IndexOf to do the search, rather than open-coding it. The unbounded // restriction is purely for simplicity; it could be removed in the future with additional code to // handle the unbounded case. // int i = slice.Slice(sliceStaticPos).IndexOf(char); if (sliceStaticPos > 0) { Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); } else { Ldloc(slice); } Ldc(node.Ch); Call(s_spanIndexOfChar); Stloc(iterationLocal); // if (i >= 0) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldc(0); BgeFar(atomicLoopDoneLabel); // i = slice.Length - sliceStaticPos; Ldloca(slice); Call(s_spanGetLengthMethod); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Sub(); } Stloc(iterationLocal); } else if (node.IsSetFamily && maxIterations == int.MaxValue && !IsCaseInsensitive(node) && (numSetChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0 && RegexCharClass.IsNegated(node.Str!)) { // If the set is negated and contains only a few characters (if it contained 1 and was negated, it would // have been reduced to a Notone), we can use an IndexOfAny to find any of the target characters. // As with the notoneloopatomic above, the unbounded constraint is purely for simplicity. Debug.Assert(numSetChars > 1); // int i = slice.Slice(sliceStaticPos).IndexOfAny(ch1, ch2, ...); if (sliceStaticPos > 0) { Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); } else { Ldloc(slice); } switch (numSetChars) { case 2: Ldc(setChars[0]); Ldc(setChars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(setChars[0]); Ldc(setChars[1]); Ldc(setChars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(setChars.Slice(0, numSetChars).ToString()); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } Stloc(iterationLocal); // if (i >= 0) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldc(0); BgeFar(atomicLoopDoneLabel); // i = slice.Length - sliceStaticPos; Ldloca(slice); Call(s_spanGetLengthMethod); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Sub(); } Stloc(iterationLocal); } else if (node.IsSetFamily && maxIterations == int.MaxValue && node.Str == RegexCharClass.AnyClass) { // .* was used with RegexOptions.Singleline, which means it'll consume everything. Just jump to the end. // The unbounded constraint is the same as in the Notone case above, done purely for simplicity. // int i = inputSpan.Length - pos; TransferSliceStaticPosToPos(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldloc(pos); Sub(); Stloc(iterationLocal); } else { // For everything else, do a normal loop. // Transfer sliceStaticPos to pos to help with bounds check elimination on the loop. TransferSliceStaticPosToPos(); Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); // int i = 0; Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); // Body: // TimeoutCheck(); MarkLabel(bodyLabel); EmitTimeoutCheck(); // if ((uint)i >= (uint)slice.Length) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(atomicLoopDoneLabel); // if (slice[i] != ch) goto atomicLoopDoneLabel; Ldloca(slice); Ldloc(iterationLocal); Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(atomicLoopDoneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(atomicLoopDoneLabel); } else // IsNotoneFamily { BeqFar(atomicLoopDoneLabel); } } // i++; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); // if (i >= maxIterations) goto atomicLoopDoneLabel; MarkLabel(conditionLabel); if (maxIterations != int.MaxValue) { Ldloc(iterationLocal); Ldc(maxIterations); BltFar(bodyLabel); } else { BrFar(bodyLabel); } } // Done: MarkLabel(atomicLoopDoneLabel); // Check to ensure we've found at least min iterations. if (minIterations > 0) { Ldloc(iterationLocal); Ldc(minIterations); BltFar(doneLabel); } // Now that we've completed our optional iterations, advance the text span // and pos by the number of iterations completed. if (!rtl) { // slice = slice.Slice(i); Ldloca(slice); Ldloc(iterationLocal); Call(s_spanSliceIntMethod); Stloc(slice); // pos += i; Ldloc(pos); Ldloc(iterationLocal); Add(); Stloc(pos); } else { // pos -= i; Ldloc(pos); Ldloc(iterationLocal); Sub(); Stloc(pos); } } // Emits the code to handle a non-backtracking optional zero-or-one loop. void EmitAtomicSingleCharZeroOrOne(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M == 0 && node.N == 1); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; if (rtl) { TransferSliceStaticPosToPos(); // we don't use static pos for rtl } Label skipUpdatesLabel = DefineLabel(); if (!rtl) { // if ((uint)sliceStaticPos >= (uint)slice.Length) goto skipUpdatesLabel; Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(skipUpdatesLabel); } else { // if (pos == 0) goto skipUpdatesLabel; Ldloc(pos); Ldc(0); BeqFar(skipUpdatesLabel); } if (!rtl) { // if (slice[sliceStaticPos] != ch) goto skipUpdatesLabel; Ldloca(slice); Ldc(sliceStaticPos); } else { // if (inputSpan[pos - 1] != ch) goto skipUpdatesLabel; Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); } Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(skipUpdatesLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(skipUpdatesLabel); } else // IsNotoneFamily { BeqFar(skipUpdatesLabel); } } if (!rtl) { // slice = slice.Slice(1); Ldloca(slice); Ldc(1); Call(s_spanSliceIntMethod); Stloc(slice); // pos++; Ldloc(pos); Ldc(1); Add(); Stloc(pos); } else { // pos--; Ldloc(pos); Ldc(1); Sub(); Stloc(pos); } MarkLabel(skipUpdatesLabel); } void EmitNonBacktrackingRepeater(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.M == node.N, $"Unexpected M={node.M} == N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(!analysis.MayBacktrack(node.Child(0)), $"Expected non-backtracking node {node.Kind}"); // Ensure every iteration of the loop sees a consistent value. TransferSliceStaticPosToPos(); // Loop M==N times to match the child exactly that numbers of times. Label condition = DefineLabel(); Label body = DefineLabel(); // for (int i = 0; ...) using RentedLocalBuilder i = RentInt32Local(); Ldc(0); Stloc(i); BrFar(condition); MarkLabel(body); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // make sure static the static position remains at 0 for subsequent constructs // for (...; ...; i++) Ldloc(i); Ldc(1); Add(); Stloc(i); // for (...; i < node.M; ...) MarkLabel(condition); Ldloc(i); Ldc(node.M); BltFar(body); } void EmitLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); Label originalDoneLabel = doneLabel; LocalBuilder startingPos = DeclareInt32(); LocalBuilder iterationCount = DeclareInt32(); Label body = DefineLabel(); Label endLoop = DefineLabel(); // iterationCount = 0; // startingPos = 0; Ldc(0); Stloc(iterationCount); Ldc(0); Stloc(startingPos); // Iteration body MarkLabel(body); EmitTimeoutCheck(); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackResizeIfNeeded(3); if (expressionHasCaptures) { // base.runstack[stackpos++] = base.Crawlpos(); EmitStackPush(() => { Ldthis(); Call(s_crawlposMethod); }); } EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(pos)); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. // iterationCount++; Ldloc(iterationCount); Ldc(1); Add(); Stloc(iterationCount); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. Label iterationFailedLabel = DefineLabel(); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 bool childBacktracks = doneLabel != iterationFailedLabel; // Loop condition. Continue iterating greedily if we've not yet reached the maximum. We also need to stop // iterating if the iteration matched empty and we already hit the minimum number of iterations. Otherwise, // we've matched as many iterations as we can with this configuration. Jump to what comes after the loop. switch ((minIterations > 0, maxIterations == int.MaxValue)) { case (true, true): // if (pos != startingPos || iterationCount < minIterations) goto body; // goto endLoop; Ldloc(pos); Ldloc(startingPos); BneFar(body); Ldloc(iterationCount); Ldc(minIterations); BltFar(body); BrFar(endLoop); break; case (true, false): // if ((pos != startingPos || iterationCount < minIterations) && iterationCount < maxIterations) goto body; // goto endLoop; Ldloc(iterationCount); Ldc(maxIterations); BgeFar(endLoop); Ldloc(pos); Ldloc(startingPos); BneFar(body); Ldloc(iterationCount); Ldc(minIterations); BltFar(body); BrFar(endLoop); break; case (false, true): // if (pos != startingPos) goto body; // goto endLoop; Ldloc(pos); Ldloc(startingPos); BneFar(body); BrFar(endLoop); break; case (false, false): // if (pos == startingPos || iterationCount >= maxIterations) goto endLoop; // goto body; Ldloc(pos); Ldloc(startingPos); BeqFar(endLoop); Ldloc(iterationCount); Ldc(maxIterations); BgeFar(endLoop); BrFar(body); break; } // Now handle what happens when an iteration fails, which could be an initial failure or it // could be while backtracking. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel); // iterationCount--; Ldloc(iterationCount); Ldc(1); Sub(); Stloc(iterationCount); // if (iterationCount < 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BltFar(originalDoneLabel); // pos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(pos); EmitStackPop(); Stloc(startingPos); if (expressionHasCaptures) { // int poppedCrawlPos = base.runstack[--stackpos]; // while (base.Crawlpos() > poppedCrawlPos) base.Uncapture(); using RentedLocalBuilder poppedCrawlPos = RentInt32Local(); EmitStackPop(); Stloc(poppedCrawlPos); EmitUncaptureUntil(poppedCrawlPos); } SliceInputSpan(); if (minIterations > 0) { // if (iterationCount == 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); // if (iterationCount < minIterations) goto doneLabel/originalDoneLabel; Ldloc(iterationCount); Ldc(minIterations); BltFar(childBacktracks ? doneLabel : originalDoneLabel); } if (isAtomic) { doneLabel = originalDoneLabel; MarkLabel(endLoop); } else { if (childBacktracks) { // goto endLoop; BrFar(endLoop); // Backtrack: Label backtrack = DefineLabel(); MarkLabel(backtrack); // if (iterationCount == 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; } MarkLabel(endLoop); if (node.IsInLoop()) { // Store the loop's state EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(iterationCount)); // Skip past the backtracking section // goto backtrackingEnd; Label backtrackingEnd = DefineLabel(); BrFar(backtrackingEnd); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // iterationCount = base.runstack[--runstack]; // startingPos = base.runstack[--runstack]; EmitStackPop(); Stloc(iterationCount); EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } } void EmitStackResizeIfNeeded(int count) { Debug.Assert(count >= 1); // if (stackpos >= base.runstack!.Length - (count - 1)) // { // Array.Resize(ref base.runstack, base.runstack.Length * 2); // } Label skipResize = DefineLabel(); Ldloc(stackpos); Ldthisfld(s_runstackField); Ldlen(); if (count > 1) { Ldc(count - 1); Sub(); } Blt(skipResize); Ldthis(); _ilg!.Emit(OpCodes.Ldflda, s_runstackField); Ldthisfld(s_runstackField); Ldlen(); Ldc(2); Mul(); Call(s_arrayResize); MarkLabel(skipResize); } void EmitStackPush(Action load) { // base.runstack[stackpos] = load(); Ldthisfld(s_runstackField); Ldloc(stackpos); load(); StelemI4(); // stackpos++; Ldloc(stackpos); Ldc(1); Add(); Stloc(stackpos); } void EmitStackPop() { // ... = base.runstack[--stackpos]; Ldthisfld(s_runstackField); Ldloc(stackpos); Ldc(1); Sub(); Stloc(stackpos); Ldloc(stackpos); LdelemI4(); } } protected void EmitScan(RegexOptions options, DynamicMethod tryFindNextStartingPositionMethod, DynamicMethod tryMatchAtCurrentPositionMethod) { bool rtl = (options & RegexOptions.RightToLeft) != 0; Label returnLabel = DefineLabel(); // while (TryFindNextPossibleStartingPosition(text)) Label whileLoopBody = DefineLabel(); MarkLabel(whileLoopBody); Ldthis(); Ldarg_1(); Call(tryFindNextStartingPositionMethod); BrfalseFar(returnLabel); if (_hasTimeout) { // CheckTimeout(); Ldthis(); Call(s_checkTimeoutMethod); } // if (TryMatchAtCurrentPosition(text) || runtextpos == text.length) // or == 0 for rtl // return; Ldthis(); Ldarg_1(); Call(tryMatchAtCurrentPositionMethod); BrtrueFar(returnLabel); Ldthisfld(s_runtextposField); if (!rtl) { Ldarga_s(1); Call(s_spanGetLengthMethod); } else { Ldc(0); } Ceq(); BrtrueFar(returnLabel); // runtextpos += 1 // or -1 for rtl Ldthis(); Ldthisfld(s_runtextposField); Ldc(!rtl ? 1 : -1); Add(); Stfld(s_runtextposField); // End loop body. BrFar(whileLoopBody); // return; MarkLabel(returnLabel); Ret(); } private void InitializeCultureForTryMatchAtCurrentPositionIfNecessary(AnalysisResults analysis) { _textInfo = null; if (analysis.HasIgnoreCase && (_options & RegexOptions.CultureInvariant) == 0) { // cache CultureInfo in local variable which saves excessive thread local storage accesses _textInfo = DeclareTextInfo(); InitLocalCultureInfo(); } } /// <summary>Emits a a check for whether the character is in the specified character class.</summary> /// <remarks>The character to be checked has already been loaded onto the stack.</remarks> private void EmitMatchCharacterClass(string charClass, bool caseInsensitive) { // We need to perform the equivalent of calling RegexRunner.CharInClass(ch, charClass), // but that call is relatively expensive. Before we fall back to it, we try to optimize // some common cases for which we can do much better, such as known character classes // for which we can call a dedicated method, or a fast-path for ASCII using a lookup table. // First, see if the char class is a built-in one for which there's a better function // we can just call directly. Everything in this section must work correctly for both // case-sensitive and case-insensitive modes, regardless of culture. switch (charClass) { case RegexCharClass.AnyClass: // true Pop(); Ldc(1); return; case RegexCharClass.DigitClass: // char.IsDigit(ch) Call(s_charIsDigitMethod); return; case RegexCharClass.NotDigitClass: // !char.IsDigit(ch) Call(s_charIsDigitMethod); Ldc(0); Ceq(); return; case RegexCharClass.SpaceClass: // char.IsWhiteSpace(ch) Call(s_charIsWhiteSpaceMethod); return; case RegexCharClass.NotSpaceClass: // !char.IsWhiteSpace(ch) Call(s_charIsWhiteSpaceMethod); Ldc(0); Ceq(); return; case RegexCharClass.WordClass: // RegexRunner.IsWordChar(ch) Call(s_isWordCharMethod); return; case RegexCharClass.NotWordClass: // !RegexRunner.IsWordChar(ch) Call(s_isWordCharMethod); Ldc(0); Ceq(); return; } // If we're meant to be doing a case-insensitive lookup, and if we're not using the invariant culture, // lowercase the input. If we're using the invariant culture, we may still end up calling ToLower later // on, but we may also be able to avoid it, in particular in the case of our lookup table, where we can // generate the lookup table already factoring in the invariant case sensitivity. There are multiple // special-code paths between here and the lookup table, but we only take those if invariant is false; // if it were true, they'd need to use CallToLower(). bool invariant = false; if (caseInsensitive) { invariant = UseToLowerInvariant; if (!invariant) { CallToLower(); } } // Next, handle simple sets of one range, e.g. [A-Z], [0-9], etc. This includes some built-in classes, like ECMADigitClass. if (!invariant && RegexCharClass.TryGetSingleRange(charClass, out char lowInclusive, out char highInclusive)) { if (lowInclusive == highInclusive) { // ch == charClass[3] Ldc(lowInclusive); Ceq(); } else { // (uint)ch - lowInclusive < highInclusive - lowInclusive + 1 Ldc(lowInclusive); Sub(); Ldc(highInclusive - lowInclusive + 1); CltUn(); } // Negate the answer if the negation flag was set if (RegexCharClass.IsNegated(charClass)) { Ldc(0); Ceq(); } return; } // Next if the character class contains nothing but a single Unicode category, we can calle char.GetUnicodeCategory and // compare against it. It has a fast-lookup path for ASCII, so is as good or better than any lookup we'd generate (plus // we get smaller code), and it's what we'd do for the fallback (which we get to avoid generating) as part of CharInClass. if (!invariant && RegexCharClass.TryGetSingleUnicodeCategory(charClass, out UnicodeCategory category, out bool negated)) { // char.GetUnicodeCategory(ch) == category Call(s_charGetUnicodeInfo); Ldc((int)category); Ceq(); if (negated) { Ldc(0); Ceq(); } return; } // All checks after this point require reading the input character multiple times, // so we store it into a temporary local. using RentedLocalBuilder tempLocal = RentInt32Local(); Stloc(tempLocal); // Next, if there's only 2 or 3 chars in the set (fairly common due to the sets we create for prefixes), // it's cheaper and smaller to compare against each than it is to use a lookup table. if (!invariant && !RegexCharClass.IsNegated(charClass)) { Span<char> setChars = stackalloc char[3]; int numChars = RegexCharClass.GetSetChars(charClass, setChars); if (numChars is 2 or 3) { if (RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out int mask)) // special-case common case of an upper and lowercase ASCII letter combination { // ((ch | mask) == setChars[1]) Ldloc(tempLocal); Ldc(mask); Or(); Ldc(setChars[1] | mask); Ceq(); } else { // (ch == setChars[0]) | (ch == setChars[1]) Ldloc(tempLocal); Ldc(setChars[0]); Ceq(); Ldloc(tempLocal); Ldc(setChars[1]); Ceq(); Or(); } // | (ch == setChars[2]) if (numChars == 3) { Ldloc(tempLocal); Ldc(setChars[2]); Ceq(); Or(); } return; } } using RentedLocalBuilder resultLocal = RentInt32Local(); // Analyze the character set more to determine what code to generate. RegexCharClass.CharClassAnalysisResults analysis = RegexCharClass.Analyze(charClass); // Helper method that emits a call to RegexRunner.CharInClass(ch{.ToLowerInvariant()}, charClass) void EmitCharInClass() { Ldloc(tempLocal); if (invariant) { CallToLower(); } Ldstr(charClass); Call(s_charInClassMethod); Stloc(resultLocal); } Label doneLabel = DefineLabel(); Label comparisonLabel = DefineLabel(); if (!invariant) // if we're being asked to do a case insensitive, invariant comparison, use the lookup table { if (analysis.ContainsNoAscii) { // We determined that the character class contains only non-ASCII, // for example if the class were [\p{IsGreek}\p{IsGreekExtended}], which is // the same as [\u0370-\u03FF\u1F00-1FFF]. (In the future, we could possibly // extend the analysis to produce a known lower-bound and compare against // that rather than always using 128 as the pivot point.) // ch >= 128 && RegexRunner.CharInClass(ch, "...") Ldloc(tempLocal); Ldc(128); Blt(comparisonLabel); EmitCharInClass(); Br(doneLabel); MarkLabel(comparisonLabel); Ldc(0); Stloc(resultLocal); MarkLabel(doneLabel); Ldloc(resultLocal); return; } if (analysis.AllAsciiContained) { // We determined that every ASCII character is in the class, for example // if the class were the negated example from case 1 above: // [^\p{IsGreek}\p{IsGreekExtended}]. // ch < 128 || RegexRunner.CharInClass(ch, "...") Ldloc(tempLocal); Ldc(128); Blt(comparisonLabel); EmitCharInClass(); Br(doneLabel); MarkLabel(comparisonLabel); Ldc(1); Stloc(resultLocal); MarkLabel(doneLabel); Ldloc(resultLocal); return; } } // Now, our big hammer is to generate a lookup table that lets us quickly index by character into a yes/no // answer as to whether the character is in the target character class. However, we don't want to store // a lookup table for every possible character for every character class in the regular expression; at one // bit for each of 65K characters, that would be an 8K bitmap per character class. Instead, we handle the // common case of ASCII input via such a lookup table, which at one bit for each of 128 characters is only // 16 bytes per character class. We of course still need to be able to handle inputs that aren't ASCII, so // we check the input against 128, and have a fallback if the input is >= to it. Determining the right // fallback could itself be expensive. For example, if it's possible that a value >= 128 could match the // character class, we output a call to RegexRunner.CharInClass, but we don't want to have to enumerate the // entire character class evaluating every character against it, just to determine whether it's a match. // Instead, we employ some quick heuristics that will always ensure we provide a correct answer even if // we could have sometimes generated better code to give that answer. // Generate the lookup table to store 128 answers as bits. We use a const string instead of a byte[] / static // data property because it lets IL emit handle all the details for us. string bitVectorString = string.Create(8, (charClass, invariant), static (dest, state) => // String length is 8 chars == 16 bytes == 128 bits. { for (int i = 0; i < 128; i++) { char c = (char)i; bool isSet = state.invariant ? RegexCharClass.CharInClass(char.ToLowerInvariant(c), state.charClass) : RegexCharClass.CharInClass(c, state.charClass); if (isSet) { dest[i >> 4] |= (char)(1 << (i & 0xF)); } } }); // We determined that the character class may contain ASCII, so we // output the lookup against the lookup table. // ch < 128 ? (bitVectorString[ch >> 4] & (1 << (ch & 0xF))) != 0 : Ldloc(tempLocal); Ldc(128); Bge(comparisonLabel); Ldstr(bitVectorString); Ldloc(tempLocal); Ldc(4); Shr(); Call(s_stringGetCharsMethod); Ldc(1); Ldloc(tempLocal); Ldc(15); And(); Ldc(31); And(); Shl(); And(); Ldc(0); CgtUn(); Stloc(resultLocal); Br(doneLabel); MarkLabel(comparisonLabel); if (analysis.ContainsOnlyAscii) { // We know that all inputs that could match are ASCII, for example if the // character class were [A-Za-z0-9], so since the ch is now known to be >= 128, we // can just fail the comparison. Ldc(0); Stloc(resultLocal); } else if (analysis.AllNonAsciiContained) { // We know that all non-ASCII inputs match, for example if the character // class were [^\r\n], so since we just determined the ch to be >= 128, we can just // give back success. Ldc(1); Stloc(resultLocal); } else { // We know that the whole class wasn't ASCII, and we don't know anything about the non-ASCII // characters other than that some might be included, for example if the character class // were [\w\d], so since ch >= 128, we need to fall back to calling CharInClass. EmitCharInClass(); } MarkLabel(doneLabel); Ldloc(resultLocal); } /// <summary>Emits a timeout check.</summary> private void EmitTimeoutCheck() { if (!_hasTimeout) { return; } Debug.Assert(_loopTimeoutCounter != null); // Increment counter for each loop iteration. Ldloc(_loopTimeoutCounter); Ldc(1); Add(); Stloc(_loopTimeoutCounter); // Emit code to check the timeout every 2048th iteration. Label label = DefineLabel(); Ldloc(_loopTimeoutCounter); Ldc(LoopTimeoutCheckCount); RemUn(); Brtrue(label); Ldthis(); Call(s_checkTimeoutMethod); MarkLabel(label); } } }
1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Threading; namespace System.Text.RegularExpressions { /// <summary>Represents a regex subexpression.</summary> internal sealed class RegexNode { /// <summary>empty bit from the node's options to store data on whether a node contains captures</summary> internal const RegexOptions HasCapturesFlag = (RegexOptions)(1 << 31); /// <summary>Arbitrary number of repetitions of the same character when we'd prefer to represent that as a repeater of that character rather than a string.</summary> internal const int MultiVsRepeaterLimit = 64; /// <summary>The node's children.</summary> /// <remarks>null if no children, a <see cref="RegexNode"/> if one child, or a <see cref="List{RegexNode}"/> if multiple children.</remarks> private object? Children; /// <summary>The kind of expression represented by this node.</summary> public RegexNodeKind Kind { get; private set; } /// <summary>A string associated with the node.</summary> /// <remarks>For a <see cref="RegexNodeKind.Multi"/>, this is the string from the expression. For an <see cref="IsSetFamily"/> node, this is the character class string from <see cref="RegexCharClass"/>.</remarks> public string? Str { get; private set; } /// <summary>The character associated with the node.</summary> /// <remarks>For a <see cref="IsOneFamily"/> or <see cref="IsNotoneFamily"/> node, the character from the expression.</remarks> public char Ch { get; private set; } /// <summary>The minimum number of iterations for a loop, or the capture group number for a capture or backreference.</summary> /// <remarks>No minimum is represented by 0. No capture group is represented by -1.</remarks> public int M { get; private set; } /// <summary>The maximum number of iterations for a loop, or the uncapture group number for a balancing group.</summary> /// <remarks>No upper bound is represented by <see cref="int.MaxValue"/>. No capture group is represented by -1.</remarks> public int N { get; private set; } /// <summary>The options associated with the node.</summary> public RegexOptions Options; /// <summary>The node's parent node in the tree.</summary> /// <remarks> /// During parsing, top-level nodes are also stacked onto a parse stack (a stack of trees) using <see cref="Parent"/>. /// After parsing, <see cref="Parent"/> is the node in the tree that has this node as or in <see cref="Children"/>. /// </remarks> public RegexNode? Parent; public RegexNode(RegexNodeKind kind, RegexOptions options) { Kind = kind; Options = options; } public RegexNode(RegexNodeKind kind, RegexOptions options, char ch) { Kind = kind; Options = options; Ch = ch; } public RegexNode(RegexNodeKind kind, RegexOptions options, string str) { Kind = kind; Options = options; Str = str; } public RegexNode(RegexNodeKind kind, RegexOptions options, int m) { Kind = kind; Options = options; M = m; } public RegexNode(RegexNodeKind kind, RegexOptions options, int m, int n) { Kind = kind; Options = options; M = m; N = n; } /// <summary>Creates a RegexNode representing a single character.</summary> /// <param name="ch">The character.</param> /// <param name="options">The node's options.</param> /// <param name="culture">The culture to use to perform any required transformations.</param> /// <returns>The created RegexNode. This might be a RegexNode.One or a RegexNode.Set.</returns> public static RegexNode CreateOneWithCaseConversion(char ch, RegexOptions options, CultureInfo? culture) { // If the options specify case-insensitivity, we try to create a node that fully encapsulates that. if ((options & RegexOptions.IgnoreCase) != 0) { Debug.Assert(culture is not null); // If the character is part of a Unicode category that doesn't participate in case conversion, // we can simply strip out the IgnoreCase option and make the node case-sensitive. if (!RegexCharClass.ParticipatesInCaseConversion(ch)) { return new RegexNode(RegexNodeKind.One, options & ~RegexOptions.IgnoreCase, ch); } // Create a set for the character, trying to include all case-insensitive equivalent characters. // If it's successful in doing so, resultIsCaseInsensitive will be false and we can strip // out RegexOptions.IgnoreCase as part of creating the set. string stringSet = RegexCharClass.OneToStringClass(ch, culture, out bool resultIsCaseInsensitive); if (!resultIsCaseInsensitive) { return new RegexNode(RegexNodeKind.Set, options & ~RegexOptions.IgnoreCase, stringSet); } // Otherwise, until we can get rid of ToLower usage at match time entirely (https://github.com/dotnet/runtime/issues/61048), // lowercase the character and proceed to create an IgnoreCase One node. ch = culture.TextInfo.ToLower(ch); } // Create a One node for the character. return new RegexNode(RegexNodeKind.One, options, ch); } /// <summary>Reverses all children of a concatenation when in RightToLeft mode.</summary> public RegexNode ReverseConcatenationIfRightToLeft() { if ((Options & RegexOptions.RightToLeft) != 0 && Kind == RegexNodeKind.Concatenate && ChildCount() > 1) { ((List<RegexNode>)Children!).Reverse(); } return this; } /// <summary> /// Pass type as OneLazy or OneLoop /// </summary> private void MakeRep(RegexNodeKind kind, int min, int max) { Kind += kind - RegexNodeKind.One; M = min; N = max; } private void MakeLoopAtomic() { switch (Kind) { case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop: // For loops, we simply change the Type to the atomic variant. // Atomic greedy loops should consume as many values as they can. Kind += RegexNodeKind.Oneloopatomic - RegexNodeKind.Oneloop; break; case RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy: // For lazy, we not only change the Type, we also lower the max number of iterations // to the minimum number of iterations, creating a repeater, as they should end up // matching as little as possible. Kind += RegexNodeKind.Oneloopatomic - RegexNodeKind.Onelazy; N = M; if (N == 0) { // If moving the max to be the same as the min dropped it to 0, there's no // work to be done for this node, and we can make it Empty. Kind = RegexNodeKind.Empty; Str = null; Ch = '\0'; } else if (Kind == RegexNodeKind.Oneloopatomic && N is >= 2 and <= MultiVsRepeaterLimit) { // If this is now a One repeater with a small enough length, // make it a Multi instead, as they're better optimized down the line. Kind = RegexNodeKind.Multi; Str = new string(Ch, N); Ch = '\0'; M = N = 0; } break; default: Debug.Fail($"Unexpected type: {Kind}"); break; } } #if DEBUG /// <summary>Validate invariants the rest of the implementation relies on for processing fully-built trees.</summary> [Conditional("DEBUG")] private void ValidateFinalTreeInvariants() { Debug.Assert(Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); var toExamine = new Stack<RegexNode>(); toExamine.Push(this); while (toExamine.Count > 0) { RegexNode node = toExamine.Pop(); // Add all children to be examined int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { RegexNode child = node.Child(i); Debug.Assert(child.Parent == node, $"{child.Describe()} missing reference to parent {node.Describe()}"); toExamine.Push(child); } // Validate that we never see certain node types. Debug.Assert(Kind != RegexNodeKind.Group, "All Group nodes should have been removed."); // Validate node types and expected child counts. switch (node.Kind) { case RegexNodeKind.Group: Debug.Fail("All Group nodes should have been removed."); break; case RegexNodeKind.Beginning: case RegexNodeKind.Bol: case RegexNodeKind.Boundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.Empty: case RegexNodeKind.End: case RegexNodeKind.EndZ: case RegexNodeKind.Eol: case RegexNodeKind.Multi: case RegexNodeKind.NonBoundary: case RegexNodeKind.NonECMABoundary: case RegexNodeKind.Nothing: case RegexNodeKind.Notone: case RegexNodeKind.Notonelazy: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.One: case RegexNodeKind.Onelazy: case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Backreference: case RegexNodeKind.Set: case RegexNodeKind.Setlazy: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Start: case RegexNodeKind.UpdateBumpalong: Debug.Assert(childCount == 0, $"Expected zero children for {node.Kind}, got {childCount}."); break; case RegexNodeKind.Atomic: case RegexNodeKind.Capture: case RegexNodeKind.Lazyloop: case RegexNodeKind.Loop: case RegexNodeKind.NegativeLookaround: case RegexNodeKind.PositiveLookaround: Debug.Assert(childCount == 1, $"Expected one and only one child for {node.Kind}, got {childCount}."); break; case RegexNodeKind.BackreferenceConditional: Debug.Assert(childCount == 2, $"Expected two children for {node.Kind}, got {childCount}"); break; case RegexNodeKind.ExpressionConditional: Debug.Assert(childCount == 3, $"Expected three children for {node.Kind}, got {childCount}"); break; case RegexNodeKind.Concatenate: case RegexNodeKind.Alternate: Debug.Assert(childCount >= 2, $"Expected at least two children for {node.Kind}, got {childCount}."); break; default: Debug.Fail($"Unexpected node type: {node.Kind}"); break; } // Validate node configuration. switch (node.Kind) { case RegexNodeKind.Multi: Debug.Assert(node.Str is not null, "Expect non-null multi string"); Debug.Assert(node.Str.Length >= 2, $"Expected {node.Str} to be at least two characters"); break; case RegexNodeKind.Set: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Setlazy: Debug.Assert(!string.IsNullOrEmpty(node.Str), $"Expected non-null, non-empty string for {node.Kind}."); break; default: Debug.Assert(node.Str is null, $"Expected null string for {node.Kind}, got \"{node.Str}\"."); break; } } } #endif /// <summary>Performs additional optimizations on an entire tree prior to being used.</summary> /// <remarks> /// Some optimizations are performed by the parser while parsing, and others are performed /// as nodes are being added to the tree. The optimizations here expect the tree to be fully /// formed, as they inspect relationships between nodes that may not have been in place as /// individual nodes were being processed/added to the tree. /// </remarks> internal RegexNode FinalOptimize() { RegexNode rootNode = this; Debug.Assert(rootNode.Kind == RegexNodeKind.Capture); Debug.Assert(rootNode.Parent is null); Debug.Assert(rootNode.ChildCount() == 1); // Only apply optimization when LTR to avoid needing additional code for the much rarer RTL case. // Also only apply these optimizations when not using NonBacktracking, as these optimizations are // all about avoiding things that are impactful for the backtracking engines but nops for non-backtracking. if ((Options & (RegexOptions.RightToLeft | RegexOptions.NonBacktracking)) == 0) { // Optimization: eliminate backtracking for loops. // For any single-character loop (Oneloop, Notoneloop, Setloop), see if we can automatically convert // that into its atomic counterpart (Oneloopatomic, Notoneloopatomic, Setloopatomic) based on what // comes after it in the expression tree. rootNode.FindAndMakeLoopsAtomic(); // Optimization: backtracking removal at expression end. // If we find backtracking construct at the end of the regex, we can instead make it non-backtracking, // since nothing would ever backtrack into it anyway. Doing this then makes the construct available // to implementations that don't support backtracking. rootNode.EliminateEndingBacktracking(); // Optimization: unnecessary re-processing of starting loops. // If an expression is guaranteed to begin with a single-character unbounded loop that isn't part of an alternation (in which case it // wouldn't be guaranteed to be at the beginning) or a capture (in which case a back reference could be influenced by its length), then we // can update the tree with a temporary node to indicate that the implementation should use that node's ending position in the input text // as the next starting position at which to start the next match. This avoids redoing matches we've already performed, e.g. matching // "\[email protected]" against "is this a valid [email protected]", the \w+ will initially match the "is" and then will fail to match the "@". // Rather than bumping the scan loop by 1 and trying again to match at the "s", we can instead start at the " ". For functional correctness // we can only consider unbounded loops, as to be able to start at the end of the loop we need the loop to have consumed all possible matches; // otherwise, you could end up with a pattern like "a{1,3}b" matching against "aaaabc", which should match, but if we pre-emptively stop consuming // after the first three a's and re-start from that position, we'll end up failing the match even though it should have succeeded. We can also // apply this optimization to non-atomic loops: even though backtracking could be necessary, such backtracking would be handled within the processing // of a single starting position. Lazy loops similarly benefit, as a failed match will result in exploring the exact same search space as with // a greedy loop, just in the opposite order (and a successful match will overwrite the bumpalong position); we need to avoid atomic lazy loops, // however, as they will only end up as a repeater for the minimum length and thus will effectively end up with a non-infinite upper bound, which // we've already outlined is problematic. { RegexNode node = rootNode.Child(0); // skip implicit root capture node bool atomicByAncestry = true; // the root is implicitly atomic because nothing comes after it (same for the implicit root capture) while (true) { switch (node.Kind) { case RegexNodeKind.Atomic: node = node.Child(0); continue; case RegexNodeKind.Concatenate: atomicByAncestry = false; node = node.Child(0); continue; case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when node.N == int.MaxValue: case RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy when node.N == int.MaxValue && !atomicByAncestry: if (node.Parent is { Kind: RegexNodeKind.Concatenate } parent) { parent.InsertChild(1, new RegexNode(RegexNodeKind.UpdateBumpalong, node.Options)); } break; } break; } } } // Done optimizing. Return the final tree. #if DEBUG rootNode.ValidateFinalTreeInvariants(); #endif return rootNode; } /// <summary>Converts nodes at the end of the node tree to be atomic.</summary> /// <remarks> /// The correctness of this optimization depends on nothing being able to backtrack into /// the provided node. That means it must be at the root of the overall expression, or /// it must be an Atomic node that nothing will backtrack into by the very nature of Atomic. /// </remarks> private void EliminateEndingBacktracking() { if (!StackHelper.TryEnsureSufficientExecutionStack() || (Options & (RegexOptions.RightToLeft | RegexOptions.NonBacktracking)) != 0) { // If we can't recur further, just stop optimizing. // We haven't done the work to validate this is correct for RTL. // And NonBacktracking doesn't support atomic groups and doesn't have backtracking to be eliminated. return; } // Walk the tree starting from the current node. RegexNode node = this; while (true) { switch (node.Kind) { // {One/Notone/Set}loops can be upgraded to {One/Notone/Set}loopatomic nodes, e.g. [abc]* => (?>[abc]*). // And {One/Notone/Set}lazys can similarly be upgraded to be atomic, which really makes them into repeaters // or even empty nodes. case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop: case RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy: node.MakeLoopAtomic(); break; // Just because a particular node is atomic doesn't mean all its descendants are. // Process them as well. Lookarounds are implicitly atomic. case RegexNodeKind.Atomic: case RegexNodeKind.PositiveLookaround: case RegexNodeKind.NegativeLookaround: node = node.Child(0); continue; // For Capture and Concatenate, we just recur into their last child (only child in the case // of Capture). However, if the child is an alternation or loop, we can also make the // node itself atomic by wrapping it in an Atomic node. Since we later check to see whether a // node is atomic based on its parent or grandparent, we don't bother wrapping such a node in // an Atomic one if its grandparent is already Atomic. // e.g. [xyz](?:abc|def) => [xyz](?>abc|def) case RegexNodeKind.Capture: case RegexNodeKind.Concatenate: RegexNode existingChild = node.Child(node.ChildCount() - 1); if ((existingChild.Kind is RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional or RegexNodeKind.Loop or RegexNodeKind.Lazyloop) && (node.Parent is null || node.Parent.Kind != RegexNodeKind.Atomic)) // validate grandparent isn't atomic { var atomic = new RegexNode(RegexNodeKind.Atomic, existingChild.Options); atomic.AddChild(existingChild); node.ReplaceChild(node.ChildCount() - 1, atomic); } node = existingChild; continue; // For alternate, we can recur into each branch separately. We use this iteration for the first branch. // Conditionals are just like alternations in this regard. // e.g. abc*|def* => ab(?>c*)|de(?>f*) case RegexNodeKind.Alternate: case RegexNodeKind.BackreferenceConditional: case RegexNodeKind.ExpressionConditional: { int branches = node.ChildCount(); for (int i = 1; i < branches; i++) { node.Child(i).EliminateEndingBacktracking(); } if (node.Kind != RegexNodeKind.ExpressionConditional) // ReduceExpressionConditional will have already applied ending backtracking removal { node = node.Child(0); continue; } } break; // For {Lazy}Loop, we search to see if there's a viable last expression, and iff there // is we recur into processing it. Also, as with the single-char lazy loops, LazyLoop // can have its max iteration count dropped to its min iteration count, as there's no // reason for it to match more than the minimal at the end; that in turn makes it a // repeater, which results in better code generation. // e.g. (?:abc*)* => (?:ab(?>c*))* // e.g. (abc*?)+? => (ab){1} case RegexNodeKind.Lazyloop: node.N = node.M; goto case RegexNodeKind.Loop; case RegexNodeKind.Loop: { if (node.N == 1) { // If the loop has a max iteration count of 1 (e.g. it's an optional node), // there's no possibility for conflict between multiple iterations, so // we can process it. node = node.Child(0); continue; } RegexNode? loopDescendent = node.FindLastExpressionInLoopForAutoAtomic(); if (loopDescendent != null) { node = loopDescendent; continue; // loop around to process node } } break; } break; } } /// <summary> /// Removes redundant nodes from the subtree, and returns an optimized subtree. /// </summary> internal RegexNode Reduce() { // TODO: https://github.com/dotnet/runtime/issues/61048 // As part of overhauling IgnoreCase handling, the parser shouldn't produce any nodes other than Backreference // that ever have IgnoreCase set on them. For now, though, remove IgnoreCase from any nodes for which it // has no behavioral effect. switch (Kind) { default: // No effect Options &= ~RegexOptions.IgnoreCase; break; case RegexNodeKind.One or RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notone or RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Set or RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic: case RegexNodeKind.Multi: case RegexNodeKind.Backreference: // Still meaningful break; } return Kind switch { RegexNodeKind.Alternate => ReduceAlternation(), RegexNodeKind.Atomic => ReduceAtomic(), RegexNodeKind.Concatenate => ReduceConcatenation(), RegexNodeKind.Group => ReduceGroup(), RegexNodeKind.Loop or RegexNodeKind.Lazyloop => ReduceLoops(), RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround => ReduceLookaround(), RegexNodeKind.Set or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy => ReduceSet(), RegexNodeKind.ExpressionConditional => ReduceExpressionConditional(), RegexNodeKind.BackreferenceConditional => ReduceBackreferenceConditional(), _ => this, }; } /// <summary>Remove an unnecessary Concatenation or Alternation node</summary> /// <remarks> /// Simple optimization for a concatenation or alternation: /// - if the node has only one child, use it instead /// - if the node has zero children, turn it into an empty with Nothing for an alternation or Empty for a concatenation /// </remarks> private RegexNode ReplaceNodeIfUnnecessary() { Debug.Assert(Kind is RegexNodeKind.Alternate or RegexNodeKind.Concatenate); return ChildCount() switch { 0 => new RegexNode(Kind == RegexNodeKind.Alternate ? RegexNodeKind.Nothing : RegexNodeKind.Empty, Options), 1 => Child(0), _ => this, }; } /// <summary>Remove all non-capturing groups.</summary> /// <remark> /// Simple optimization: once parsed into a tree, non-capturing groups /// serve no function, so strip them out. /// e.g. (?:(?:(?:abc))) => abc /// </remark> private RegexNode ReduceGroup() { Debug.Assert(Kind == RegexNodeKind.Group); RegexNode u = this; while (u.Kind == RegexNodeKind.Group) { Debug.Assert(u.ChildCount() == 1); u = u.Child(0); } return u; } /// <summary> /// Remove unnecessary atomic nodes, and make appropriate descendents of the atomic node themselves atomic. /// </summary> /// <remarks> /// e.g. (?>(?>(?>a*))) => (?>a*) /// e.g. (?>(abc*)*) => (?>(abc(?>c*))*) /// </remarks> private RegexNode ReduceAtomic() { // RegexOptions.NonBacktracking doesn't support atomic groups, so when that option // is set we don't want to create atomic groups where they weren't explicitly authored. if ((Options & RegexOptions.NonBacktracking) != 0) { return this; } Debug.Assert(Kind == RegexNodeKind.Atomic); Debug.Assert(ChildCount() == 1); RegexNode atomic = this; RegexNode child = Child(0); while (child.Kind == RegexNodeKind.Atomic) { atomic = child; child = atomic.Child(0); } switch (child.Kind) { // If the child is empty/nothing, there's nothing to be made atomic so the Atomic // node can simply be removed. case RegexNodeKind.Empty: case RegexNodeKind.Nothing: return child; // If the child is already atomic, we can just remove the atomic node. case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: return child; // If an atomic subexpression contains only a {one/notone/set}{loop/lazy}, // change it to be an {one/notone/set}loopatomic and remove the atomic node. case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: child.MakeLoopAtomic(); return child; // Alternations have a variety of possible optimizations that can be applied // iff they're atomic. case RegexNodeKind.Alternate: if ((Options & RegexOptions.RightToLeft) == 0) { List<RegexNode>? branches = child.Children as List<RegexNode>; Debug.Assert(branches is not null && branches.Count != 0); // If an alternation is atomic and its first branch is Empty, the whole thing // is a nop, as Empty will match everything trivially, and no backtracking // into the node will be performed, making the remaining branches irrelevant. if (branches[0].Kind == RegexNodeKind.Empty) { return new RegexNode(RegexNodeKind.Empty, child.Options); } // Similarly, we can trim off any branches after an Empty, as they'll never be used. // An Empty will match anything, and thus branches after that would only be used // if we backtracked into it and advanced passed the Empty after trying the Empty... // but if the alternation is atomic, such backtracking won't happen. for (int i = 1; i < branches.Count - 1; i++) { if (branches[i].Kind == RegexNodeKind.Empty) { branches.RemoveRange(i + 1, branches.Count - (i + 1)); break; } } // If an alternation is atomic, we won't ever backtrack back into it, which // means order matters but not repetition. With backtracking, it would be incorrect // to convert an expression like "hi|there|hello" into "hi|hello|there", as doing // so could then change the order of results if we matched "hi" and then failed // based on what came after it, and both "hello" and "there" could be successful // with what came later. But without backtracking, we can reorder "hi|there|hello" // to instead be "hi|hello|there", as "hello" and "there" can't match the same text, // and once this atomic alternation has matched, we won't try another branch. This // reordering is valuable as it then enables further optimizations, e.g. // "hi|there|hello" => "hi|hello|there" => "h(?:i|ello)|there", which means we only // need to check the 'h' once in case it's not an 'h', and it's easier to employ different // code gen that, for example, switches on first character of the branches, enabling faster // choice of branch without always having to walk through each. bool reordered = false; for (int start = 0; start < branches.Count; start++) { // Get the node that may start our range. If it's a one, multi, or concat of those, proceed. RegexNode startNode = branches[start]; if (startNode.FindBranchOneOrMultiStart() is null) { continue; } // Find the contiguous range of nodes from this point that are similarly one, multi, or concat of those. int endExclusive = start + 1; while (endExclusive < branches.Count && branches[endExclusive].FindBranchOneOrMultiStart() is not null) { endExclusive++; } // If there's at least 3, there may be something to reorder (we won't reorder anything // before the starting position, and so only 2 items is considered ordered). if (endExclusive - start >= 3) { int compare = start; while (compare < endExclusive) { // Get the starting character char c = branches[compare].FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti(); // Move compare to point to the last branch that has the same starting value. while (compare < endExclusive && branches[compare].FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti() == c) { compare++; } // Compare now points to the first node that doesn't match the starting node. // If we've walked off our range, there's nothing left to reorder. if (compare < endExclusive) { // There may be something to reorder. See if there are any other nodes that begin with the same character. for (int next = compare + 1; next < endExclusive; next++) { RegexNode nextChild = branches[next]; if (nextChild.FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti() == c) { branches.RemoveAt(next); branches.Insert(compare++, nextChild); reordered = true; } } } } } // Move to the end of the range we've now explored. endExclusive is not a viable // starting position either, and the start++ for the loop will thus take us to // the next potential place to start a range. start = endExclusive; } // If anything was reordered, there may be new optimization opportunities inside // of the alternation, so reduce it again. if (reordered) { atomic.ReplaceChild(0, child); child = atomic.Child(0); } } goto default; // For everything else, try to reduce ending backtracking of the last contained expression. default: child.EliminateEndingBacktracking(); return atomic; } } /// <summary>Combine nested loops where applicable.</summary> /// <remarks> /// Nested repeaters just get multiplied with each other if they're not too lumpy. /// Other optimizations may have also resulted in {Lazy}loops directly containing /// sets, ones, and notones, in which case they can be transformed into the corresponding /// individual looping constructs. /// </remarks> private RegexNode ReduceLoops() { Debug.Assert(Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop); RegexNode u = this; RegexNodeKind kind = Kind; int min = M; int max = N; while (u.ChildCount() > 0) { RegexNode child = u.Child(0); // multiply reps of the same type only if (child.Kind != kind) { bool valid = false; if (kind == RegexNodeKind.Loop) { switch (child.Kind) { case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: valid = true; break; } } else // type == Lazyloop { switch (child.Kind) { case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: valid = true; break; } } if (!valid) { break; } } // child can be too lumpy to blur, e.g., (a {100,105}) {3} or (a {2,})? // [but things like (a {2,})+ are not too lumpy...] if (u.M == 0 && child.M > 1 || child.N < child.M * 2) { break; } u = child; if (u.M > 0) { u.M = min = ((int.MaxValue - 1) / u.M < min) ? int.MaxValue : u.M * min; } if (u.N > 0) { u.N = max = ((int.MaxValue - 1) / u.N < max) ? int.MaxValue : u.N * max; } } if (min == int.MaxValue) { return new RegexNode(RegexNodeKind.Nothing, Options); } // If the Loop or Lazyloop now only has one child node and its a Set, One, or Notone, // reduce to just Setloop/lazy, Oneloop/lazy, or Notoneloop/lazy. The parser will // generally have only produced the latter, but other reductions could have exposed // this. if (u.ChildCount() == 1) { RegexNode child = u.Child(0); switch (child.Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: child.MakeRep(u.Kind == RegexNodeKind.Lazyloop ? RegexNodeKind.Onelazy : RegexNodeKind.Oneloop, u.M, u.N); u = child; break; } } return u; } /// <summary> /// Reduces set-related nodes to simpler one-related and notone-related nodes, where applicable. /// </summary> /// <remarks> /// e.g. /// [a] => a /// [a]* => a* /// [a]*? => a*? /// (?>[a]*) => (?>a*) /// [^a] => ^a /// []* => Nothing /// </remarks> private RegexNode ReduceSet() { // Extract empty-set, one, and not-one case as special Debug.Assert(Kind is RegexNodeKind.Set or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy); Debug.Assert(!string.IsNullOrEmpty(Str)); if (RegexCharClass.IsEmpty(Str)) { Kind = RegexNodeKind.Nothing; Str = null; } else if (RegexCharClass.IsSingleton(Str)) { Ch = RegexCharClass.SingletonChar(Str); Str = null; Kind = Kind == RegexNodeKind.Set ? RegexNodeKind.One : Kind == RegexNodeKind.Setloop ? RegexNodeKind.Oneloop : Kind == RegexNodeKind.Setloopatomic ? RegexNodeKind.Oneloopatomic : RegexNodeKind.Onelazy; } else if (RegexCharClass.IsSingletonInverse(Str)) { Ch = RegexCharClass.SingletonChar(Str); Str = null; Kind = Kind == RegexNodeKind.Set ? RegexNodeKind.Notone : Kind == RegexNodeKind.Setloop ? RegexNodeKind.Notoneloop : Kind == RegexNodeKind.Setloopatomic ? RegexNodeKind.Notoneloopatomic : RegexNodeKind.Notonelazy; } return this; } /// <summary>Optimize an alternation.</summary> private RegexNode ReduceAlternation() { Debug.Assert(Kind == RegexNodeKind.Alternate); switch (ChildCount()) { case 0: return new RegexNode(RegexNodeKind.Nothing, Options); case 1: return Child(0); default: ReduceSingleLetterAndNestedAlternations(); RegexNode node = ReplaceNodeIfUnnecessary(); if (node.Kind == RegexNodeKind.Alternate) { node = ExtractCommonPrefixText(node); if (node.Kind == RegexNodeKind.Alternate) { node = ExtractCommonPrefixOneNotoneSet(node); if (node.Kind == RegexNodeKind.Alternate) { node = RemoveRedundantEmptiesAndNothings(node); } } } return node; } // This function performs two optimizations: // - Single-letter alternations can be replaced by faster set specifications // e.g. "a|b|c|def|g|h" -> "[a-c]|def|[gh]" // - Nested alternations with no intervening operators can be flattened: // e.g. "apple|(?:orange|pear)|grape" -> "apple|orange|pear|grape" void ReduceSingleLetterAndNestedAlternations() { bool wasLastSet = false; bool lastNodeCannotMerge = false; RegexOptions optionsLast = 0; RegexOptions optionsAt; int i; int j; RegexNode at; RegexNode prev; List<RegexNode> children = (List<RegexNode>)Children!; for (i = 0, j = 0; i < children.Count; i++, j++) { at = children[i]; if (j < i) children[j] = at; while (true) { if (at.Kind == RegexNodeKind.Alternate) { if (at.Children is List<RegexNode> atChildren) { for (int k = 0; k < atChildren.Count; k++) { atChildren[k].Parent = this; } children.InsertRange(i + 1, atChildren); } else { RegexNode atChild = (RegexNode)at.Children!; atChild.Parent = this; children.Insert(i + 1, atChild); } j--; } else if (at.Kind is RegexNodeKind.Set or RegexNodeKind.One) { // Cannot merge sets if L or I options differ, or if either are negated. optionsAt = at.Options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase); if (at.Kind == RegexNodeKind.Set) { if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge || !RegexCharClass.IsMergeable(at.Str!)) { wasLastSet = true; lastNodeCannotMerge = !RegexCharClass.IsMergeable(at.Str!); optionsLast = optionsAt; break; } } else if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge) { wasLastSet = true; lastNodeCannotMerge = false; optionsLast = optionsAt; break; } // The last node was a Set or a One, we're a Set or One and our options are the same. // Merge the two nodes. j--; prev = children[j]; RegexCharClass prevCharClass; if (prev.Kind == RegexNodeKind.One) { prevCharClass = new RegexCharClass(); prevCharClass.AddChar(prev.Ch); } else { prevCharClass = RegexCharClass.Parse(prev.Str!); } if (at.Kind == RegexNodeKind.One) { prevCharClass.AddChar(at.Ch); } else { RegexCharClass atCharClass = RegexCharClass.Parse(at.Str!); prevCharClass.AddCharClass(atCharClass); } prev.Kind = RegexNodeKind.Set; prev.Str = prevCharClass.ToStringClass(Options); if ((prev.Options & RegexOptions.IgnoreCase) != 0 && RegexCharClass.MakeCaseSensitiveIfPossible(prev.Str, RegexParser.GetTargetCulture(prev.Options)) is string newSetString) { prev.Str = newSetString; prev.Options &= ~RegexOptions.IgnoreCase; } } else if (at.Kind == RegexNodeKind.Nothing) { j--; } else { wasLastSet = false; lastNodeCannotMerge = false; } break; } } if (j < i) { children.RemoveRange(j, i - j); } } // This function optimizes out prefix nodes from alternation branches that are // the same across multiple contiguous branches. // e.g. \w12|\d34|\d56|\w78|\w90 => \w12|\d(?:34|56)|\w(?:78|90) static RegexNode ExtractCommonPrefixOneNotoneSet(RegexNode alternation) { Debug.Assert(alternation.Kind == RegexNodeKind.Alternate); Debug.Assert(alternation.Children is List<RegexNode> { Count: >= 2 }); var children = (List<RegexNode>)alternation.Children; // Only process left-to-right prefixes. if ((alternation.Options & RegexOptions.RightToLeft) != 0) { return alternation; } // Only handle the case where each branch is a concatenation foreach (RegexNode child in children) { if (child.Kind != RegexNodeKind.Concatenate || child.ChildCount() < 2) { return alternation; } } for (int startingIndex = 0; startingIndex < children.Count - 1; startingIndex++) { Debug.Assert(children[startingIndex].Children is List<RegexNode> { Count: >= 2 }); // Only handle the case where each branch begins with the same One, Notone, or Set (individual or loop). // Note that while we can do this for individual characters, fixed length loops, and atomic loops, doing // it for non-atomic variable length loops could change behavior as each branch could otherwise have a // different number of characters consumed by the loop based on what's after it. RegexNode required = children[startingIndex].Child(0); switch (required.Kind) { case RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set: case RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloopatomic: case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop or RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy when required.M == required.N: break; default: continue; } // Only handle the case where each branch begins with the exact same node value int endingIndex = startingIndex + 1; for (; endingIndex < children.Count; endingIndex++) { RegexNode other = children[endingIndex].Child(0); if (required.Kind != other.Kind || required.Options != other.Options || required.M != other.M || required.N != other.N || required.Ch != other.Ch || required.Str != other.Str) { break; } } if (endingIndex - startingIndex <= 1) { // Nothing to extract from this starting index. continue; } // Remove the prefix node from every branch, adding it to a new alternation var newAlternate = new RegexNode(RegexNodeKind.Alternate, alternation.Options); for (int i = startingIndex; i < endingIndex; i++) { ((List<RegexNode>)children[i].Children!).RemoveAt(0); newAlternate.AddChild(children[i]); } // If this alternation is wrapped as atomic, we need to do the same for the new alternation. if (alternation.Parent is RegexNode { Kind: RegexNodeKind.Atomic } parent) { var atomic = new RegexNode(RegexNodeKind.Atomic, alternation.Options); atomic.AddChild(newAlternate); newAlternate = atomic; } // Now create a concatenation of the prefix node with the new alternation for the combined // branches, and replace all of the branches in this alternation with that new concatenation. var newConcat = new RegexNode(RegexNodeKind.Concatenate, alternation.Options); newConcat.AddChild(required); newConcat.AddChild(newAlternate); alternation.ReplaceChild(startingIndex, newConcat); children.RemoveRange(startingIndex + 1, endingIndex - startingIndex - 1); } return alternation.ReplaceNodeIfUnnecessary(); } // Removes unnecessary Empty and Nothing nodes from the alternation. A Nothing will never // match, so it can be removed entirely, and an Empty can be removed if there's a previous // Empty in the alternation: it's an extreme case of just having a repeated branch in an // alternation, and while we don't check for all duplicates, checking for empty is easy. static RegexNode RemoveRedundantEmptiesAndNothings(RegexNode node) { Debug.Assert(node.Kind == RegexNodeKind.Alternate); Debug.Assert(node.ChildCount() >= 2); var children = (List<RegexNode>)node.Children!; int i = 0, j = 0; bool seenEmpty = false; while (i < children.Count) { RegexNode child = children[i]; switch (child.Kind) { case RegexNodeKind.Empty when !seenEmpty: seenEmpty = true; goto default; case RegexNodeKind.Empty: case RegexNodeKind.Nothing: i++; break; default: children[j] = children[i]; i++; j++; break; } } children.RemoveRange(j, children.Count - j); return node.ReplaceNodeIfUnnecessary(); } // Analyzes all the branches of the alternation for text that's identical at the beginning // of every branch. That text is then pulled out into its own one or multi node in a // concatenation with the alternation (whose branches are updated to remove that prefix). // This is valuable for a few reasons. One, it exposes potentially more text to the // expression prefix analyzer used to influence FindFirstChar. Second, it exposes more // potential alternation optimizations, e.g. if the same prefix is followed in two branches // by sets that can be merged. Third, it reduces the amount of duplicated comparisons required // if we end up backtracking into subsequent branches. // e.g. abc|ade => a(?bc|de) static RegexNode ExtractCommonPrefixText(RegexNode alternation) { Debug.Assert(alternation.Kind == RegexNodeKind.Alternate); Debug.Assert(alternation.Children is List<RegexNode> { Count: >= 2 }); var children = (List<RegexNode>)alternation.Children; // To keep things relatively simple, we currently only handle: // - Left to right (e.g. we don't process alternations in lookbehinds) // - Branches that are one or multi nodes, or that are concatenations beginning with one or multi nodes. // - All branches having the same options. // Only extract left-to-right prefixes. if ((alternation.Options & RegexOptions.RightToLeft) != 0) { return alternation; } Span<char> scratchChar = stackalloc char[1]; ReadOnlySpan<char> startingSpan = stackalloc char[0]; for (int startingIndex = 0; startingIndex < children.Count - 1; startingIndex++) { // Process the first branch to get the maximum possible common string. RegexNode? startingNode = children[startingIndex].FindBranchOneOrMultiStart(); if (startingNode is null) { return alternation; } RegexOptions startingNodeOptions = startingNode.Options; startingSpan = startingNode.Str.AsSpan(); if (startingNode.Kind == RegexNodeKind.One) { scratchChar[0] = startingNode.Ch; startingSpan = scratchChar; } Debug.Assert(startingSpan.Length > 0); // Now compare the rest of the branches against it. int endingIndex = startingIndex + 1; for (; endingIndex < children.Count; endingIndex++) { // Get the starting node of the next branch. startingNode = children[endingIndex].FindBranchOneOrMultiStart(); if (startingNode is null || startingNode.Options != startingNodeOptions) { break; } // See if the new branch's prefix has a shared prefix with the current one. // If it does, shorten to that; if it doesn't, bail. if (startingNode.Kind == RegexNodeKind.One) { if (startingSpan[0] != startingNode.Ch) { break; } if (startingSpan.Length != 1) { startingSpan = startingSpan.Slice(0, 1); } } else { Debug.Assert(startingNode.Kind == RegexNodeKind.Multi); Debug.Assert(startingNode.Str!.Length > 0); int minLength = Math.Min(startingSpan.Length, startingNode.Str.Length); int c = 0; while (c < minLength && startingSpan[c] == startingNode.Str[c]) c++; if (c == 0) { break; } startingSpan = startingSpan.Slice(0, c); } } // When we get here, we have a starting string prefix shared by all branches // in the range [startingIndex, endingIndex). if (endingIndex - startingIndex <= 1) { // There's nothing to consolidate for this starting node. continue; } // We should be able to consolidate something for the nodes in the range [startingIndex, endingIndex). Debug.Assert(startingSpan.Length > 0); // Create a new node of the form: // Concatenation(prefix, Alternation(each | node | with | prefix | removed)) // that replaces all these branches in this alternation. var prefix = startingSpan.Length == 1 ? new RegexNode(RegexNodeKind.One, startingNodeOptions, startingSpan[0]) : new RegexNode(RegexNodeKind.Multi, startingNodeOptions, startingSpan.ToString()); var newAlternate = new RegexNode(RegexNodeKind.Alternate, startingNodeOptions); for (int i = startingIndex; i < endingIndex; i++) { RegexNode branch = children[i]; ProcessOneOrMulti(branch.Kind == RegexNodeKind.Concatenate ? branch.Child(0) : branch, startingSpan); branch = branch.Reduce(); newAlternate.AddChild(branch); // Remove the starting text from the one or multi node. This may end up changing // the type of the node to be Empty if the starting text matches the node's full value. static void ProcessOneOrMulti(RegexNode node, ReadOnlySpan<char> startingSpan) { if (node.Kind == RegexNodeKind.One) { Debug.Assert(startingSpan.Length == 1); Debug.Assert(startingSpan[0] == node.Ch); node.Kind = RegexNodeKind.Empty; node.Ch = '\0'; } else { Debug.Assert(node.Kind == RegexNodeKind.Multi); Debug.Assert(node.Str.AsSpan().StartsWith(startingSpan, StringComparison.Ordinal)); if (node.Str!.Length == startingSpan.Length) { node.Kind = RegexNodeKind.Empty; node.Str = null; } else if (node.Str.Length - 1 == startingSpan.Length) { node.Kind = RegexNodeKind.One; node.Ch = node.Str[node.Str.Length - 1]; node.Str = null; } else { node.Str = node.Str.Substring(startingSpan.Length); } } } } if (alternation.Parent is RegexNode parent && parent.Kind == RegexNodeKind.Atomic) { var atomic = new RegexNode(RegexNodeKind.Atomic, startingNodeOptions); atomic.AddChild(newAlternate); newAlternate = atomic; } var newConcat = new RegexNode(RegexNodeKind.Concatenate, startingNodeOptions); newConcat.AddChild(prefix); newConcat.AddChild(newAlternate); alternation.ReplaceChild(startingIndex, newConcat); children.RemoveRange(startingIndex + 1, endingIndex - startingIndex - 1); } return alternation.ChildCount() == 1 ? alternation.Child(0) : alternation; } } /// <summary> /// Finds the starting one or multi of the branch, if it has one; otherwise, returns null. /// For simplicity, this only considers branches that are One or Multi, or a Concatenation /// beginning with a One or Multi. We don't traverse more than one level to avoid the /// complication of then having to later update that hierarchy when removing the prefix, /// but it could be done in the future if proven beneficial enough. /// </summary> public RegexNode? FindBranchOneOrMultiStart() { RegexNode branch = Kind == RegexNodeKind.Concatenate ? Child(0) : this; return branch.Kind is RegexNodeKind.One or RegexNodeKind.Multi ? branch : null; } /// <summary>Same as <see cref="FindBranchOneOrMultiStart"/> but also for Sets.</summary> public RegexNode? FindBranchOneMultiOrSetStart() { RegexNode branch = Kind == RegexNodeKind.Concatenate ? Child(0) : this; return branch.Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set ? branch : null; } /// <summary>Gets the character that begins a One or Multi.</summary> public char FirstCharOfOneOrMulti() { Debug.Assert(Kind is RegexNodeKind.One or RegexNodeKind.Multi); Debug.Assert((Options & RegexOptions.RightToLeft) == 0); return Kind == RegexNodeKind.One ? Ch : Str![0]; } /// <summary>Finds the guaranteed beginning literal(s) of the node, or null if none exists.</summary> public (char Char, string? String, string? SetChars)? FindStartingLiteral(int maxSetCharacters = 5) // 5 is max optimized by IndexOfAny today { Debug.Assert(maxSetCharacters >= 0 && maxSetCharacters <= 128, $"{nameof(maxSetCharacters)} == {maxSetCharacters} should be small enough to be stack allocated."); RegexNode? node = this; while (true) { if (node is not null && (node.Options & RegexOptions.RightToLeft) == 0) { switch (node.Kind) { case RegexNodeKind.One: case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy when node.M > 0: if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(node.Ch)) { return (node.Ch, null, null); } break; case RegexNodeKind.Multi: if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(node.Str.AsSpan())) { return ('\0', node.Str, null); } break; case RegexNodeKind.Set: case RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy when node.M > 0: Span<char> setChars = stackalloc char[maxSetCharacters]; int numChars; if (!RegexCharClass.IsNegated(node.Str!) && (numChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0) { setChars = setChars.Slice(0, numChars); if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(setChars)) { return ('\0', null, setChars.ToString()); } } break; case RegexNodeKind.Atomic: case RegexNodeKind.Concatenate: case RegexNodeKind.Capture: case RegexNodeKind.Group: case RegexNodeKind.Loop or RegexNodeKind.Lazyloop when node.M > 0: case RegexNodeKind.PositiveLookaround: node = node.Child(0); continue; } } return null; } } /// <summary> /// Optimizes a concatenation by coalescing adjacent characters and strings, /// coalescing adjacent loops, converting loops to be atomic where applicable, /// and removing the concatenation itself if it's unnecessary. /// </summary> private RegexNode ReduceConcatenation() { Debug.Assert(Kind == RegexNodeKind.Concatenate); // If the concat node has zero or only one child, get rid of the concat. switch (ChildCount()) { case 0: return new RegexNode(RegexNodeKind.Empty, Options); case 1: return Child(0); } // Coalesce adjacent loops. This helps to minimize work done by the interpreter, minimize code gen, // and also help to reduce catastrophic backtracking. ReduceConcatenationWithAdjacentLoops(); // Coalesce adjacent characters/strings. This is done after the adjacent loop coalescing so that // a One adjacent to both a Multi and a Loop prefers being folded into the Loop rather than into // the Multi. Doing so helps with auto-atomicity when it's later applied. ReduceConcatenationWithAdjacentStrings(); // If the concatenation is now empty, return an empty node, or if it's got a single child, return that child. // Otherwise, return this. return ReplaceNodeIfUnnecessary(); } /// <summary> /// Combine adjacent characters/strings. /// e.g. (?:abc)(?:def) -> abcdef /// </summary> private void ReduceConcatenationWithAdjacentStrings() { Debug.Assert(Kind == RegexNodeKind.Concatenate); Debug.Assert(Children is List<RegexNode>); bool wasLastString = false; RegexOptions optionsLast = 0; int i, j; List<RegexNode> children = (List<RegexNode>)Children!; for (i = 0, j = 0; i < children.Count; i++, j++) { RegexNode at = children[i]; if (j < i) { children[j] = at; } if (at.Kind == RegexNodeKind.Concatenate && ((at.Options & RegexOptions.RightToLeft) == (Options & RegexOptions.RightToLeft))) { if (at.Children is List<RegexNode> atChildren) { for (int k = 0; k < atChildren.Count; k++) { atChildren[k].Parent = this; } children.InsertRange(i + 1, atChildren); } else { RegexNode atChild = (RegexNode)at.Children!; atChild.Parent = this; children.Insert(i + 1, atChild); } j--; } else if (at.Kind is RegexNodeKind.Multi or RegexNodeKind.One) { // Cannot merge strings if L or I options differ RegexOptions optionsAt = at.Options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase); if (!wasLastString || optionsLast != optionsAt) { wasLastString = true; optionsLast = optionsAt; continue; } RegexNode prev = children[--j]; if (prev.Kind == RegexNodeKind.One) { prev.Kind = RegexNodeKind.Multi; prev.Str = prev.Ch.ToString(); } if ((optionsAt & RegexOptions.RightToLeft) == 0) { prev.Str = (at.Kind == RegexNodeKind.One) ? $"{prev.Str}{at.Ch}" : prev.Str + at.Str; } else { prev.Str = (at.Kind == RegexNodeKind.One) ? $"{at.Ch}{prev.Str}" : at.Str + prev.Str; } } else if (at.Kind == RegexNodeKind.Empty) { j--; } else { wasLastString = false; } } if (j < i) { children.RemoveRange(j, i - j); } } /// <summary> /// Combine adjacent loops. /// e.g. a*a*a* => a* /// e.g. a+ab => a{2,}b /// </summary> private void ReduceConcatenationWithAdjacentLoops() { Debug.Assert(Kind == RegexNodeKind.Concatenate); Debug.Assert(Children is List<RegexNode>); var children = (List<RegexNode>)Children!; int current = 0, next = 1, nextSave = 1; while (next < children.Count) { RegexNode currentNode = children[current]; RegexNode nextNode = children[next]; if (currentNode.Options == nextNode.Options) { static bool CanCombineCounts(int nodeMin, int nodeMax, int nextMin, int nextMax) { // We shouldn't have an infinite minimum; bail if we find one. Also check for the // degenerate case where we'd make the min overflow or go infinite when it wasn't already. if (nodeMin == int.MaxValue || nextMin == int.MaxValue || (uint)nodeMin + (uint)nextMin >= int.MaxValue) { return false; } // Similar overflow / go infinite check for max (which can be infinite). if (nodeMax != int.MaxValue && nextMax != int.MaxValue && (uint)nodeMax + (uint)nextMax >= int.MaxValue) { return false; } return true; } switch (currentNode.Kind) { // Coalescing a loop with its same type case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy when nextNode.Kind == currentNode.Kind && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy when nextNode.Kind == currentNode.Kind && currentNode.Str == nextNode.Str: if (CanCombineCounts(currentNode.M, currentNode.N, nextNode.M, nextNode.N)) { currentNode.M += nextNode.M; if (currentNode.N != int.MaxValue) { currentNode.N = nextNode.N == int.MaxValue ? int.MaxValue : currentNode.N + nextNode.N; } next++; continue; } break; // Coalescing a loop with an additional item of the same type case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy when nextNode.Kind == RegexNodeKind.One && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy when nextNode.Kind == RegexNodeKind.Notone && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy when nextNode.Kind == RegexNodeKind.Set && currentNode.Str == nextNode.Str: if (CanCombineCounts(currentNode.M, currentNode.N, 1, 1)) { currentNode.M++; if (currentNode.N != int.MaxValue) { currentNode.N++; } next++; continue; } break; // Coalescing a loop with a subsequent string case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy when nextNode.Kind == RegexNodeKind.Multi && currentNode.Ch == nextNode.Str![0]: { // Determine how many of the multi's characters can be combined. // We already checked for the first, so we know it's at least one. int matchingCharsInMulti = 1; while (matchingCharsInMulti < nextNode.Str.Length && currentNode.Ch == nextNode.Str[matchingCharsInMulti]) { matchingCharsInMulti++; } if (CanCombineCounts(currentNode.M, currentNode.N, matchingCharsInMulti, matchingCharsInMulti)) { // Update the loop's bounds to include those characters from the multi currentNode.M += matchingCharsInMulti; if (currentNode.N != int.MaxValue) { currentNode.N += matchingCharsInMulti; } // If it was the full multi, skip/remove the multi and continue processing this loop. if (nextNode.Str.Length == matchingCharsInMulti) { next++; continue; } // Otherwise, trim the characters from the multiple that were absorbed into the loop. // If it now only has a single character, it becomes a One. Debug.Assert(matchingCharsInMulti < nextNode.Str.Length); if (nextNode.Str.Length - matchingCharsInMulti == 1) { nextNode.Kind = RegexNodeKind.One; nextNode.Ch = nextNode.Str[nextNode.Str.Length - 1]; nextNode.Str = null; } else { nextNode.Str = nextNode.Str.Substring(matchingCharsInMulti); } } } break; // NOTE: We could add support for coalescing a string with a subsequent loop, but the benefits of that // are limited. Pulling a subsequent string's prefix back into the loop helps with making the loop atomic, // but if the loop is after the string, pulling the suffix of the string forward into the loop may actually // be a deoptimization as those characters could end up matching more slowly as part of loop matching. // Coalescing an individual item with a loop. case RegexNodeKind.One when (nextNode.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy) && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Notone when (nextNode.Kind is RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy) && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Set when (nextNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy) && currentNode.Str == nextNode.Str: if (CanCombineCounts(1, 1, nextNode.M, nextNode.N)) { currentNode.Kind = nextNode.Kind; currentNode.M = nextNode.M + 1; currentNode.N = nextNode.N == int.MaxValue ? int.MaxValue : nextNode.N + 1; next++; continue; } break; // Coalescing an individual item with another individual item. // We don't coalesce adjacent One nodes into a Oneloop as we'd rather they be joined into a Multi. case RegexNodeKind.Notone when nextNode.Kind == currentNode.Kind && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Set when nextNode.Kind == RegexNodeKind.Set && currentNode.Str == nextNode.Str: currentNode.MakeRep(RegexNodeKind.Oneloop, 2, 2); next++; continue; } } children[nextSave++] = children[next]; current = next; next++; } if (nextSave < children.Count) { children.RemoveRange(nextSave, children.Count - nextSave); } } /// <summary> /// Finds {one/notone/set}loop nodes in the concatenation that can be automatically upgraded /// to {one/notone/set}loopatomic nodes. Such changes avoid potential useless backtracking. /// e.g. A*B (where sets A and B don't overlap) => (?>A*)B. /// </summary> private void FindAndMakeLoopsAtomic() { Debug.Assert((Options & RegexOptions.NonBacktracking) == 0, "Atomic groups aren't supported and don't help performance with NonBacktracking"); if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we're too deep on the stack, give up optimizing further. return; } if ((Options & RegexOptions.RightToLeft) != 0) { // RTL is so rare, we don't need to spend additional time/code optimizing for it. return; } // For all node types that have children, recur into each of those children. int childCount = ChildCount(); if (childCount != 0) { for (int i = 0; i < childCount; i++) { Child(i).FindAndMakeLoopsAtomic(); } } // If this isn't a concatenation, nothing more to do. if (Kind is not RegexNodeKind.Concatenate) { return; } // This is a concatenation. Iterate through each pair of nodes in the concatenation seeing whether we can // make the first node (or its right-most child) atomic based on the second node (or its left-most child). Debug.Assert(Children is List<RegexNode>); var children = (List<RegexNode>)Children; for (int i = 0; i < childCount - 1; i++) { ProcessNode(children[i], children[i + 1]); static void ProcessNode(RegexNode node, RegexNode subsequent) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, just stop optimizing. return; } // Skip down the node past irrelevant nodes. while (true) { // We can always recur into captures and into the last node of concatenations. if (node.Kind is RegexNodeKind.Capture or RegexNodeKind.Concatenate) { node = node.Child(node.ChildCount() - 1); continue; } // For loops with at least one guaranteed iteration, we can recur into them, but // we need to be careful not to just always do so; the ending node of a loop can only // be made atomic if what comes after the loop but also the beginning of the loop are // compatible for the optimization. if (node.Kind == RegexNodeKind.Loop) { RegexNode? loopDescendent = node.FindLastExpressionInLoopForAutoAtomic(); if (loopDescendent != null) { node = loopDescendent; continue; } } // Can't skip any further. break; } // If the node can be changed to atomic based on what comes after it, do so. switch (node.Kind) { case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop when CanBeMadeAtomic(node, subsequent, allowSubsequentIteration: true): node.MakeLoopAtomic(); break; case RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional: // In the case of alternation, we can't change the alternation node itself // based on what comes after it (at least not with more complicated analysis // that factors in all branches together), but we can look at each individual // branch, and analyze ending loops in each branch individually to see if they // can be made atomic. Then if we do end up backtracking into the alternation, // we at least won't need to backtrack into that loop. The same is true for // conditionals, though we don't want to process the condition expression // itself, as it's already considered atomic and handled as part of ReduceExpressionConditional. { int alternateBranches = node.ChildCount(); for (int b = node.Kind == RegexNodeKind.ExpressionConditional ? 1 : 0; b < alternateBranches; b++) { ProcessNode(node.Child(b), subsequent); } } break; } } } } /// <summary> /// Recurs into the last expression of a loop node, looking to see if it can find a node /// that could be made atomic _assuming_ the conditions exist for it with the loop's ancestors. /// </summary> /// <returns>The found node that should be explored further for auto-atomicity; null if it doesn't exist.</returns> private RegexNode? FindLastExpressionInLoopForAutoAtomic() { RegexNode node = this; Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop); // Start by looking at the loop's sole child. node = node.Child(0); // Skip past captures. while (node.Kind == RegexNodeKind.Capture) { node = node.Child(0); } // If the loop's body is a concatenate, we can skip to its last child iff that // last child doesn't conflict with the first child, since this whole concatenation // could be repeated, such that the first node ends up following the last. For // example, in the expression (a+[def])*, the last child is [def] and the first is // a+, which can't possibly overlap with [def]. In contrast, if we had (a+[ade])*, // [ade] could potentially match the starting 'a'. if (node.Kind == RegexNodeKind.Concatenate) { int concatCount = node.ChildCount(); RegexNode lastConcatChild = node.Child(concatCount - 1); if (CanBeMadeAtomic(lastConcatChild, node.Child(0), allowSubsequentIteration: false)) { return lastConcatChild; } } // Otherwise, the loop has nothing that can participate in auto-atomicity. return null; } /// <summary>Optimizations for positive and negative lookaheads/behinds.</summary> private RegexNode ReduceLookaround() { Debug.Assert(Kind is RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround); Debug.Assert(ChildCount() == 1); // A lookaround is a zero-width atomic assertion. // As it's atomic, nothing will backtrack into it, and we can // eliminate any ending backtracking from it. EliminateEndingBacktracking(); // A positive lookaround wrapped around an empty is a nop, and we can reduce it // to simply Empty. A developer typically doesn't write this, but rather it evolves // due to optimizations resulting in empty. // A negative lookaround wrapped around an empty child, i.e. (?!), is // sometimes used as a way to insert a guaranteed no-match into the expression, // often as part of a conditional. We can reduce it to simply Nothing. if (Child(0).Kind == RegexNodeKind.Empty) { Kind = Kind == RegexNodeKind.PositiveLookaround ? RegexNodeKind.Empty : RegexNodeKind.Nothing; Children = null; } return this; } /// <summary>Optimizations for backreference conditionals.</summary> private RegexNode ReduceBackreferenceConditional() { Debug.Assert(Kind == RegexNodeKind.BackreferenceConditional); Debug.Assert(ChildCount() is 1 or 2); // This isn't so much an optimization as it is changing the tree for consistency. We want // all engines to be able to trust that every backreference conditional will have two children, // even though it's optional in the syntax. If it's missing a "not matched" branch, // we add one that will match empty. if (ChildCount() == 1) { AddChild(new RegexNode(RegexNodeKind.Empty, Options)); } return this; } /// <summary>Optimizations for expression conditionals.</summary> private RegexNode ReduceExpressionConditional() { Debug.Assert(Kind == RegexNodeKind.ExpressionConditional); Debug.Assert(ChildCount() is 2 or 3); // This isn't so much an optimization as it is changing the tree for consistency. We want // all engines to be able to trust that every expression conditional will have three children, // even though it's optional in the syntax. If it's missing a "not matched" branch, // we add one that will match empty. if (ChildCount() == 2) { AddChild(new RegexNode(RegexNodeKind.Empty, Options)); } // It's common for the condition to be an explicit positive lookahead, as specifying // that eliminates any ambiguity in syntax as to whether the expression is to be matched // as an expression or to be a reference to a capture group. After parsing, however, // there's no ambiguity, and we can remove an extra level of positive lookahead, as the // engines need to treat the condition as a zero-width positive, atomic assertion regardless. RegexNode condition = Child(0); if (condition.Kind == RegexNodeKind.PositiveLookaround && (condition.Options & RegexOptions.RightToLeft) == 0) { ReplaceChild(0, condition.Child(0)); } // We can also eliminate any ending backtracking in the condition, as the condition // is considered to be a positive lookahead, which is an atomic zero-width assertion. condition = Child(0); condition.EliminateEndingBacktracking(); return this; } /// <summary> /// Determines whether node can be switched to an atomic loop. Subsequent is the node /// immediately after 'node'. /// </summary> private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent, bool allowSubsequentIteration) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, just stop optimizing. return false; } // In most case, we'll simply check the node against whatever subsequent is. However, in case // subsequent ends up being a loop with a min bound of 0, we'll also need to evaluate the node // against whatever comes after subsequent. In that case, we'll walk the tree to find the // next subsequent, and we'll loop around against to perform the comparison again. while (true) { // Skip the successor down to the closest node that's guaranteed to follow it. int childCount; while ((childCount = subsequent.ChildCount()) > 0) { Debug.Assert(subsequent.Kind != RegexNodeKind.Group); switch (subsequent.Kind) { case RegexNodeKind.Concatenate: case RegexNodeKind.Capture: case RegexNodeKind.Atomic: case RegexNodeKind.PositiveLookaround when (subsequent.Options & RegexOptions.RightToLeft) == 0: // only lookaheads, not lookbehinds (represented as RTL PositiveLookaround nodes) case RegexNodeKind.Loop or RegexNodeKind.Lazyloop when subsequent.M > 0: subsequent = subsequent.Child(0); continue; } break; } // If the two nodes don't agree on options in any way, don't try to optimize them. // TODO: Remove this once https://github.com/dotnet/runtime/issues/61048 is implemented. if (node.Options != subsequent.Options) { return false; } // If the successor is an alternation, all of its children need to be evaluated, since any of them // could come after this node. If any of them fail the optimization, then the whole node fails. // This applies to expression conditionals as well, as long as they have both a yes and a no branch (if there's // only a yes branch, we'd need to also check whatever comes after the conditional). It doesn't apply to // backreference conditionals, as the condition itself is unknown statically and could overlap with the // loop being considered for atomicity. switch (subsequent.Kind) { case RegexNodeKind.Alternate: case RegexNodeKind.ExpressionConditional when childCount == 3: // condition, yes, and no branch for (int i = 0; i < childCount; i++) { if (!CanBeMadeAtomic(node, subsequent.Child(i), allowSubsequentIteration)) { return false; } } return true; } // If this node is a {one/notone/set}loop, see if it overlaps with its successor in the concatenation. // If it doesn't, then we can upgrade it to being a {one/notone/set}loopatomic. // Doing so avoids unnecessary backtracking. switch (node.Kind) { case RegexNodeKind.Oneloop: switch (subsequent.Kind) { case RegexNodeKind.One when node.Ch != subsequent.Ch: case RegexNodeKind.Notone when node.Ch == subsequent.Ch: case RegexNodeKind.Set when !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M > 0 && node.Ch != subsequent.Ch: case RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): case RegexNodeKind.Multi when node.Ch != subsequent.Str![0]: case RegexNodeKind.End: case RegexNodeKind.EndZ or RegexNodeKind.Eol when node.Ch != '\n': case RegexNodeKind.Boundary when RegexCharClass.IsBoundaryWordChar(node.Ch): case RegexNodeKind.NonBoundary when !RegexCharClass.IsBoundaryWordChar(node.Ch): case RegexNodeKind.ECMABoundary when RegexCharClass.IsECMAWordChar(node.Ch): case RegexNodeKind.NonECMABoundary when !RegexCharClass.IsECMAWordChar(node.Ch): return true; case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M == 0 && node.Ch != subsequent.Ch: case RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic when subsequent.M == 0 && node.Ch == subsequent.Ch: case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M == 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. break; default: return false; } break; case RegexNodeKind.Notoneloop: switch (subsequent.Kind) { case RegexNodeKind.One when node.Ch == subsequent.Ch: case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: case RegexNodeKind.Multi when node.Ch == subsequent.Str![0]: case RegexNodeKind.End: return true; case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M == 0 && node.Ch == subsequent.Ch: // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. break; default: return false; } break; case RegexNodeKind.Setloop: switch (subsequent.Kind) { case RegexNodeKind.One when !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case RegexNodeKind.Set when !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M > 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): case RegexNodeKind.Multi when !RegexCharClass.CharInClass(subsequent.Str![0], node.Str!): case RegexNodeKind.End: case RegexNodeKind.EndZ or RegexNodeKind.Eol when !RegexCharClass.CharInClass('\n', node.Str!): case RegexNodeKind.Boundary when node.Str is RegexCharClass.WordClass or RegexCharClass.DigitClass: case RegexNodeKind.NonBoundary when node.Str is RegexCharClass.NotWordClass or RegexCharClass.NotDigitClass: case RegexNodeKind.ECMABoundary when node.Str is RegexCharClass.ECMAWordClass or RegexCharClass.ECMADigitClass: case RegexNodeKind.NonECMABoundary when node.Str is RegexCharClass.NotECMAWordClass or RegexCharClass.NotDigitClass: return true; case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M == 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M == 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. break; default: return false; } break; default: return false; } // We only get here if the node could be made atomic based on subsequent but subsequent has a lower bound of zero // and thus we need to move subsequent to be the next node in sequence and loop around to try again. Debug.Assert(subsequent.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy); Debug.Assert(subsequent.M == 0); if (!allowSubsequentIteration) { return false; } // To be conservative, we only walk up through a very limited set of constructs (even though we may have walked // down through more, like loops), looking for the next concatenation that we're not at the end of, at // which point subsequent becomes whatever node is next in that concatenation. while (true) { RegexNode? parent = subsequent.Parent; switch (parent?.Kind) { case RegexNodeKind.Atomic: case RegexNodeKind.Alternate: case RegexNodeKind.Capture: subsequent = parent; continue; case RegexNodeKind.Concatenate: var peers = (List<RegexNode>)parent.Children!; int currentIndex = peers.IndexOf(subsequent); Debug.Assert(currentIndex >= 0, "Node should have been in its parent's child list"); if (currentIndex + 1 == peers.Count) { subsequent = parent; continue; } else { subsequent = peers[currentIndex + 1]; break; } case null: // If we hit the root, we're at the end of the expression, at which point nothing could backtrack // in and we can declare success. return true; default: // Anything else, we don't know what to do, so we have to assume it could conflict with the loop. return false; } break; } } } /// <summary>Computes a min bound on the required length of any string that could possibly match.</summary> /// <returns>The min computed length. If the result is 0, there is no minimum we can enforce.</returns> /// <remarks> /// e.g. abc[def](ghijkl|mn) => 6 /// </remarks> public int ComputeMinLength() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, assume there's no minimum we can enforce. return 0; } switch (Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: // Single character. return 1; case RegexNodeKind.Multi: // Every character in the string needs to match. return Str!.Length; case RegexNodeKind.Notonelazy: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Onelazy: case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Setlazy: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: // One character repeated at least M times. return M; case RegexNodeKind.Lazyloop: case RegexNodeKind.Loop: // A node graph repeated at least M times. return (int)Math.Min(int.MaxValue - 1, (long)M * Child(0).ComputeMinLength()); case RegexNodeKind.Alternate: // The minimum required length for any of the alternation's branches. { int childCount = ChildCount(); Debug.Assert(childCount >= 2); int min = Child(0).ComputeMinLength(); for (int i = 1; i < childCount && min > 0; i++) { min = Math.Min(min, Child(i).ComputeMinLength()); } return min; } case RegexNodeKind.BackreferenceConditional: // Minimum of its yes and no branches. The backreference doesn't add to the length. return Math.Min(Child(0).ComputeMinLength(), Child(1).ComputeMinLength()); case RegexNodeKind.ExpressionConditional: // Minimum of its yes and no branches. The condition is a zero-width assertion. return Math.Min(Child(1).ComputeMinLength(), Child(2).ComputeMinLength()); case RegexNodeKind.Concatenate: // The sum of all of the concatenation's children. { long sum = 0; int childCount = ChildCount(); for (int i = 0; i < childCount; i++) { sum += Child(i).ComputeMinLength(); } return (int)Math.Min(int.MaxValue - 1, sum); } case RegexNodeKind.Atomic: case RegexNodeKind.Capture: case RegexNodeKind.Group: // For groups, we just delegate to the sole child. Debug.Assert(ChildCount() == 1); return Child(0).ComputeMinLength(); case RegexNodeKind.Empty: case RegexNodeKind.Nothing: case RegexNodeKind.UpdateBumpalong: // Nothing to match. In the future, we could potentially use Nothing to say that the min length // is infinite, but that would require a different structure, as that would only apply if the // Nothing match is required in all cases (rather than, say, as one branch of an alternation). case RegexNodeKind.Beginning: case RegexNodeKind.Bol: case RegexNodeKind.Boundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.End: case RegexNodeKind.EndZ: case RegexNodeKind.Eol: case RegexNodeKind.NonBoundary: case RegexNodeKind.NonECMABoundary: case RegexNodeKind.Start: case RegexNodeKind.NegativeLookaround: case RegexNodeKind.PositiveLookaround: // Zero-width case RegexNodeKind.Backreference: // Requires matching data available only at run-time. In the future, we could choose to find // and follow the capture group this aligns with, while being careful not to end up in an // infinite cycle. return 0; default: Debug.Fail($"Unknown node: {Kind}"); goto case RegexNodeKind.Empty; } } /// <summary>Computes a maximum length of any string that could possibly match.</summary> /// <returns>The maximum length of any string that could possibly match, or null if the length may not always be the same.</returns> /// <remarks> /// e.g. abc[def](gh|ijklmnop) => 12 /// </remarks> public int? ComputeMaxLength() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, assume there's no minimum we can enforce. return null; } switch (Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: // Single character. return 1; case RegexNodeKind.Multi: // Every character in the string needs to match. return Str!.Length; case RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic: // Return the max number of iterations if there's an upper bound, or null if it's infinite return N == int.MaxValue ? null : N; case RegexNodeKind.Loop or RegexNodeKind.Lazyloop: if (N != int.MaxValue) { // A node graph repeated a fixed number of times if (Child(0).ComputeMaxLength() is int childMaxLength) { long maxLength = (long)N * childMaxLength; if (maxLength < int.MaxValue) { return (int)maxLength; } } } return null; case RegexNodeKind.Alternate: // The maximum length of any child branch, as long as they all have one. { int childCount = ChildCount(); Debug.Assert(childCount >= 2); if (Child(0).ComputeMaxLength() is not int maxLength) { return null; } for (int i = 1; i < childCount; i++) { if (Child(i).ComputeMaxLength() is not int next) { return null; } maxLength = Math.Max(maxLength, next); } return maxLength; } case RegexNodeKind.BackreferenceConditional: case RegexNodeKind.ExpressionConditional: // The maximum length of either child branch, as long as they both have one.. The condition for an expression conditional is a zero-width assertion. { int i = Kind == RegexNodeKind.BackreferenceConditional ? 0 : 1; return Child(i).ComputeMaxLength() is int yes && Child(i + 1).ComputeMaxLength() is int no ? Math.Max(yes, no) : null; } case RegexNodeKind.Concatenate: // The sum of all of the concatenation's children's max lengths, as long as they all have one. { long sum = 0; int childCount = ChildCount(); for (int i = 0; i < childCount; i++) { if (Child(i).ComputeMaxLength() is not int length) { return null; } sum += length; } if (sum < int.MaxValue) { return (int)sum; } return null; } case RegexNodeKind.Atomic: case RegexNodeKind.Capture: // For groups, we just delegate to the sole child. Debug.Assert(ChildCount() == 1); return Child(0).ComputeMaxLength(); case RegexNodeKind.Empty: case RegexNodeKind.Nothing: case RegexNodeKind.UpdateBumpalong: case RegexNodeKind.Beginning: case RegexNodeKind.Bol: case RegexNodeKind.Boundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.End: case RegexNodeKind.EndZ: case RegexNodeKind.Eol: case RegexNodeKind.NonBoundary: case RegexNodeKind.NonECMABoundary: case RegexNodeKind.Start: case RegexNodeKind.PositiveLookaround: case RegexNodeKind.NegativeLookaround: // Zero-width return 0; case RegexNodeKind.Backreference: // Requires matching data available only at run-time. In the future, we could choose to find // and follow the capture group this aligns with, while being careful not to end up in an // infinite cycle. return null; default: Debug.Fail($"Unknown node: {Kind}"); goto case RegexNodeKind.Empty; } } /// <summary> /// Determine whether the specified child node is the beginning of a sequence that can /// trivially have length checks combined in order to avoid bounds checks. /// </summary> /// <param name="childIndex">The starting index of the child to check.</param> /// <param name="requiredLength">The sum of all the fixed lengths for the nodes in the sequence.</param> /// <param name="exclusiveEnd">The index of the node just after the last one in the sequence.</param> /// <returns>true if more than one node can have their length checks combined; otherwise, false.</returns> /// <remarks> /// There are additional node types for which we can prove a fixed length, e.g. examining all branches /// of an alternation and returning true if all their lengths are equal. However, the primary purpose /// of this method is to avoid bounds checks by consolidating length checks that guard accesses to /// strings/spans for which the JIT can see a fixed index within bounds, and alternations employ /// patterns that defeat that (e.g. reassigning the span in question). As such, the implementation /// remains focused on only a core subset of nodes that are a) likely to be used in concatenations and /// b) employ simple patterns of checks. /// </remarks> public bool TryGetJoinableLengthCheckChildRange(int childIndex, out int requiredLength, out int exclusiveEnd) { static bool CanJoinLengthCheck(RegexNode node) => node.Kind switch { RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set => true, RegexNodeKind.Multi => true, RegexNodeKind.Oneloop or RegexNodeKind.Onelazy or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic when node.M == node.N => true, _ => false, }; RegexNode child = Child(childIndex); if (CanJoinLengthCheck(child)) { requiredLength = child.ComputeMinLength(); int childCount = ChildCount(); for (exclusiveEnd = childIndex + 1; exclusiveEnd < childCount; exclusiveEnd++) { child = Child(exclusiveEnd); if (!CanJoinLengthCheck(child)) { break; } requiredLength += child.ComputeMinLength(); } if (exclusiveEnd - childIndex > 1) { return true; } } requiredLength = 0; exclusiveEnd = 0; return false; } public RegexNode MakeQuantifier(bool lazy, int min, int max) { // Certain cases of repeaters (min == max) can be handled specially if (min == max) { switch (max) { case 0: // The node is repeated 0 times, so it's actually empty. return new RegexNode(RegexNodeKind.Empty, Options); case 1: // The node is repeated 1 time, so it's not actually a repeater. return this; case <= MultiVsRepeaterLimit when Kind == RegexNodeKind.One: // The same character is repeated a fixed number of times, so it's actually a multi. // While this could remain a repeater, multis are more readily optimized later in // processing. The counts used here in real-world expressions are invariably small (e.g. 4), // but we set an upper bound just to avoid creating really large strings. Debug.Assert(max >= 2); Kind = RegexNodeKind.Multi; Str = new string(Ch, max); Ch = '\0'; return this; } } switch (Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: MakeRep(lazy ? RegexNodeKind.Onelazy : RegexNodeKind.Oneloop, min, max); return this; default: var result = new RegexNode(lazy ? RegexNodeKind.Lazyloop : RegexNodeKind.Loop, Options, min, max); result.AddChild(this); return result; } } public void AddChild(RegexNode newChild) { newChild.Parent = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Parent = this; // in case Reduce returns a different node that needs to be reparented if (Children is null) { Children = newChild; } else if (Children is RegexNode currentChild) { Children = new List<RegexNode>() { currentChild, newChild }; } else { ((List<RegexNode>)Children).Add(newChild); } } public void InsertChild(int index, RegexNode newChild) { Debug.Assert(Children is List<RegexNode>); newChild.Parent = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Parent = this; // in case Reduce returns a different node that needs to be reparented ((List<RegexNode>)Children).Insert(index, newChild); } public void ReplaceChild(int index, RegexNode newChild) { Debug.Assert(Children != null); Debug.Assert(index < ChildCount()); newChild.Parent = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Parent = this; // in case Reduce returns a different node that needs to be reparented if (Children is RegexNode) { Children = newChild; } else { ((List<RegexNode>)Children)[index] = newChild; } } public RegexNode Child(int i) => Children is RegexNode child ? child : ((List<RegexNode>)Children!)[i]; public int ChildCount() { if (Children is null) { return 0; } if (Children is List<RegexNode> children) { return children.Count; } Debug.Assert(Children is RegexNode); return 1; } // Determines whether the node supports a compilation / code generation strategy based on walking the node tree. // Also returns a human-readable string to explain the reason (it will be emitted by the source generator, hence // there's no need to localize). internal bool SupportsCompilation([NotNullWhen(false)] out string? reason) { if ((Options & RegexOptions.NonBacktracking) != 0) { reason = "RegexOptions.NonBacktracking isn't supported"; return false; } if (ExceedsMaxDepthAllowedDepth(this, allowedDepth: 40)) { // For the source generator, deep RegexNode trees can result in emitting C# code that exceeds C# compiler // limitations, leading to "CS8078: An expression is too long or complex to compile". As such, we place // an artificial limit on max tree depth in order to mitigate such issues. The allowed depth can be tweaked // as needed; its exceedingly rare to find expressions with such deep trees. And while RegexCompiler doesn't // have to deal with C# compiler limitations, we still want to limit max tree depth as we want to limit // how deep recursion we'll employ as part of code generation. reason = "the expression may result exceeding run-time or compiler limits"; return false; } // Supported. reason = null; return true; static bool ExceedsMaxDepthAllowedDepth(RegexNode node, int allowedDepth) { if (allowedDepth <= 0) { return true; } int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { if (ExceedsMaxDepthAllowedDepth(node.Child(i), allowedDepth - 1)) { return true; } } return false; } } /// <summary>Gets whether the node is a Set/Setloop/Setloopatomic/Setlazy node.</summary> public bool IsSetFamily => Kind is RegexNodeKind.Set or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy; /// <summary>Gets whether the node is a One/Oneloop/Oneloopatomic/Onelazy node.</summary> public bool IsOneFamily => Kind is RegexNodeKind.One or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy; /// <summary>Gets whether the node is a Notone/Notoneloop/Notoneloopatomic/Notonelazy node.</summary> public bool IsNotoneFamily => Kind is RegexNodeKind.Notone or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy; /// <summary>Gets whether this node is contained inside of a loop.</summary> public bool IsInLoop() { for (RegexNode? parent = Parent; parent is not null; parent = parent.Parent) { if (parent.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop) { return true; } } return false; } #if DEBUG [ExcludeFromCodeCoverage] public override string ToString() { RegexNode? curNode = this; int curChild = 0; var sb = new StringBuilder().AppendLine(curNode.Describe()); var stack = new List<int>(); while (true) { if (curChild < curNode!.ChildCount()) { stack.Add(curChild + 1); curNode = curNode.Child(curChild); curChild = 0; sb.Append(new string(' ', stack.Count * 2)).Append(curNode.Describe()).AppendLine(); } else { if (stack.Count == 0) { break; } curChild = stack[stack.Count - 1]; stack.RemoveAt(stack.Count - 1); curNode = curNode.Parent; } } return sb.ToString(); } [ExcludeFromCodeCoverage] private string Describe() { var sb = new StringBuilder(Kind.ToString()); if ((Options & RegexOptions.ExplicitCapture) != 0) sb.Append("-C"); if ((Options & RegexOptions.IgnoreCase) != 0) sb.Append("-I"); if ((Options & RegexOptions.RightToLeft) != 0) sb.Append("-L"); if ((Options & RegexOptions.Multiline) != 0) sb.Append("-M"); if ((Options & RegexOptions.Singleline) != 0) sb.Append("-S"); if ((Options & RegexOptions.IgnorePatternWhitespace) != 0) sb.Append("-X"); if ((Options & RegexOptions.ECMAScript) != 0) sb.Append("-E"); switch (Kind) { case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.One: case RegexNodeKind.Notone: sb.Append(" '").Append(RegexCharClass.DescribeChar(Ch)).Append('\''); break; case RegexNodeKind.Capture: sb.Append(' ').Append($"index = {M}"); if (N != -1) { sb.Append($", unindex = {N}"); } break; case RegexNodeKind.Backreference: case RegexNodeKind.BackreferenceConditional: sb.Append(' ').Append($"index = {M}"); break; case RegexNodeKind.Multi: sb.Append(" \"").Append(Str).Append('"'); break; case RegexNodeKind.Set: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Setlazy: sb.Append(' ').Append(RegexCharClass.DescribeSet(Str!)); break; } switch (Kind) { case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Setlazy: case RegexNodeKind.Loop: case RegexNodeKind.Lazyloop: sb.Append( (M == 0 && N == int.MaxValue) ? "*" : (M == 0 && N == 1) ? "?" : (M == 1 && N == int.MaxValue) ? "+" : (N == int.MaxValue) ? $"{{{M}, *}}" : (N == M) ? $"{{{M}}}" : $"{{{M}, {N}}}"); break; } return sb.ToString(); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Threading; namespace System.Text.RegularExpressions { /// <summary>Represents a regex subexpression.</summary> internal sealed class RegexNode { /// <summary>empty bit from the node's options to store data on whether a node contains captures</summary> internal const RegexOptions HasCapturesFlag = (RegexOptions)(1 << 31); /// <summary>Arbitrary number of repetitions of the same character when we'd prefer to represent that as a repeater of that character rather than a string.</summary> internal const int MultiVsRepeaterLimit = 64; /// <summary>The node's children.</summary> /// <remarks>null if no children, a <see cref="RegexNode"/> if one child, or a <see cref="List{RegexNode}"/> if multiple children.</remarks> private object? Children; /// <summary>The kind of expression represented by this node.</summary> public RegexNodeKind Kind { get; private set; } /// <summary>A string associated with the node.</summary> /// <remarks>For a <see cref="RegexNodeKind.Multi"/>, this is the string from the expression. For an <see cref="IsSetFamily"/> node, this is the character class string from <see cref="RegexCharClass"/>.</remarks> public string? Str { get; private set; } /// <summary>The character associated with the node.</summary> /// <remarks>For a <see cref="IsOneFamily"/> or <see cref="IsNotoneFamily"/> node, the character from the expression.</remarks> public char Ch { get; private set; } /// <summary>The minimum number of iterations for a loop, or the capture group number for a capture or backreference.</summary> /// <remarks>No minimum is represented by 0. No capture group is represented by -1.</remarks> public int M { get; private set; } /// <summary>The maximum number of iterations for a loop, or the uncapture group number for a balancing group.</summary> /// <remarks>No upper bound is represented by <see cref="int.MaxValue"/>. No capture group is represented by -1.</remarks> public int N { get; private set; } /// <summary>The options associated with the node.</summary> public RegexOptions Options; /// <summary>The node's parent node in the tree.</summary> /// <remarks> /// During parsing, top-level nodes are also stacked onto a parse stack (a stack of trees) using <see cref="Parent"/>. /// After parsing, <see cref="Parent"/> is the node in the tree that has this node as or in <see cref="Children"/>. /// </remarks> public RegexNode? Parent; public RegexNode(RegexNodeKind kind, RegexOptions options) { Kind = kind; Options = options; } public RegexNode(RegexNodeKind kind, RegexOptions options, char ch) { Kind = kind; Options = options; Ch = ch; } public RegexNode(RegexNodeKind kind, RegexOptions options, string str) { Kind = kind; Options = options; Str = str; } public RegexNode(RegexNodeKind kind, RegexOptions options, int m) { Kind = kind; Options = options; M = m; } public RegexNode(RegexNodeKind kind, RegexOptions options, int m, int n) { Kind = kind; Options = options; M = m; N = n; } /// <summary>Creates a RegexNode representing a single character.</summary> /// <param name="ch">The character.</param> /// <param name="options">The node's options.</param> /// <param name="culture">The culture to use to perform any required transformations.</param> /// <returns>The created RegexNode. This might be a RegexNode.One or a RegexNode.Set.</returns> public static RegexNode CreateOneWithCaseConversion(char ch, RegexOptions options, CultureInfo? culture) { // If the options specify case-insensitivity, we try to create a node that fully encapsulates that. if ((options & RegexOptions.IgnoreCase) != 0) { Debug.Assert(culture is not null); // If the character is part of a Unicode category that doesn't participate in case conversion, // we can simply strip out the IgnoreCase option and make the node case-sensitive. if (!RegexCharClass.ParticipatesInCaseConversion(ch)) { return new RegexNode(RegexNodeKind.One, options & ~RegexOptions.IgnoreCase, ch); } // Create a set for the character, trying to include all case-insensitive equivalent characters. // If it's successful in doing so, resultIsCaseInsensitive will be false and we can strip // out RegexOptions.IgnoreCase as part of creating the set. string stringSet = RegexCharClass.OneToStringClass(ch, culture, out bool resultIsCaseInsensitive); if (!resultIsCaseInsensitive) { return new RegexNode(RegexNodeKind.Set, options & ~RegexOptions.IgnoreCase, stringSet); } // Otherwise, until we can get rid of ToLower usage at match time entirely (https://github.com/dotnet/runtime/issues/61048), // lowercase the character and proceed to create an IgnoreCase One node. ch = culture.TextInfo.ToLower(ch); } // Create a One node for the character. return new RegexNode(RegexNodeKind.One, options, ch); } /// <summary>Reverses all children of a concatenation when in RightToLeft mode.</summary> public RegexNode ReverseConcatenationIfRightToLeft() { if ((Options & RegexOptions.RightToLeft) != 0 && Kind == RegexNodeKind.Concatenate && ChildCount() > 1) { ((List<RegexNode>)Children!).Reverse(); } return this; } /// <summary> /// Pass type as OneLazy or OneLoop /// </summary> private void MakeRep(RegexNodeKind kind, int min, int max) { Kind += kind - RegexNodeKind.One; M = min; N = max; } private void MakeLoopAtomic() { switch (Kind) { case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop: // For loops, we simply change the Type to the atomic variant. // Atomic greedy loops should consume as many values as they can. Kind += RegexNodeKind.Oneloopatomic - RegexNodeKind.Oneloop; break; case RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy: // For lazy, we not only change the Type, we also lower the max number of iterations // to the minimum number of iterations, creating a repeater, as they should end up // matching as little as possible. Kind += RegexNodeKind.Oneloopatomic - RegexNodeKind.Onelazy; N = M; if (N == 0) { // If moving the max to be the same as the min dropped it to 0, there's no // work to be done for this node, and we can make it Empty. Kind = RegexNodeKind.Empty; Str = null; Ch = '\0'; } else if (Kind == RegexNodeKind.Oneloopatomic && N is >= 2 and <= MultiVsRepeaterLimit) { // If this is now a One repeater with a small enough length, // make it a Multi instead, as they're better optimized down the line. Kind = RegexNodeKind.Multi; Str = new string(Ch, N); Ch = '\0'; M = N = 0; } break; default: Debug.Fail($"Unexpected type: {Kind}"); break; } } #if DEBUG /// <summary>Validate invariants the rest of the implementation relies on for processing fully-built trees.</summary> [Conditional("DEBUG")] private void ValidateFinalTreeInvariants() { Debug.Assert(Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); var toExamine = new Stack<RegexNode>(); toExamine.Push(this); while (toExamine.Count > 0) { RegexNode node = toExamine.Pop(); // Add all children to be examined int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { RegexNode child = node.Child(i); Debug.Assert(child.Parent == node, $"{child.Describe()} missing reference to parent {node.Describe()}"); toExamine.Push(child); } // Validate that we never see certain node types. Debug.Assert(Kind != RegexNodeKind.Group, "All Group nodes should have been removed."); // Validate node types and expected child counts. switch (node.Kind) { case RegexNodeKind.Group: Debug.Fail("All Group nodes should have been removed."); break; case RegexNodeKind.Beginning: case RegexNodeKind.Bol: case RegexNodeKind.Boundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.Empty: case RegexNodeKind.End: case RegexNodeKind.EndZ: case RegexNodeKind.Eol: case RegexNodeKind.Multi: case RegexNodeKind.NonBoundary: case RegexNodeKind.NonECMABoundary: case RegexNodeKind.Nothing: case RegexNodeKind.Notone: case RegexNodeKind.Notonelazy: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.One: case RegexNodeKind.Onelazy: case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Backreference: case RegexNodeKind.Set: case RegexNodeKind.Setlazy: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Start: case RegexNodeKind.UpdateBumpalong: Debug.Assert(childCount == 0, $"Expected zero children for {node.Kind}, got {childCount}."); break; case RegexNodeKind.Atomic: case RegexNodeKind.Capture: case RegexNodeKind.Lazyloop: case RegexNodeKind.Loop: case RegexNodeKind.NegativeLookaround: case RegexNodeKind.PositiveLookaround: Debug.Assert(childCount == 1, $"Expected one and only one child for {node.Kind}, got {childCount}."); break; case RegexNodeKind.BackreferenceConditional: Debug.Assert(childCount == 2, $"Expected two children for {node.Kind}, got {childCount}"); break; case RegexNodeKind.ExpressionConditional: Debug.Assert(childCount == 3, $"Expected three children for {node.Kind}, got {childCount}"); break; case RegexNodeKind.Concatenate: case RegexNodeKind.Alternate: Debug.Assert(childCount >= 2, $"Expected at least two children for {node.Kind}, got {childCount}."); break; default: Debug.Fail($"Unexpected node type: {node.Kind}"); break; } // Validate node configuration. switch (node.Kind) { case RegexNodeKind.Multi: Debug.Assert(node.Str is not null, "Expect non-null multi string"); Debug.Assert(node.Str.Length >= 2, $"Expected {node.Str} to be at least two characters"); break; case RegexNodeKind.Set: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Setlazy: Debug.Assert(!string.IsNullOrEmpty(node.Str), $"Expected non-null, non-empty string for {node.Kind}."); break; default: Debug.Assert(node.Str is null, $"Expected null string for {node.Kind}, got \"{node.Str}\"."); break; } } } #endif /// <summary>Performs additional optimizations on an entire tree prior to being used.</summary> /// <remarks> /// Some optimizations are performed by the parser while parsing, and others are performed /// as nodes are being added to the tree. The optimizations here expect the tree to be fully /// formed, as they inspect relationships between nodes that may not have been in place as /// individual nodes were being processed/added to the tree. /// </remarks> internal RegexNode FinalOptimize() { RegexNode rootNode = this; Debug.Assert(rootNode.Kind == RegexNodeKind.Capture); Debug.Assert(rootNode.Parent is null); Debug.Assert(rootNode.ChildCount() == 1); // Only apply optimization when LTR to avoid needing additional code for the much rarer RTL case. // Also only apply these optimizations when not using NonBacktracking, as these optimizations are // all about avoiding things that are impactful for the backtracking engines but nops for non-backtracking. if ((Options & (RegexOptions.RightToLeft | RegexOptions.NonBacktracking)) == 0) { // Optimization: eliminate backtracking for loops. // For any single-character loop (Oneloop, Notoneloop, Setloop), see if we can automatically convert // that into its atomic counterpart (Oneloopatomic, Notoneloopatomic, Setloopatomic) based on what // comes after it in the expression tree. rootNode.FindAndMakeLoopsAtomic(); // Optimization: backtracking removal at expression end. // If we find backtracking construct at the end of the regex, we can instead make it non-backtracking, // since nothing would ever backtrack into it anyway. Doing this then makes the construct available // to implementations that don't support backtracking. rootNode.EliminateEndingBacktracking(); // Optimization: unnecessary re-processing of starting loops. // If an expression is guaranteed to begin with a single-character unbounded loop that isn't part of an alternation (in which case it // wouldn't be guaranteed to be at the beginning) or a capture (in which case a back reference could be influenced by its length), then we // can update the tree with a temporary node to indicate that the implementation should use that node's ending position in the input text // as the next starting position at which to start the next match. This avoids redoing matches we've already performed, e.g. matching // "\[email protected]" against "is this a valid [email protected]", the \w+ will initially match the "is" and then will fail to match the "@". // Rather than bumping the scan loop by 1 and trying again to match at the "s", we can instead start at the " ". For functional correctness // we can only consider unbounded loops, as to be able to start at the end of the loop we need the loop to have consumed all possible matches; // otherwise, you could end up with a pattern like "a{1,3}b" matching against "aaaabc", which should match, but if we pre-emptively stop consuming // after the first three a's and re-start from that position, we'll end up failing the match even though it should have succeeded. We can also // apply this optimization to non-atomic loops: even though backtracking could be necessary, such backtracking would be handled within the processing // of a single starting position. Lazy loops similarly benefit, as a failed match will result in exploring the exact same search space as with // a greedy loop, just in the opposite order (and a successful match will overwrite the bumpalong position); we need to avoid atomic lazy loops, // however, as they will only end up as a repeater for the minimum length and thus will effectively end up with a non-infinite upper bound, which // we've already outlined is problematic. { RegexNode node = rootNode.Child(0); // skip implicit root capture node bool atomicByAncestry = true; // the root is implicitly atomic because nothing comes after it (same for the implicit root capture) while (true) { switch (node.Kind) { case RegexNodeKind.Atomic: node = node.Child(0); continue; case RegexNodeKind.Concatenate: atomicByAncestry = false; node = node.Child(0); continue; case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when node.N == int.MaxValue: case RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy when node.N == int.MaxValue && !atomicByAncestry: if (node.Parent is { Kind: RegexNodeKind.Concatenate } parent) { parent.InsertChild(1, new RegexNode(RegexNodeKind.UpdateBumpalong, node.Options)); } break; } break; } } } // Done optimizing. Return the final tree. #if DEBUG rootNode.ValidateFinalTreeInvariants(); #endif return rootNode; } /// <summary>Converts nodes at the end of the node tree to be atomic.</summary> /// <remarks> /// The correctness of this optimization depends on nothing being able to backtrack into /// the provided node. That means it must be at the root of the overall expression, or /// it must be an Atomic node that nothing will backtrack into by the very nature of Atomic. /// </remarks> private void EliminateEndingBacktracking() { if (!StackHelper.TryEnsureSufficientExecutionStack() || (Options & (RegexOptions.RightToLeft | RegexOptions.NonBacktracking)) != 0) { // If we can't recur further, just stop optimizing. // We haven't done the work to validate this is correct for RTL. // And NonBacktracking doesn't support atomic groups and doesn't have backtracking to be eliminated. return; } // Walk the tree starting from the current node. RegexNode node = this; while (true) { switch (node.Kind) { // {One/Notone/Set}loops can be upgraded to {One/Notone/Set}loopatomic nodes, e.g. [abc]* => (?>[abc]*). // And {One/Notone/Set}lazys can similarly be upgraded to be atomic, which really makes them into repeaters // or even empty nodes. case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop: case RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy: node.MakeLoopAtomic(); break; // Just because a particular node is atomic doesn't mean all its descendants are. // Process them as well. Lookarounds are implicitly atomic. case RegexNodeKind.Atomic: case RegexNodeKind.PositiveLookaround: case RegexNodeKind.NegativeLookaround: node = node.Child(0); continue; // For Capture and Concatenate, we just recur into their last child (only child in the case // of Capture). However, if the child is an alternation or loop, we can also make the // node itself atomic by wrapping it in an Atomic node. Since we later check to see whether a // node is atomic based on its parent or grandparent, we don't bother wrapping such a node in // an Atomic one if its grandparent is already Atomic. // e.g. [xyz](?:abc|def) => [xyz](?>abc|def) case RegexNodeKind.Capture: case RegexNodeKind.Concatenate: RegexNode existingChild = node.Child(node.ChildCount() - 1); if ((existingChild.Kind is RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional or RegexNodeKind.Loop or RegexNodeKind.Lazyloop) && (node.Parent is null || node.Parent.Kind != RegexNodeKind.Atomic)) // validate grandparent isn't atomic { var atomic = new RegexNode(RegexNodeKind.Atomic, existingChild.Options); atomic.AddChild(existingChild); node.ReplaceChild(node.ChildCount() - 1, atomic); } node = existingChild; continue; // For alternate, we can recur into each branch separately. We use this iteration for the first branch. // Conditionals are just like alternations in this regard. // e.g. abc*|def* => ab(?>c*)|de(?>f*) case RegexNodeKind.Alternate: case RegexNodeKind.BackreferenceConditional: case RegexNodeKind.ExpressionConditional: { int branches = node.ChildCount(); for (int i = 1; i < branches; i++) { node.Child(i).EliminateEndingBacktracking(); } if (node.Kind != RegexNodeKind.ExpressionConditional) // ReduceExpressionConditional will have already applied ending backtracking removal { node = node.Child(0); continue; } } break; // For {Lazy}Loop, we search to see if there's a viable last expression, and iff there // is we recur into processing it. Also, as with the single-char lazy loops, LazyLoop // can have its max iteration count dropped to its min iteration count, as there's no // reason for it to match more than the minimal at the end; that in turn makes it a // repeater, which results in better code generation. // e.g. (?:abc*)* => (?:ab(?>c*))* // e.g. (abc*?)+? => (ab){1} case RegexNodeKind.Lazyloop: node.N = node.M; goto case RegexNodeKind.Loop; case RegexNodeKind.Loop: { if (node.N == 1) { // If the loop has a max iteration count of 1 (e.g. it's an optional node), // there's no possibility for conflict between multiple iterations, so // we can process it. node = node.Child(0); continue; } RegexNode? loopDescendent = node.FindLastExpressionInLoopForAutoAtomic(); if (loopDescendent != null) { node = loopDescendent; continue; // loop around to process node } } break; } break; } } /// <summary> /// Removes redundant nodes from the subtree, and returns an optimized subtree. /// </summary> internal RegexNode Reduce() { // TODO: https://github.com/dotnet/runtime/issues/61048 // As part of overhauling IgnoreCase handling, the parser shouldn't produce any nodes other than Backreference // that ever have IgnoreCase set on them. For now, though, remove IgnoreCase from any nodes for which it // has no behavioral effect. switch (Kind) { default: // No effect Options &= ~RegexOptions.IgnoreCase; break; case RegexNodeKind.One or RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notone or RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Set or RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic: case RegexNodeKind.Multi: case RegexNodeKind.Backreference: // Still meaningful break; } return Kind switch { RegexNodeKind.Alternate => ReduceAlternation(), RegexNodeKind.Atomic => ReduceAtomic(), RegexNodeKind.Concatenate => ReduceConcatenation(), RegexNodeKind.Group => ReduceGroup(), RegexNodeKind.Loop or RegexNodeKind.Lazyloop => ReduceLoops(), RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround => ReduceLookaround(), RegexNodeKind.Set or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy => ReduceSet(), RegexNodeKind.ExpressionConditional => ReduceExpressionConditional(), RegexNodeKind.BackreferenceConditional => ReduceBackreferenceConditional(), _ => this, }; } /// <summary>Remove an unnecessary Concatenation or Alternation node</summary> /// <remarks> /// Simple optimization for a concatenation or alternation: /// - if the node has only one child, use it instead /// - if the node has zero children, turn it into an empty with Nothing for an alternation or Empty for a concatenation /// </remarks> private RegexNode ReplaceNodeIfUnnecessary() { Debug.Assert(Kind is RegexNodeKind.Alternate or RegexNodeKind.Concatenate); return ChildCount() switch { 0 => new RegexNode(Kind == RegexNodeKind.Alternate ? RegexNodeKind.Nothing : RegexNodeKind.Empty, Options), 1 => Child(0), _ => this, }; } /// <summary>Remove all non-capturing groups.</summary> /// <remark> /// Simple optimization: once parsed into a tree, non-capturing groups /// serve no function, so strip them out. /// e.g. (?:(?:(?:abc))) => abc /// </remark> private RegexNode ReduceGroup() { Debug.Assert(Kind == RegexNodeKind.Group); RegexNode u = this; while (u.Kind == RegexNodeKind.Group) { Debug.Assert(u.ChildCount() == 1); u = u.Child(0); } return u; } /// <summary> /// Remove unnecessary atomic nodes, and make appropriate descendents of the atomic node themselves atomic. /// </summary> /// <remarks> /// e.g. (?>(?>(?>a*))) => (?>a*) /// e.g. (?>(abc*)*) => (?>(abc(?>c*))*) /// </remarks> private RegexNode ReduceAtomic() { // RegexOptions.NonBacktracking doesn't support atomic groups, so when that option // is set we don't want to create atomic groups where they weren't explicitly authored. if ((Options & RegexOptions.NonBacktracking) != 0) { return this; } Debug.Assert(Kind == RegexNodeKind.Atomic); Debug.Assert(ChildCount() == 1); RegexNode atomic = this; RegexNode child = Child(0); while (child.Kind == RegexNodeKind.Atomic) { atomic = child; child = atomic.Child(0); } switch (child.Kind) { // If the child is empty/nothing, there's nothing to be made atomic so the Atomic // node can simply be removed. case RegexNodeKind.Empty: case RegexNodeKind.Nothing: return child; // If the child is already atomic, we can just remove the atomic node. case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: return child; // If an atomic subexpression contains only a {one/notone/set}{loop/lazy}, // change it to be an {one/notone/set}loopatomic and remove the atomic node. case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: child.MakeLoopAtomic(); return child; // Alternations have a variety of possible optimizations that can be applied // iff they're atomic. case RegexNodeKind.Alternate: if ((Options & RegexOptions.RightToLeft) == 0) { List<RegexNode>? branches = child.Children as List<RegexNode>; Debug.Assert(branches is not null && branches.Count != 0); // If an alternation is atomic and its first branch is Empty, the whole thing // is a nop, as Empty will match everything trivially, and no backtracking // into the node will be performed, making the remaining branches irrelevant. if (branches[0].Kind == RegexNodeKind.Empty) { return new RegexNode(RegexNodeKind.Empty, child.Options); } // Similarly, we can trim off any branches after an Empty, as they'll never be used. // An Empty will match anything, and thus branches after that would only be used // if we backtracked into it and advanced passed the Empty after trying the Empty... // but if the alternation is atomic, such backtracking won't happen. for (int i = 1; i < branches.Count - 1; i++) { if (branches[i].Kind == RegexNodeKind.Empty) { branches.RemoveRange(i + 1, branches.Count - (i + 1)); break; } } // If an alternation is atomic, we won't ever backtrack back into it, which // means order matters but not repetition. With backtracking, it would be incorrect // to convert an expression like "hi|there|hello" into "hi|hello|there", as doing // so could then change the order of results if we matched "hi" and then failed // based on what came after it, and both "hello" and "there" could be successful // with what came later. But without backtracking, we can reorder "hi|there|hello" // to instead be "hi|hello|there", as "hello" and "there" can't match the same text, // and once this atomic alternation has matched, we won't try another branch. This // reordering is valuable as it then enables further optimizations, e.g. // "hi|there|hello" => "hi|hello|there" => "h(?:i|ello)|there", which means we only // need to check the 'h' once in case it's not an 'h', and it's easier to employ different // code gen that, for example, switches on first character of the branches, enabling faster // choice of branch without always having to walk through each. bool reordered = false; for (int start = 0; start < branches.Count; start++) { // Get the node that may start our range. If it's a one, multi, or concat of those, proceed. RegexNode startNode = branches[start]; if (startNode.FindBranchOneOrMultiStart() is null) { continue; } // Find the contiguous range of nodes from this point that are similarly one, multi, or concat of those. int endExclusive = start + 1; while (endExclusive < branches.Count && branches[endExclusive].FindBranchOneOrMultiStart() is not null) { endExclusive++; } // If there's at least 3, there may be something to reorder (we won't reorder anything // before the starting position, and so only 2 items is considered ordered). if (endExclusive - start >= 3) { int compare = start; while (compare < endExclusive) { // Get the starting character char c = branches[compare].FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti(); // Move compare to point to the last branch that has the same starting value. while (compare < endExclusive && branches[compare].FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti() == c) { compare++; } // Compare now points to the first node that doesn't match the starting node. // If we've walked off our range, there's nothing left to reorder. if (compare < endExclusive) { // There may be something to reorder. See if there are any other nodes that begin with the same character. for (int next = compare + 1; next < endExclusive; next++) { RegexNode nextChild = branches[next]; if (nextChild.FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti() == c) { branches.RemoveAt(next); branches.Insert(compare++, nextChild); reordered = true; } } } } } // Move to the end of the range we've now explored. endExclusive is not a viable // starting position either, and the start++ for the loop will thus take us to // the next potential place to start a range. start = endExclusive; } // If anything was reordered, there may be new optimization opportunities inside // of the alternation, so reduce it again. if (reordered) { atomic.ReplaceChild(0, child); child = atomic.Child(0); } } goto default; // For everything else, try to reduce ending backtracking of the last contained expression. default: child.EliminateEndingBacktracking(); return atomic; } } /// <summary>Combine nested loops where applicable.</summary> /// <remarks> /// Nested repeaters just get multiplied with each other if they're not too lumpy. /// Other optimizations may have also resulted in {Lazy}loops directly containing /// sets, ones, and notones, in which case they can be transformed into the corresponding /// individual looping constructs. /// </remarks> private RegexNode ReduceLoops() { Debug.Assert(Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop); RegexNode u = this; RegexNodeKind kind = Kind; int min = M; int max = N; while (u.ChildCount() > 0) { RegexNode child = u.Child(0); // multiply reps of the same type only if (child.Kind != kind) { bool valid = false; if (kind == RegexNodeKind.Loop) { switch (child.Kind) { case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: valid = true; break; } } else // type == Lazyloop { switch (child.Kind) { case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: valid = true; break; } } if (!valid) { break; } } // child can be too lumpy to blur, e.g., (a {100,105}) {3} or (a {2,})? // [but things like (a {2,})+ are not too lumpy...] if (u.M == 0 && child.M > 1 || child.N < child.M * 2) { break; } u = child; if (u.M > 0) { u.M = min = ((int.MaxValue - 1) / u.M < min) ? int.MaxValue : u.M * min; } if (u.N > 0) { u.N = max = ((int.MaxValue - 1) / u.N < max) ? int.MaxValue : u.N * max; } } if (min == int.MaxValue) { return new RegexNode(RegexNodeKind.Nothing, Options); } // If the Loop or Lazyloop now only has one child node and its a Set, One, or Notone, // reduce to just Setloop/lazy, Oneloop/lazy, or Notoneloop/lazy. The parser will // generally have only produced the latter, but other reductions could have exposed // this. if (u.ChildCount() == 1) { RegexNode child = u.Child(0); switch (child.Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: child.MakeRep(u.Kind == RegexNodeKind.Lazyloop ? RegexNodeKind.Onelazy : RegexNodeKind.Oneloop, u.M, u.N); u = child; break; } } return u; } /// <summary> /// Reduces set-related nodes to simpler one-related and notone-related nodes, where applicable. /// </summary> /// <remarks> /// e.g. /// [a] => a /// [a]* => a* /// [a]*? => a*? /// (?>[a]*) => (?>a*) /// [^a] => ^a /// []* => Nothing /// </remarks> private RegexNode ReduceSet() { // Extract empty-set, one, and not-one case as special Debug.Assert(Kind is RegexNodeKind.Set or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy); Debug.Assert(!string.IsNullOrEmpty(Str)); if (RegexCharClass.IsEmpty(Str)) { Kind = RegexNodeKind.Nothing; Str = null; } else if (RegexCharClass.IsSingleton(Str)) { Ch = RegexCharClass.SingletonChar(Str); Str = null; Kind = Kind == RegexNodeKind.Set ? RegexNodeKind.One : Kind == RegexNodeKind.Setloop ? RegexNodeKind.Oneloop : Kind == RegexNodeKind.Setloopatomic ? RegexNodeKind.Oneloopatomic : RegexNodeKind.Onelazy; } else if (RegexCharClass.IsSingletonInverse(Str)) { Ch = RegexCharClass.SingletonChar(Str); Str = null; Kind = Kind == RegexNodeKind.Set ? RegexNodeKind.Notone : Kind == RegexNodeKind.Setloop ? RegexNodeKind.Notoneloop : Kind == RegexNodeKind.Setloopatomic ? RegexNodeKind.Notoneloopatomic : RegexNodeKind.Notonelazy; } return this; } /// <summary>Optimize an alternation.</summary> private RegexNode ReduceAlternation() { Debug.Assert(Kind == RegexNodeKind.Alternate); switch (ChildCount()) { case 0: return new RegexNode(RegexNodeKind.Nothing, Options); case 1: return Child(0); default: ReduceSingleLetterAndNestedAlternations(); RegexNode node = ReplaceNodeIfUnnecessary(); if (node.Kind == RegexNodeKind.Alternate) { node = ExtractCommonPrefixText(node); if (node.Kind == RegexNodeKind.Alternate) { node = ExtractCommonPrefixOneNotoneSet(node); if (node.Kind == RegexNodeKind.Alternate) { node = RemoveRedundantEmptiesAndNothings(node); } } } return node; } // This function performs two optimizations: // - Single-letter alternations can be replaced by faster set specifications // e.g. "a|b|c|def|g|h" -> "[a-c]|def|[gh]" // - Nested alternations with no intervening operators can be flattened: // e.g. "apple|(?:orange|pear)|grape" -> "apple|orange|pear|grape" void ReduceSingleLetterAndNestedAlternations() { bool wasLastSet = false; bool lastNodeCannotMerge = false; RegexOptions optionsLast = 0; RegexOptions optionsAt; int i; int j; RegexNode at; RegexNode prev; List<RegexNode> children = (List<RegexNode>)Children!; for (i = 0, j = 0; i < children.Count; i++, j++) { at = children[i]; if (j < i) children[j] = at; while (true) { if (at.Kind == RegexNodeKind.Alternate) { if (at.Children is List<RegexNode> atChildren) { for (int k = 0; k < atChildren.Count; k++) { atChildren[k].Parent = this; } children.InsertRange(i + 1, atChildren); } else { RegexNode atChild = (RegexNode)at.Children!; atChild.Parent = this; children.Insert(i + 1, atChild); } j--; } else if (at.Kind is RegexNodeKind.Set or RegexNodeKind.One) { // Cannot merge sets if L or I options differ, or if either are negated. optionsAt = at.Options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase); if (at.Kind == RegexNodeKind.Set) { if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge || !RegexCharClass.IsMergeable(at.Str!)) { wasLastSet = true; lastNodeCannotMerge = !RegexCharClass.IsMergeable(at.Str!); optionsLast = optionsAt; break; } } else if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge) { wasLastSet = true; lastNodeCannotMerge = false; optionsLast = optionsAt; break; } // The last node was a Set or a One, we're a Set or One and our options are the same. // Merge the two nodes. j--; prev = children[j]; RegexCharClass prevCharClass; if (prev.Kind == RegexNodeKind.One) { prevCharClass = new RegexCharClass(); prevCharClass.AddChar(prev.Ch); } else { prevCharClass = RegexCharClass.Parse(prev.Str!); } if (at.Kind == RegexNodeKind.One) { prevCharClass.AddChar(at.Ch); } else { RegexCharClass atCharClass = RegexCharClass.Parse(at.Str!); prevCharClass.AddCharClass(atCharClass); } prev.Kind = RegexNodeKind.Set; prev.Str = prevCharClass.ToStringClass(Options); if ((prev.Options & RegexOptions.IgnoreCase) != 0 && RegexCharClass.MakeCaseSensitiveIfPossible(prev.Str, RegexParser.GetTargetCulture(prev.Options)) is string newSetString) { prev.Str = newSetString; prev.Options &= ~RegexOptions.IgnoreCase; } } else if (at.Kind == RegexNodeKind.Nothing) { j--; } else { wasLastSet = false; lastNodeCannotMerge = false; } break; } } if (j < i) { children.RemoveRange(j, i - j); } } // This function optimizes out prefix nodes from alternation branches that are // the same across multiple contiguous branches. // e.g. \w12|\d34|\d56|\w78|\w90 => \w12|\d(?:34|56)|\w(?:78|90) static RegexNode ExtractCommonPrefixOneNotoneSet(RegexNode alternation) { Debug.Assert(alternation.Kind == RegexNodeKind.Alternate); Debug.Assert(alternation.Children is List<RegexNode> { Count: >= 2 }); var children = (List<RegexNode>)alternation.Children; // Only process left-to-right prefixes. if ((alternation.Options & RegexOptions.RightToLeft) != 0) { return alternation; } // Only handle the case where each branch is a concatenation foreach (RegexNode child in children) { if (child.Kind != RegexNodeKind.Concatenate || child.ChildCount() < 2) { return alternation; } } for (int startingIndex = 0; startingIndex < children.Count - 1; startingIndex++) { Debug.Assert(children[startingIndex].Children is List<RegexNode> { Count: >= 2 }); // Only handle the case where each branch begins with the same One, Notone, or Set (individual or loop). // Note that while we can do this for individual characters, fixed length loops, and atomic loops, doing // it for non-atomic variable length loops could change behavior as each branch could otherwise have a // different number of characters consumed by the loop based on what's after it. RegexNode required = children[startingIndex].Child(0); switch (required.Kind) { case RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set: case RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloopatomic: case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop or RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy when required.M == required.N: break; default: continue; } // Only handle the case where each branch begins with the exact same node value int endingIndex = startingIndex + 1; for (; endingIndex < children.Count; endingIndex++) { RegexNode other = children[endingIndex].Child(0); if (required.Kind != other.Kind || required.Options != other.Options || required.M != other.M || required.N != other.N || required.Ch != other.Ch || required.Str != other.Str) { break; } } if (endingIndex - startingIndex <= 1) { // Nothing to extract from this starting index. continue; } // Remove the prefix node from every branch, adding it to a new alternation var newAlternate = new RegexNode(RegexNodeKind.Alternate, alternation.Options); for (int i = startingIndex; i < endingIndex; i++) { ((List<RegexNode>)children[i].Children!).RemoveAt(0); newAlternate.AddChild(children[i]); } // If this alternation is wrapped as atomic, we need to do the same for the new alternation. if (alternation.Parent is RegexNode { Kind: RegexNodeKind.Atomic } parent) { var atomic = new RegexNode(RegexNodeKind.Atomic, alternation.Options); atomic.AddChild(newAlternate); newAlternate = atomic; } // Now create a concatenation of the prefix node with the new alternation for the combined // branches, and replace all of the branches in this alternation with that new concatenation. var newConcat = new RegexNode(RegexNodeKind.Concatenate, alternation.Options); newConcat.AddChild(required); newConcat.AddChild(newAlternate); alternation.ReplaceChild(startingIndex, newConcat); children.RemoveRange(startingIndex + 1, endingIndex - startingIndex - 1); } return alternation.ReplaceNodeIfUnnecessary(); } // Removes unnecessary Empty and Nothing nodes from the alternation. A Nothing will never // match, so it can be removed entirely, and an Empty can be removed if there's a previous // Empty in the alternation: it's an extreme case of just having a repeated branch in an // alternation, and while we don't check for all duplicates, checking for empty is easy. static RegexNode RemoveRedundantEmptiesAndNothings(RegexNode node) { Debug.Assert(node.Kind == RegexNodeKind.Alternate); Debug.Assert(node.ChildCount() >= 2); var children = (List<RegexNode>)node.Children!; int i = 0, j = 0; bool seenEmpty = false; while (i < children.Count) { RegexNode child = children[i]; switch (child.Kind) { case RegexNodeKind.Empty when !seenEmpty: seenEmpty = true; goto default; case RegexNodeKind.Empty: case RegexNodeKind.Nothing: i++; break; default: children[j] = children[i]; i++; j++; break; } } children.RemoveRange(j, children.Count - j); return node.ReplaceNodeIfUnnecessary(); } // Analyzes all the branches of the alternation for text that's identical at the beginning // of every branch. That text is then pulled out into its own one or multi node in a // concatenation with the alternation (whose branches are updated to remove that prefix). // This is valuable for a few reasons. One, it exposes potentially more text to the // expression prefix analyzer used to influence FindFirstChar. Second, it exposes more // potential alternation optimizations, e.g. if the same prefix is followed in two branches // by sets that can be merged. Third, it reduces the amount of duplicated comparisons required // if we end up backtracking into subsequent branches. // e.g. abc|ade => a(?bc|de) static RegexNode ExtractCommonPrefixText(RegexNode alternation) { Debug.Assert(alternation.Kind == RegexNodeKind.Alternate); Debug.Assert(alternation.Children is List<RegexNode> { Count: >= 2 }); var children = (List<RegexNode>)alternation.Children; // To keep things relatively simple, we currently only handle: // - Left to right (e.g. we don't process alternations in lookbehinds) // - Branches that are one or multi nodes, or that are concatenations beginning with one or multi nodes. // - All branches having the same options. // Only extract left-to-right prefixes. if ((alternation.Options & RegexOptions.RightToLeft) != 0) { return alternation; } Span<char> scratchChar = stackalloc char[1]; ReadOnlySpan<char> startingSpan = stackalloc char[0]; for (int startingIndex = 0; startingIndex < children.Count - 1; startingIndex++) { // Process the first branch to get the maximum possible common string. RegexNode? startingNode = children[startingIndex].FindBranchOneOrMultiStart(); if (startingNode is null) { return alternation; } RegexOptions startingNodeOptions = startingNode.Options; startingSpan = startingNode.Str.AsSpan(); if (startingNode.Kind == RegexNodeKind.One) { scratchChar[0] = startingNode.Ch; startingSpan = scratchChar; } Debug.Assert(startingSpan.Length > 0); // Now compare the rest of the branches against it. int endingIndex = startingIndex + 1; for (; endingIndex < children.Count; endingIndex++) { // Get the starting node of the next branch. startingNode = children[endingIndex].FindBranchOneOrMultiStart(); if (startingNode is null || startingNode.Options != startingNodeOptions) { break; } // See if the new branch's prefix has a shared prefix with the current one. // If it does, shorten to that; if it doesn't, bail. if (startingNode.Kind == RegexNodeKind.One) { if (startingSpan[0] != startingNode.Ch) { break; } if (startingSpan.Length != 1) { startingSpan = startingSpan.Slice(0, 1); } } else { Debug.Assert(startingNode.Kind == RegexNodeKind.Multi); Debug.Assert(startingNode.Str!.Length > 0); int minLength = Math.Min(startingSpan.Length, startingNode.Str.Length); int c = 0; while (c < minLength && startingSpan[c] == startingNode.Str[c]) c++; if (c == 0) { break; } startingSpan = startingSpan.Slice(0, c); } } // When we get here, we have a starting string prefix shared by all branches // in the range [startingIndex, endingIndex). if (endingIndex - startingIndex <= 1) { // There's nothing to consolidate for this starting node. continue; } // We should be able to consolidate something for the nodes in the range [startingIndex, endingIndex). Debug.Assert(startingSpan.Length > 0); // Create a new node of the form: // Concatenation(prefix, Alternation(each | node | with | prefix | removed)) // that replaces all these branches in this alternation. var prefix = startingSpan.Length == 1 ? new RegexNode(RegexNodeKind.One, startingNodeOptions, startingSpan[0]) : new RegexNode(RegexNodeKind.Multi, startingNodeOptions, startingSpan.ToString()); var newAlternate = new RegexNode(RegexNodeKind.Alternate, startingNodeOptions); for (int i = startingIndex; i < endingIndex; i++) { RegexNode branch = children[i]; ProcessOneOrMulti(branch.Kind == RegexNodeKind.Concatenate ? branch.Child(0) : branch, startingSpan); branch = branch.Reduce(); newAlternate.AddChild(branch); // Remove the starting text from the one or multi node. This may end up changing // the type of the node to be Empty if the starting text matches the node's full value. static void ProcessOneOrMulti(RegexNode node, ReadOnlySpan<char> startingSpan) { if (node.Kind == RegexNodeKind.One) { Debug.Assert(startingSpan.Length == 1); Debug.Assert(startingSpan[0] == node.Ch); node.Kind = RegexNodeKind.Empty; node.Ch = '\0'; } else { Debug.Assert(node.Kind == RegexNodeKind.Multi); Debug.Assert(node.Str.AsSpan().StartsWith(startingSpan, StringComparison.Ordinal)); if (node.Str!.Length == startingSpan.Length) { node.Kind = RegexNodeKind.Empty; node.Str = null; } else if (node.Str.Length - 1 == startingSpan.Length) { node.Kind = RegexNodeKind.One; node.Ch = node.Str[node.Str.Length - 1]; node.Str = null; } else { node.Str = node.Str.Substring(startingSpan.Length); } } } } if (alternation.Parent is RegexNode parent && parent.Kind == RegexNodeKind.Atomic) { var atomic = new RegexNode(RegexNodeKind.Atomic, startingNodeOptions); atomic.AddChild(newAlternate); newAlternate = atomic; } var newConcat = new RegexNode(RegexNodeKind.Concatenate, startingNodeOptions); newConcat.AddChild(prefix); newConcat.AddChild(newAlternate); alternation.ReplaceChild(startingIndex, newConcat); children.RemoveRange(startingIndex + 1, endingIndex - startingIndex - 1); } return alternation.ChildCount() == 1 ? alternation.Child(0) : alternation; } } /// <summary> /// Finds the starting one or multi of the branch, if it has one; otherwise, returns null. /// For simplicity, this only considers branches that are One or Multi, or a Concatenation /// beginning with a One or Multi. We don't traverse more than one level to avoid the /// complication of then having to later update that hierarchy when removing the prefix, /// but it could be done in the future if proven beneficial enough. /// </summary> public RegexNode? FindBranchOneOrMultiStart() { RegexNode branch = Kind == RegexNodeKind.Concatenate ? Child(0) : this; return branch.Kind is RegexNodeKind.One or RegexNodeKind.Multi ? branch : null; } /// <summary>Same as <see cref="FindBranchOneOrMultiStart"/> but also for Sets.</summary> public RegexNode? FindBranchOneMultiOrSetStart() { RegexNode branch = Kind == RegexNodeKind.Concatenate ? Child(0) : this; return branch.Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set ? branch : null; } /// <summary>Gets the character that begins a One or Multi.</summary> public char FirstCharOfOneOrMulti() { Debug.Assert(Kind is RegexNodeKind.One or RegexNodeKind.Multi); Debug.Assert((Options & RegexOptions.RightToLeft) == 0); return Kind == RegexNodeKind.One ? Ch : Str![0]; } /// <summary>Finds the guaranteed beginning literal(s) of the node, or null if none exists.</summary> public (char Char, string? String, string? SetChars)? FindStartingLiteral(int maxSetCharacters = 5) // 5 is max optimized by IndexOfAny today { Debug.Assert(maxSetCharacters >= 0 && maxSetCharacters <= 128, $"{nameof(maxSetCharacters)} == {maxSetCharacters} should be small enough to be stack allocated."); RegexNode? node = this; while (true) { if (node is not null && (node.Options & RegexOptions.RightToLeft) == 0) { switch (node.Kind) { case RegexNodeKind.One: case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy when node.M > 0: if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(node.Ch)) { return (node.Ch, null, null); } break; case RegexNodeKind.Multi: if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(node.Str.AsSpan())) { return ('\0', node.Str, null); } break; case RegexNodeKind.Set: case RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy when node.M > 0: Span<char> setChars = stackalloc char[maxSetCharacters]; int numChars; if (!RegexCharClass.IsNegated(node.Str!) && (numChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0) { setChars = setChars.Slice(0, numChars); if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(setChars)) { return ('\0', null, setChars.ToString()); } } break; case RegexNodeKind.Atomic: case RegexNodeKind.Concatenate: case RegexNodeKind.Capture: case RegexNodeKind.Group: case RegexNodeKind.Loop or RegexNodeKind.Lazyloop when node.M > 0: case RegexNodeKind.PositiveLookaround: node = node.Child(0); continue; } } return null; } } /// <summary> /// Optimizes a concatenation by coalescing adjacent characters and strings, /// coalescing adjacent loops, converting loops to be atomic where applicable, /// and removing the concatenation itself if it's unnecessary. /// </summary> private RegexNode ReduceConcatenation() { Debug.Assert(Kind == RegexNodeKind.Concatenate); // If the concat node has zero or only one child, get rid of the concat. switch (ChildCount()) { case 0: return new RegexNode(RegexNodeKind.Empty, Options); case 1: return Child(0); } // Coalesce adjacent loops. This helps to minimize work done by the interpreter, minimize code gen, // and also help to reduce catastrophic backtracking. ReduceConcatenationWithAdjacentLoops(); // Coalesce adjacent characters/strings. This is done after the adjacent loop coalescing so that // a One adjacent to both a Multi and a Loop prefers being folded into the Loop rather than into // the Multi. Doing so helps with auto-atomicity when it's later applied. ReduceConcatenationWithAdjacentStrings(); // If the concatenation is now empty, return an empty node, or if it's got a single child, return that child. // Otherwise, return this. return ReplaceNodeIfUnnecessary(); } /// <summary> /// Combine adjacent characters/strings. /// e.g. (?:abc)(?:def) -> abcdef /// </summary> private void ReduceConcatenationWithAdjacentStrings() { Debug.Assert(Kind == RegexNodeKind.Concatenate); Debug.Assert(Children is List<RegexNode>); bool wasLastString = false; RegexOptions optionsLast = 0; int i, j; List<RegexNode> children = (List<RegexNode>)Children!; for (i = 0, j = 0; i < children.Count; i++, j++) { RegexNode at = children[i]; if (j < i) { children[j] = at; } if (at.Kind == RegexNodeKind.Concatenate && ((at.Options & RegexOptions.RightToLeft) == (Options & RegexOptions.RightToLeft))) { if (at.Children is List<RegexNode> atChildren) { for (int k = 0; k < atChildren.Count; k++) { atChildren[k].Parent = this; } children.InsertRange(i + 1, atChildren); } else { RegexNode atChild = (RegexNode)at.Children!; atChild.Parent = this; children.Insert(i + 1, atChild); } j--; } else if (at.Kind is RegexNodeKind.Multi or RegexNodeKind.One) { // Cannot merge strings if L or I options differ RegexOptions optionsAt = at.Options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase); if (!wasLastString || optionsLast != optionsAt) { wasLastString = true; optionsLast = optionsAt; continue; } RegexNode prev = children[--j]; if (prev.Kind == RegexNodeKind.One) { prev.Kind = RegexNodeKind.Multi; prev.Str = prev.Ch.ToString(); } if ((optionsAt & RegexOptions.RightToLeft) == 0) { prev.Str = (at.Kind == RegexNodeKind.One) ? $"{prev.Str}{at.Ch}" : prev.Str + at.Str; } else { prev.Str = (at.Kind == RegexNodeKind.One) ? $"{at.Ch}{prev.Str}" : at.Str + prev.Str; } } else if (at.Kind == RegexNodeKind.Empty) { j--; } else { wasLastString = false; } } if (j < i) { children.RemoveRange(j, i - j); } } /// <summary> /// Combine adjacent loops. /// e.g. a*a*a* => a* /// e.g. a+ab => a{2,}b /// </summary> private void ReduceConcatenationWithAdjacentLoops() { Debug.Assert(Kind == RegexNodeKind.Concatenate); Debug.Assert(Children is List<RegexNode>); var children = (List<RegexNode>)Children!; int current = 0, next = 1, nextSave = 1; while (next < children.Count) { RegexNode currentNode = children[current]; RegexNode nextNode = children[next]; if (currentNode.Options == nextNode.Options) { static bool CanCombineCounts(int nodeMin, int nodeMax, int nextMin, int nextMax) { // We shouldn't have an infinite minimum; bail if we find one. Also check for the // degenerate case where we'd make the min overflow or go infinite when it wasn't already. if (nodeMin == int.MaxValue || nextMin == int.MaxValue || (uint)nodeMin + (uint)nextMin >= int.MaxValue) { return false; } // Similar overflow / go infinite check for max (which can be infinite). if (nodeMax != int.MaxValue && nextMax != int.MaxValue && (uint)nodeMax + (uint)nextMax >= int.MaxValue) { return false; } return true; } switch (currentNode.Kind) { // Coalescing a loop with its same type case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy when nextNode.Kind == currentNode.Kind && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy when nextNode.Kind == currentNode.Kind && currentNode.Str == nextNode.Str: if (CanCombineCounts(currentNode.M, currentNode.N, nextNode.M, nextNode.N)) { currentNode.M += nextNode.M; if (currentNode.N != int.MaxValue) { currentNode.N = nextNode.N == int.MaxValue ? int.MaxValue : currentNode.N + nextNode.N; } next++; continue; } break; // Coalescing a loop with an additional item of the same type case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy when nextNode.Kind == RegexNodeKind.One && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy when nextNode.Kind == RegexNodeKind.Notone && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy when nextNode.Kind == RegexNodeKind.Set && currentNode.Str == nextNode.Str: if (CanCombineCounts(currentNode.M, currentNode.N, 1, 1)) { currentNode.M++; if (currentNode.N != int.MaxValue) { currentNode.N++; } next++; continue; } break; // Coalescing a loop with a subsequent string case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy when nextNode.Kind == RegexNodeKind.Multi && currentNode.Ch == nextNode.Str![0]: { // Determine how many of the multi's characters can be combined. // We already checked for the first, so we know it's at least one. int matchingCharsInMulti = 1; while (matchingCharsInMulti < nextNode.Str.Length && currentNode.Ch == nextNode.Str[matchingCharsInMulti]) { matchingCharsInMulti++; } if (CanCombineCounts(currentNode.M, currentNode.N, matchingCharsInMulti, matchingCharsInMulti)) { // Update the loop's bounds to include those characters from the multi currentNode.M += matchingCharsInMulti; if (currentNode.N != int.MaxValue) { currentNode.N += matchingCharsInMulti; } // If it was the full multi, skip/remove the multi and continue processing this loop. if (nextNode.Str.Length == matchingCharsInMulti) { next++; continue; } // Otherwise, trim the characters from the multiple that were absorbed into the loop. // If it now only has a single character, it becomes a One. Debug.Assert(matchingCharsInMulti < nextNode.Str.Length); if (nextNode.Str.Length - matchingCharsInMulti == 1) { nextNode.Kind = RegexNodeKind.One; nextNode.Ch = nextNode.Str[nextNode.Str.Length - 1]; nextNode.Str = null; } else { nextNode.Str = nextNode.Str.Substring(matchingCharsInMulti); } } } break; // NOTE: We could add support for coalescing a string with a subsequent loop, but the benefits of that // are limited. Pulling a subsequent string's prefix back into the loop helps with making the loop atomic, // but if the loop is after the string, pulling the suffix of the string forward into the loop may actually // be a deoptimization as those characters could end up matching more slowly as part of loop matching. // Coalescing an individual item with a loop. case RegexNodeKind.One when (nextNode.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy) && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Notone when (nextNode.Kind is RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy) && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Set when (nextNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy) && currentNode.Str == nextNode.Str: if (CanCombineCounts(1, 1, nextNode.M, nextNode.N)) { currentNode.Kind = nextNode.Kind; currentNode.M = nextNode.M + 1; currentNode.N = nextNode.N == int.MaxValue ? int.MaxValue : nextNode.N + 1; next++; continue; } break; // Coalescing an individual item with another individual item. // We don't coalesce adjacent One nodes into a Oneloop as we'd rather they be joined into a Multi. case RegexNodeKind.Notone when nextNode.Kind == currentNode.Kind && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Set when nextNode.Kind == RegexNodeKind.Set && currentNode.Str == nextNode.Str: currentNode.MakeRep(RegexNodeKind.Oneloop, 2, 2); next++; continue; } } children[nextSave++] = children[next]; current = next; next++; } if (nextSave < children.Count) { children.RemoveRange(nextSave, children.Count - nextSave); } } /// <summary> /// Finds {one/notone/set}loop nodes in the concatenation that can be automatically upgraded /// to {one/notone/set}loopatomic nodes. Such changes avoid potential useless backtracking. /// e.g. A*B (where sets A and B don't overlap) => (?>A*)B. /// </summary> private void FindAndMakeLoopsAtomic() { Debug.Assert((Options & RegexOptions.NonBacktracking) == 0, "Atomic groups aren't supported and don't help performance with NonBacktracking"); if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we're too deep on the stack, give up optimizing further. return; } if ((Options & RegexOptions.RightToLeft) != 0) { // RTL is so rare, we don't need to spend additional time/code optimizing for it. return; } // For all node types that have children, recur into each of those children. int childCount = ChildCount(); if (childCount != 0) { for (int i = 0; i < childCount; i++) { Child(i).FindAndMakeLoopsAtomic(); } } // If this isn't a concatenation, nothing more to do. if (Kind is not RegexNodeKind.Concatenate) { return; } // This is a concatenation. Iterate through each pair of nodes in the concatenation seeing whether we can // make the first node (or its right-most child) atomic based on the second node (or its left-most child). Debug.Assert(Children is List<RegexNode>); var children = (List<RegexNode>)Children; for (int i = 0; i < childCount - 1; i++) { ProcessNode(children[i], children[i + 1]); static void ProcessNode(RegexNode node, RegexNode subsequent) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, just stop optimizing. return; } // Skip down the node past irrelevant nodes. while (true) { // We can always recur into captures and into the last node of concatenations. if (node.Kind is RegexNodeKind.Capture or RegexNodeKind.Concatenate) { node = node.Child(node.ChildCount() - 1); continue; } // For loops with at least one guaranteed iteration, we can recur into them, but // we need to be careful not to just always do so; the ending node of a loop can only // be made atomic if what comes after the loop but also the beginning of the loop are // compatible for the optimization. if (node.Kind == RegexNodeKind.Loop) { RegexNode? loopDescendent = node.FindLastExpressionInLoopForAutoAtomic(); if (loopDescendent != null) { node = loopDescendent; continue; } } // Can't skip any further. break; } // If the node can be changed to atomic based on what comes after it, do so. switch (node.Kind) { case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop when CanBeMadeAtomic(node, subsequent, allowSubsequentIteration: true): node.MakeLoopAtomic(); break; case RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional: // In the case of alternation, we can't change the alternation node itself // based on what comes after it (at least not with more complicated analysis // that factors in all branches together), but we can look at each individual // branch, and analyze ending loops in each branch individually to see if they // can be made atomic. Then if we do end up backtracking into the alternation, // we at least won't need to backtrack into that loop. The same is true for // conditionals, though we don't want to process the condition expression // itself, as it's already considered atomic and handled as part of ReduceExpressionConditional. { int alternateBranches = node.ChildCount(); for (int b = node.Kind == RegexNodeKind.ExpressionConditional ? 1 : 0; b < alternateBranches; b++) { ProcessNode(node.Child(b), subsequent); } } break; } } } } /// <summary> /// Recurs into the last expression of a loop node, looking to see if it can find a node /// that could be made atomic _assuming_ the conditions exist for it with the loop's ancestors. /// </summary> /// <returns>The found node that should be explored further for auto-atomicity; null if it doesn't exist.</returns> private RegexNode? FindLastExpressionInLoopForAutoAtomic() { RegexNode node = this; Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop); // Start by looking at the loop's sole child. node = node.Child(0); // Skip past captures. while (node.Kind == RegexNodeKind.Capture) { node = node.Child(0); } // If the loop's body is a concatenate, we can skip to its last child iff that // last child doesn't conflict with the first child, since this whole concatenation // could be repeated, such that the first node ends up following the last. For // example, in the expression (a+[def])*, the last child is [def] and the first is // a+, which can't possibly overlap with [def]. In contrast, if we had (a+[ade])*, // [ade] could potentially match the starting 'a'. if (node.Kind == RegexNodeKind.Concatenate) { int concatCount = node.ChildCount(); RegexNode lastConcatChild = node.Child(concatCount - 1); if (CanBeMadeAtomic(lastConcatChild, node.Child(0), allowSubsequentIteration: false)) { return lastConcatChild; } } // Otherwise, the loop has nothing that can participate in auto-atomicity. return null; } /// <summary>Optimizations for positive and negative lookaheads/behinds.</summary> private RegexNode ReduceLookaround() { Debug.Assert(Kind is RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround); Debug.Assert(ChildCount() == 1); // A lookaround is a zero-width atomic assertion. // As it's atomic, nothing will backtrack into it, and we can // eliminate any ending backtracking from it. EliminateEndingBacktracking(); // A positive lookaround wrapped around an empty is a nop, and we can reduce it // to simply Empty. A developer typically doesn't write this, but rather it evolves // due to optimizations resulting in empty. // A negative lookaround wrapped around an empty child, i.e. (?!), is // sometimes used as a way to insert a guaranteed no-match into the expression, // often as part of a conditional. We can reduce it to simply Nothing. if (Child(0).Kind == RegexNodeKind.Empty) { Kind = Kind == RegexNodeKind.PositiveLookaround ? RegexNodeKind.Empty : RegexNodeKind.Nothing; Children = null; } return this; } /// <summary>Optimizations for backreference conditionals.</summary> private RegexNode ReduceBackreferenceConditional() { Debug.Assert(Kind == RegexNodeKind.BackreferenceConditional); Debug.Assert(ChildCount() is 1 or 2); // This isn't so much an optimization as it is changing the tree for consistency. We want // all engines to be able to trust that every backreference conditional will have two children, // even though it's optional in the syntax. If it's missing a "not matched" branch, // we add one that will match empty. if (ChildCount() == 1) { AddChild(new RegexNode(RegexNodeKind.Empty, Options)); } return this; } /// <summary>Optimizations for expression conditionals.</summary> private RegexNode ReduceExpressionConditional() { Debug.Assert(Kind == RegexNodeKind.ExpressionConditional); Debug.Assert(ChildCount() is 2 or 3); // This isn't so much an optimization as it is changing the tree for consistency. We want // all engines to be able to trust that every expression conditional will have three children, // even though it's optional in the syntax. If it's missing a "not matched" branch, // we add one that will match empty. if (ChildCount() == 2) { AddChild(new RegexNode(RegexNodeKind.Empty, Options)); } // It's common for the condition to be an explicit positive lookahead, as specifying // that eliminates any ambiguity in syntax as to whether the expression is to be matched // as an expression or to be a reference to a capture group. After parsing, however, // there's no ambiguity, and we can remove an extra level of positive lookahead, as the // engines need to treat the condition as a zero-width positive, atomic assertion regardless. RegexNode condition = Child(0); if (condition.Kind == RegexNodeKind.PositiveLookaround && (condition.Options & RegexOptions.RightToLeft) == 0) { ReplaceChild(0, condition.Child(0)); } // We can also eliminate any ending backtracking in the condition, as the condition // is considered to be a positive lookahead, which is an atomic zero-width assertion. condition = Child(0); condition.EliminateEndingBacktracking(); return this; } /// <summary> /// Determines whether node can be switched to an atomic loop. Subsequent is the node /// immediately after 'node'. /// </summary> private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent, bool allowSubsequentIteration) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, just stop optimizing. return false; } // In most case, we'll simply check the node against whatever subsequent is. However, in case // subsequent ends up being a loop with a min bound of 0, we'll also need to evaluate the node // against whatever comes after subsequent. In that case, we'll walk the tree to find the // next subsequent, and we'll loop around against to perform the comparison again. while (true) { // Skip the successor down to the closest node that's guaranteed to follow it. int childCount; while ((childCount = subsequent.ChildCount()) > 0) { Debug.Assert(subsequent.Kind != RegexNodeKind.Group); switch (subsequent.Kind) { case RegexNodeKind.Concatenate: case RegexNodeKind.Capture: case RegexNodeKind.Atomic: case RegexNodeKind.PositiveLookaround when (subsequent.Options & RegexOptions.RightToLeft) == 0: // only lookaheads, not lookbehinds (represented as RTL PositiveLookaround nodes) case RegexNodeKind.Loop or RegexNodeKind.Lazyloop when subsequent.M > 0: subsequent = subsequent.Child(0); continue; } break; } // If the two nodes don't agree on options in any way, don't try to optimize them. // TODO: Remove this once https://github.com/dotnet/runtime/issues/61048 is implemented. if (node.Options != subsequent.Options) { return false; } // If the successor is an alternation, all of its children need to be evaluated, since any of them // could come after this node. If any of them fail the optimization, then the whole node fails. // This applies to expression conditionals as well, as long as they have both a yes and a no branch (if there's // only a yes branch, we'd need to also check whatever comes after the conditional). It doesn't apply to // backreference conditionals, as the condition itself is unknown statically and could overlap with the // loop being considered for atomicity. switch (subsequent.Kind) { case RegexNodeKind.Alternate: case RegexNodeKind.ExpressionConditional when childCount == 3: // condition, yes, and no branch for (int i = 0; i < childCount; i++) { if (!CanBeMadeAtomic(node, subsequent.Child(i), allowSubsequentIteration)) { return false; } } return true; } // If this node is a {one/notone/set}loop, see if it overlaps with its successor in the concatenation. // If it doesn't, then we can upgrade it to being a {one/notone/set}loopatomic. // Doing so avoids unnecessary backtracking. switch (node.Kind) { case RegexNodeKind.Oneloop: switch (subsequent.Kind) { case RegexNodeKind.One when node.Ch != subsequent.Ch: case RegexNodeKind.Notone when node.Ch == subsequent.Ch: case RegexNodeKind.Set when !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M > 0 && node.Ch != subsequent.Ch: case RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): case RegexNodeKind.Multi when node.Ch != subsequent.Str![0]: case RegexNodeKind.End: case RegexNodeKind.EndZ or RegexNodeKind.Eol when node.Ch != '\n': case RegexNodeKind.Boundary when RegexCharClass.IsBoundaryWordChar(node.Ch): case RegexNodeKind.NonBoundary when !RegexCharClass.IsBoundaryWordChar(node.Ch): case RegexNodeKind.ECMABoundary when RegexCharClass.IsECMAWordChar(node.Ch): case RegexNodeKind.NonECMABoundary when !RegexCharClass.IsECMAWordChar(node.Ch): return true; case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M == 0 && node.Ch != subsequent.Ch: case RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic when subsequent.M == 0 && node.Ch == subsequent.Ch: case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M == 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. break; default: return false; } break; case RegexNodeKind.Notoneloop: switch (subsequent.Kind) { case RegexNodeKind.One when node.Ch == subsequent.Ch: case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: case RegexNodeKind.Multi when node.Ch == subsequent.Str![0]: case RegexNodeKind.End: return true; case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M == 0 && node.Ch == subsequent.Ch: // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. break; default: return false; } break; case RegexNodeKind.Setloop: switch (subsequent.Kind) { case RegexNodeKind.One when !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case RegexNodeKind.Set when !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M > 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): case RegexNodeKind.Multi when !RegexCharClass.CharInClass(subsequent.Str![0], node.Str!): case RegexNodeKind.End: case RegexNodeKind.EndZ or RegexNodeKind.Eol when !RegexCharClass.CharInClass('\n', node.Str!): case RegexNodeKind.Boundary when node.Str is RegexCharClass.WordClass or RegexCharClass.DigitClass: case RegexNodeKind.NonBoundary when node.Str is RegexCharClass.NotWordClass or RegexCharClass.NotDigitClass: case RegexNodeKind.ECMABoundary when node.Str is RegexCharClass.ECMAWordClass or RegexCharClass.ECMADigitClass: case RegexNodeKind.NonECMABoundary when node.Str is RegexCharClass.NotECMAWordClass or RegexCharClass.NotDigitClass: return true; case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M == 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M == 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. break; default: return false; } break; default: return false; } // We only get here if the node could be made atomic based on subsequent but subsequent has a lower bound of zero // and thus we need to move subsequent to be the next node in sequence and loop around to try again. Debug.Assert(subsequent.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy); Debug.Assert(subsequent.M == 0); if (!allowSubsequentIteration) { return false; } // To be conservative, we only walk up through a very limited set of constructs (even though we may have walked // down through more, like loops), looking for the next concatenation that we're not at the end of, at // which point subsequent becomes whatever node is next in that concatenation. while (true) { RegexNode? parent = subsequent.Parent; switch (parent?.Kind) { case RegexNodeKind.Atomic: case RegexNodeKind.Alternate: case RegexNodeKind.Capture: subsequent = parent; continue; case RegexNodeKind.Concatenate: var peers = (List<RegexNode>)parent.Children!; int currentIndex = peers.IndexOf(subsequent); Debug.Assert(currentIndex >= 0, "Node should have been in its parent's child list"); if (currentIndex + 1 == peers.Count) { subsequent = parent; continue; } else { subsequent = peers[currentIndex + 1]; break; } case null: // If we hit the root, we're at the end of the expression, at which point nothing could backtrack // in and we can declare success. return true; default: // Anything else, we don't know what to do, so we have to assume it could conflict with the loop. return false; } break; } } } /// <summary>Computes a min bound on the required length of any string that could possibly match.</summary> /// <returns>The min computed length. If the result is 0, there is no minimum we can enforce.</returns> /// <remarks> /// e.g. abc[def](ghijkl|mn) => 6 /// </remarks> public int ComputeMinLength() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, assume there's no minimum we can enforce. return 0; } switch (Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: // Single character. return 1; case RegexNodeKind.Multi: // Every character in the string needs to match. return Str!.Length; case RegexNodeKind.Notonelazy: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Onelazy: case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Setlazy: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: // One character repeated at least M times. return M; case RegexNodeKind.Lazyloop: case RegexNodeKind.Loop: // A node graph repeated at least M times. return (int)Math.Min(int.MaxValue - 1, (long)M * Child(0).ComputeMinLength()); case RegexNodeKind.Alternate: // The minimum required length for any of the alternation's branches. { int childCount = ChildCount(); Debug.Assert(childCount >= 2); int min = Child(0).ComputeMinLength(); for (int i = 1; i < childCount && min > 0; i++) { min = Math.Min(min, Child(i).ComputeMinLength()); } return min; } case RegexNodeKind.BackreferenceConditional: // Minimum of its yes and no branches. The backreference doesn't add to the length. return Math.Min(Child(0).ComputeMinLength(), Child(1).ComputeMinLength()); case RegexNodeKind.ExpressionConditional: // Minimum of its yes and no branches. The condition is a zero-width assertion. return Math.Min(Child(1).ComputeMinLength(), Child(2).ComputeMinLength()); case RegexNodeKind.Concatenate: // The sum of all of the concatenation's children. { long sum = 0; int childCount = ChildCount(); for (int i = 0; i < childCount; i++) { sum += Child(i).ComputeMinLength(); } return (int)Math.Min(int.MaxValue - 1, sum); } case RegexNodeKind.Atomic: case RegexNodeKind.Capture: case RegexNodeKind.Group: // For groups, we just delegate to the sole child. Debug.Assert(ChildCount() == 1); return Child(0).ComputeMinLength(); case RegexNodeKind.Empty: case RegexNodeKind.Nothing: case RegexNodeKind.UpdateBumpalong: // Nothing to match. In the future, we could potentially use Nothing to say that the min length // is infinite, but that would require a different structure, as that would only apply if the // Nothing match is required in all cases (rather than, say, as one branch of an alternation). case RegexNodeKind.Beginning: case RegexNodeKind.Bol: case RegexNodeKind.Boundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.End: case RegexNodeKind.EndZ: case RegexNodeKind.Eol: case RegexNodeKind.NonBoundary: case RegexNodeKind.NonECMABoundary: case RegexNodeKind.Start: case RegexNodeKind.NegativeLookaround: case RegexNodeKind.PositiveLookaround: // Zero-width case RegexNodeKind.Backreference: // Requires matching data available only at run-time. In the future, we could choose to find // and follow the capture group this aligns with, while being careful not to end up in an // infinite cycle. return 0; default: Debug.Fail($"Unknown node: {Kind}"); goto case RegexNodeKind.Empty; } } /// <summary>Computes a maximum length of any string that could possibly match.</summary> /// <returns>The maximum length of any string that could possibly match, or null if the length may not always be the same.</returns> /// <remarks> /// e.g. abc[def](gh|ijklmnop) => 12 /// </remarks> public int? ComputeMaxLength() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, assume there's no minimum we can enforce. return null; } switch (Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: // Single character. return 1; case RegexNodeKind.Multi: // Every character in the string needs to match. return Str!.Length; case RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic: // Return the max number of iterations if there's an upper bound, or null if it's infinite return N == int.MaxValue ? null : N; case RegexNodeKind.Loop or RegexNodeKind.Lazyloop: if (N != int.MaxValue) { // A node graph repeated a fixed number of times if (Child(0).ComputeMaxLength() is int childMaxLength) { long maxLength = (long)N * childMaxLength; if (maxLength < int.MaxValue) { return (int)maxLength; } } } return null; case RegexNodeKind.Alternate: // The maximum length of any child branch, as long as they all have one. { int childCount = ChildCount(); Debug.Assert(childCount >= 2); if (Child(0).ComputeMaxLength() is not int maxLength) { return null; } for (int i = 1; i < childCount; i++) { if (Child(i).ComputeMaxLength() is not int next) { return null; } maxLength = Math.Max(maxLength, next); } return maxLength; } case RegexNodeKind.BackreferenceConditional: case RegexNodeKind.ExpressionConditional: // The maximum length of either child branch, as long as they both have one.. The condition for an expression conditional is a zero-width assertion. { int i = Kind == RegexNodeKind.BackreferenceConditional ? 0 : 1; return Child(i).ComputeMaxLength() is int yes && Child(i + 1).ComputeMaxLength() is int no ? Math.Max(yes, no) : null; } case RegexNodeKind.Concatenate: // The sum of all of the concatenation's children's max lengths, as long as they all have one. { long sum = 0; int childCount = ChildCount(); for (int i = 0; i < childCount; i++) { if (Child(i).ComputeMaxLength() is not int length) { return null; } sum += length; } if (sum < int.MaxValue) { return (int)sum; } return null; } case RegexNodeKind.Atomic: case RegexNodeKind.Capture: // For groups, we just delegate to the sole child. Debug.Assert(ChildCount() == 1); return Child(0).ComputeMaxLength(); case RegexNodeKind.Empty: case RegexNodeKind.Nothing: case RegexNodeKind.UpdateBumpalong: case RegexNodeKind.Beginning: case RegexNodeKind.Bol: case RegexNodeKind.Boundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.End: case RegexNodeKind.EndZ: case RegexNodeKind.Eol: case RegexNodeKind.NonBoundary: case RegexNodeKind.NonECMABoundary: case RegexNodeKind.Start: case RegexNodeKind.PositiveLookaround: case RegexNodeKind.NegativeLookaround: // Zero-width return 0; case RegexNodeKind.Backreference: // Requires matching data available only at run-time. In the future, we could choose to find // and follow the capture group this aligns with, while being careful not to end up in an // infinite cycle. return null; default: Debug.Fail($"Unknown node: {Kind}"); goto case RegexNodeKind.Empty; } } /// <summary> /// Determines whether the specified child index of a concatenation begins a sequence whose values /// should be used to perform an ordinal case-insensitive comparison. /// </summary> /// <param name="childIndex">The index of the child with which to start the sequence.</param> /// <param name="exclusiveChildBound">The exclusive upper bound on the child index to iterate to.</param> /// <param name="nodesConsumed">How many nodes make up the sequence, if any.</param> /// <param name="caseInsensitiveString">The string to use for an ordinal case-insensitive comparison, if any.</param> /// <returns>true if a sequence was found; otherwise, false.</returns> public bool TryGetOrdinalCaseInsensitiveString(int childIndex, int exclusiveChildBound, out int nodesConsumed, [NotNullWhen(true)] out string? caseInsensitiveString) { Debug.Assert(Kind == RegexNodeKind.Concatenate, $"Expected Concatenate, got {Kind}"); var vsb = new ValueStringBuilder(stackalloc char[32]); // We're looking in particular for sets of ASCII characters, so we focus only on sets with two characters in them, e.g. [Aa]. Span<char> twoChars = stackalloc char[2]; // Iterate from the child index to the exclusive upper bound. int i = childIndex; for ( ; i < exclusiveChildBound; i++) { RegexNode child = Child(i); if ((child.Options & RegexOptions.IgnoreCase) != 0) { // TODO https://github.com/dotnet/runtime/issues/61048: Remove this block once fixed. // We don't want any nodes that are still IgnoreCase, as they'd no longer be IgnoreCase if // they were applicable to this optimization. break; } if (child.Kind is RegexNodeKind.One) { // We only want to include ASCII characters, and only if they don't participate in case conversion // such that they only case to themselves and nothing other cases to them. Otherwise, including // them would potentially cause us to match against things not allowed by the pattern. if (child.Ch >= 128 || RegexCharClass.ParticipatesInCaseConversion(child.Ch)) { break; } vsb.Append(child.Ch); } else if (child.Kind is RegexNodeKind.Multi) { // As with RegexNodeKind.One, the string needs to be composed solely of ASCII characters that // don't participate in case conversion. if (!RegexCharClass.IsAscii(child.Str.AsSpan()) || RegexCharClass.ParticipatesInCaseConversion(child.Str.AsSpan())) { break; } vsb.Append(child.Str); } else if (child.Kind is RegexNodeKind.Set || (child.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic && child.M == child.N)) { // In particular we want to look for sets that contain only the upper and lowercase variant // of the same ASCII letter. if (RegexCharClass.IsNegated(child.Str!) || RegexCharClass.GetSetChars(child.Str!, twoChars) != 2 || twoChars[0] >= 128 || twoChars[1] >= 128 || twoChars[0] == twoChars[1] || !char.IsLetter(twoChars[0]) || !char.IsLetter(twoChars[1]) || ((twoChars[0] | 0x20) != (twoChars[1] | 0x20))) { break; } vsb.Append((char)(twoChars[0] | 0x20), child.Kind is RegexNodeKind.Set ? 1 : child.M); } else { break; } } // If we found at least two characters, consider it a sequence found. It's possible // they all came from the same node, so this could be a sequence of just one node. if (vsb.Length >= 2) { caseInsensitiveString = vsb.ToString(); nodesConsumed = i - childIndex; return true; } // No sequence found. caseInsensitiveString = null; nodesConsumed = 0; vsb.Dispose(); return false; } /// <summary> /// Determine whether the specified child node is the beginning of a sequence that can /// trivially have length checks combined in order to avoid bounds checks. /// </summary> /// <param name="childIndex">The starting index of the child to check.</param> /// <param name="requiredLength">The sum of all the fixed lengths for the nodes in the sequence.</param> /// <param name="exclusiveEnd">The index of the node just after the last one in the sequence.</param> /// <returns>true if more than one node can have their length checks combined; otherwise, false.</returns> /// <remarks> /// There are additional node types for which we can prove a fixed length, e.g. examining all branches /// of an alternation and returning true if all their lengths are equal. However, the primary purpose /// of this method is to avoid bounds checks by consolidating length checks that guard accesses to /// strings/spans for which the JIT can see a fixed index within bounds, and alternations employ /// patterns that defeat that (e.g. reassigning the span in question). As such, the implementation /// remains focused on only a core subset of nodes that are a) likely to be used in concatenations and /// b) employ simple patterns of checks. /// </remarks> public bool TryGetJoinableLengthCheckChildRange(int childIndex, out int requiredLength, out int exclusiveEnd) { Debug.Assert(Kind == RegexNodeKind.Concatenate, $"Expected Concatenate, got {Kind}"); static bool CanJoinLengthCheck(RegexNode node) => node.Kind switch { RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set => true, RegexNodeKind.Multi => true, RegexNodeKind.Oneloop or RegexNodeKind.Onelazy or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic when node.M == node.N => true, _ => false, }; RegexNode child = Child(childIndex); if (CanJoinLengthCheck(child)) { requiredLength = child.ComputeMinLength(); int childCount = ChildCount(); for (exclusiveEnd = childIndex + 1; exclusiveEnd < childCount; exclusiveEnd++) { child = Child(exclusiveEnd); if (!CanJoinLengthCheck(child)) { break; } requiredLength += child.ComputeMinLength(); } if (exclusiveEnd - childIndex > 1) { return true; } } requiredLength = 0; exclusiveEnd = 0; return false; } public RegexNode MakeQuantifier(bool lazy, int min, int max) { // Certain cases of repeaters (min == max) can be handled specially if (min == max) { switch (max) { case 0: // The node is repeated 0 times, so it's actually empty. return new RegexNode(RegexNodeKind.Empty, Options); case 1: // The node is repeated 1 time, so it's not actually a repeater. return this; case <= MultiVsRepeaterLimit when Kind == RegexNodeKind.One: // The same character is repeated a fixed number of times, so it's actually a multi. // While this could remain a repeater, multis are more readily optimized later in // processing. The counts used here in real-world expressions are invariably small (e.g. 4), // but we set an upper bound just to avoid creating really large strings. Debug.Assert(max >= 2); Kind = RegexNodeKind.Multi; Str = new string(Ch, max); Ch = '\0'; return this; } } switch (Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: MakeRep(lazy ? RegexNodeKind.Onelazy : RegexNodeKind.Oneloop, min, max); return this; default: var result = new RegexNode(lazy ? RegexNodeKind.Lazyloop : RegexNodeKind.Loop, Options, min, max); result.AddChild(this); return result; } } public void AddChild(RegexNode newChild) { newChild.Parent = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Parent = this; // in case Reduce returns a different node that needs to be reparented if (Children is null) { Children = newChild; } else if (Children is RegexNode currentChild) { Children = new List<RegexNode>() { currentChild, newChild }; } else { ((List<RegexNode>)Children).Add(newChild); } } public void InsertChild(int index, RegexNode newChild) { Debug.Assert(Children is List<RegexNode>); newChild.Parent = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Parent = this; // in case Reduce returns a different node that needs to be reparented ((List<RegexNode>)Children).Insert(index, newChild); } public void ReplaceChild(int index, RegexNode newChild) { Debug.Assert(Children != null); Debug.Assert(index < ChildCount()); newChild.Parent = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Parent = this; // in case Reduce returns a different node that needs to be reparented if (Children is RegexNode) { Children = newChild; } else { ((List<RegexNode>)Children)[index] = newChild; } } public RegexNode Child(int i) => Children is RegexNode child ? child : ((List<RegexNode>)Children!)[i]; public int ChildCount() { if (Children is null) { return 0; } if (Children is List<RegexNode> children) { return children.Count; } Debug.Assert(Children is RegexNode); return 1; } // Determines whether the node supports a compilation / code generation strategy based on walking the node tree. // Also returns a human-readable string to explain the reason (it will be emitted by the source generator, hence // there's no need to localize). internal bool SupportsCompilation([NotNullWhen(false)] out string? reason) { if ((Options & RegexOptions.NonBacktracking) != 0) { reason = "RegexOptions.NonBacktracking isn't supported"; return false; } if (ExceedsMaxDepthAllowedDepth(this, allowedDepth: 40)) { // For the source generator, deep RegexNode trees can result in emitting C# code that exceeds C# compiler // limitations, leading to "CS8078: An expression is too long or complex to compile". As such, we place // an artificial limit on max tree depth in order to mitigate such issues. The allowed depth can be tweaked // as needed; its exceedingly rare to find expressions with such deep trees. And while RegexCompiler doesn't // have to deal with C# compiler limitations, we still want to limit max tree depth as we want to limit // how deep recursion we'll employ as part of code generation. reason = "the expression may result exceeding run-time or compiler limits"; return false; } // Supported. reason = null; return true; static bool ExceedsMaxDepthAllowedDepth(RegexNode node, int allowedDepth) { if (allowedDepth <= 0) { return true; } int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { if (ExceedsMaxDepthAllowedDepth(node.Child(i), allowedDepth - 1)) { return true; } } return false; } } /// <summary>Gets whether the node is a Set/Setloop/Setloopatomic/Setlazy node.</summary> public bool IsSetFamily => Kind is RegexNodeKind.Set or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy; /// <summary>Gets whether the node is a One/Oneloop/Oneloopatomic/Onelazy node.</summary> public bool IsOneFamily => Kind is RegexNodeKind.One or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy; /// <summary>Gets whether the node is a Notone/Notoneloop/Notoneloopatomic/Notonelazy node.</summary> public bool IsNotoneFamily => Kind is RegexNodeKind.Notone or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy; /// <summary>Gets whether this node is contained inside of a loop.</summary> public bool IsInLoop() { for (RegexNode? parent = Parent; parent is not null; parent = parent.Parent) { if (parent.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop) { return true; } } return false; } #if DEBUG [ExcludeFromCodeCoverage] public override string ToString() { RegexNode? curNode = this; int curChild = 0; var sb = new StringBuilder().AppendLine(curNode.Describe()); var stack = new List<int>(); while (true) { if (curChild < curNode!.ChildCount()) { stack.Add(curChild + 1); curNode = curNode.Child(curChild); curChild = 0; sb.Append(new string(' ', stack.Count * 2)).Append(curNode.Describe()).AppendLine(); } else { if (stack.Count == 0) { break; } curChild = stack[stack.Count - 1]; stack.RemoveAt(stack.Count - 1); curNode = curNode.Parent; } } return sb.ToString(); } [ExcludeFromCodeCoverage] private string Describe() { var sb = new StringBuilder(Kind.ToString()); if ((Options & RegexOptions.ExplicitCapture) != 0) sb.Append("-C"); if ((Options & RegexOptions.IgnoreCase) != 0) sb.Append("-I"); if ((Options & RegexOptions.RightToLeft) != 0) sb.Append("-L"); if ((Options & RegexOptions.Multiline) != 0) sb.Append("-M"); if ((Options & RegexOptions.Singleline) != 0) sb.Append("-S"); if ((Options & RegexOptions.IgnorePatternWhitespace) != 0) sb.Append("-X"); if ((Options & RegexOptions.ECMAScript) != 0) sb.Append("-E"); switch (Kind) { case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.One: case RegexNodeKind.Notone: sb.Append(" '").Append(RegexCharClass.DescribeChar(Ch)).Append('\''); break; case RegexNodeKind.Capture: sb.Append(' ').Append($"index = {M}"); if (N != -1) { sb.Append($", unindex = {N}"); } break; case RegexNodeKind.Backreference: case RegexNodeKind.BackreferenceConditional: sb.Append(' ').Append($"index = {M}"); break; case RegexNodeKind.Multi: sb.Append(" \"").Append(Str).Append('"'); break; case RegexNodeKind.Set: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Setlazy: sb.Append(' ').Append(RegexCharClass.DescribeSet(Str!)); break; } switch (Kind) { case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Setlazy: case RegexNodeKind.Loop: case RegexNodeKind.Lazyloop: sb.Append( (M == 0 && N == int.MaxValue) ? "*" : (M == 0 && N == 1) ? "?" : (M == 1 && N == int.MaxValue) ? "+" : (N == int.MaxValue) ? $"{{{M}, *}}" : (N == M) ? $"{{{M}}}" : $"{{{M}, {N}}}"); break; } return sb.ToString(); } #endif } }
1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Text.Json/gen/Reflection/MethodInfoWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Globalization; using System.Reflection; using Microsoft.CodeAnalysis; namespace System.Text.Json.Reflection { internal class MethodInfoWrapper : MethodInfo { private readonly IMethodSymbol _method; private readonly MetadataLoadContextInternal _metadataLoadContext; public MethodInfoWrapper(IMethodSymbol method, MetadataLoadContextInternal metadataLoadContext) { _method = method; _metadataLoadContext = metadataLoadContext; } public override ICustomAttributeProvider ReturnTypeCustomAttributes => throw new NotImplementedException(); private MethodAttributes? _attributes; public override MethodAttributes Attributes => _attributes ??= _method.GetMethodAttributes(); public override RuntimeMethodHandle MethodHandle => throw new NotSupportedException(); public override Type DeclaringType => _method.ContainingType.AsType(_metadataLoadContext); public override Type ReturnType => _method.ReturnType.AsType(_metadataLoadContext); public override string Name => _method.Name; public override bool IsGenericMethod => _method.IsGenericMethod; public bool IsInitOnly => _method.IsInitOnly; public override Type ReflectedType => throw new NotImplementedException(); public override IList<CustomAttributeData> GetCustomAttributesData() { var attributes = new List<CustomAttributeData>(); foreach (AttributeData a in _method.GetAttributes()) { attributes.Add(new CustomAttributeDataWrapper(a, _metadataLoadContext)); } return attributes; } public override MethodInfo GetBaseDefinition() { throw new NotImplementedException(); } public override object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); } public override Type[] GetGenericArguments() { var typeArguments = new List<Type>(); foreach (ITypeSymbol t in _method.TypeArguments) { typeArguments.Add(t.AsType(_metadataLoadContext)); } return typeArguments.ToArray(); } public override MethodImplAttributes GetMethodImplementationFlags() { throw new NotImplementedException(); } public override ParameterInfo[] GetParameters() { var parameters = new List<ParameterInfo>(); foreach (IParameterSymbol p in _method.Parameters) { parameters.Add(new ParameterInfoWrapper(p, _metadataLoadContext)); } return parameters.ToArray(); } public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { throw new NotSupportedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Globalization; using System.Reflection; using Microsoft.CodeAnalysis; namespace System.Text.Json.Reflection { internal class MethodInfoWrapper : MethodInfo { private readonly IMethodSymbol _method; private readonly MetadataLoadContextInternal _metadataLoadContext; public MethodInfoWrapper(IMethodSymbol method, MetadataLoadContextInternal metadataLoadContext) { _method = method; _metadataLoadContext = metadataLoadContext; } public override ICustomAttributeProvider ReturnTypeCustomAttributes => throw new NotImplementedException(); private MethodAttributes? _attributes; public override MethodAttributes Attributes => _attributes ??= _method.GetMethodAttributes(); public override RuntimeMethodHandle MethodHandle => throw new NotSupportedException(); public override Type DeclaringType => _method.ContainingType.AsType(_metadataLoadContext); public override Type ReturnType => _method.ReturnType.AsType(_metadataLoadContext); public override string Name => _method.Name; public override bool IsGenericMethod => _method.IsGenericMethod; public bool IsInitOnly => _method.IsInitOnly; public override Type ReflectedType => throw new NotImplementedException(); public override IList<CustomAttributeData> GetCustomAttributesData() { var attributes = new List<CustomAttributeData>(); foreach (AttributeData a in _method.GetAttributes()) { attributes.Add(new CustomAttributeDataWrapper(a, _metadataLoadContext)); } return attributes; } public override MethodInfo GetBaseDefinition() { throw new NotImplementedException(); } public override object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); } public override Type[] GetGenericArguments() { var typeArguments = new List<Type>(); foreach (ITypeSymbol t in _method.TypeArguments) { typeArguments.Add(t.AsType(_metadataLoadContext)); } return typeArguments.ToArray(); } public override MethodImplAttributes GetMethodImplementationFlags() { throw new NotImplementedException(); } public override ParameterInfo[] GetParameters() { var parameters = new List<ParameterInfo>(); foreach (IParameterSymbol p in _method.Parameters) { parameters.Add(new ParameterInfoWrapper(p, _metadataLoadContext)); } return parameters.ToArray(); } public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { throw new NotSupportedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } } }
-1