From 9a26c5c4bd829fb9ea34ec8b49dcbb0725af465b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 24 Nov 2020 17:29:41 +0100 Subject: [PATCH] =?UTF-8?q?Removed=20code=20decompiler=20=F0=9F=8E=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComputeSharp.Shaders.csproj | 1 - .../Renderer/Models/ShaderInfo.cs | 40 +-- .../Templates/ShaderTemplate.mustache | 8 +- src/ComputeSharp.Shaders/ShaderRunner{T}.cs | 2 +- .../Translation/MethodDecompiler.cs | 258 ------------------ .../Translation/ShaderLoader{T}.cs | 113 +------- 6 files changed, 31 insertions(+), 391 deletions(-) delete mode 100644 src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index c4e61ed8..66a98d68 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -7,7 +7,6 @@ - diff --git a/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs index fd6e92ed..31b0acfd 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/ShaderInfo.cs @@ -3,58 +3,58 @@ using ComputeSharp.Shaders.Renderer.Models.Fields; using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract; using ComputeSharp.Shaders.Renderer.Models.Functions; -#pragma warning disable CS8618 // Non-nullable field is uninitialized +#pragma warning disable CS8618 namespace ComputeSharp.Shaders.Renderer.Models { /// - /// A that contains info to render a shader source to compile + /// A that contains info to render a shader source to compile. /// internal sealed class ShaderInfo { /// - /// Gets or sets the list of captured buffers being present in the current shader + /// Gets or sets the list of captured buffers being present in the current shader. /// - public IReadOnlyList BuffersList { get; set; } + public IReadOnlyList BuffersList { get; init; } /// - /// Gets or sets the list of captured variables being present in the current shader + /// Gets or sets the list of captured variables being present in the current shader. /// - public IReadOnlyList FieldsList { get; set; } + public IReadOnlyList FieldsList { get; init; } /// - /// Gets or sets the number of threads in the X group + /// Gets or sets the number of threads in the X group. /// - public int NumThreadsX { get; set; } + public int NumThreadsX { get; init; } /// - /// Gets or sets the number of threads in the Y group + /// Gets or sets the number of threads in the Y group. /// - public int NumThreadsY { get; set; } + public int NumThreadsY { get; init; } /// - /// Gets or sets the number of threads in the Z group + /// Gets or sets the number of threads in the Z group. /// - public int NumThreadsZ { get; set; } + public int NumThreadsZ { get; init; } /// - /// Gets or sets the name for the threads id variable used in the shader + /// Gets or sets the name for the threads id variable used in the shader. /// - public string ThreadsIdsVariableName { get; set; } + public string ThreadsIdsVariableName { get; init; } /// - /// Gets or sets the shader body to compile + /// Gets or sets the entry point of the shader. /// - public string ShaderBody { get; set; } + public string EntryPoint { get; init; } /// - /// Gets or sets the list of static functions used by the shader + /// Gets or sets the list of static functions used by the shader. /// - public IReadOnlyList FunctionsList { get; set; } + public IReadOnlyList FunctionsList { get; init; } /// - /// Gets or sets the list of local (implicit) functions used by the shader + /// Gets or sets the list of local (implicit) functions used by the shader. /// - public IReadOnlyList LocalFunctionsList { get; set; } + public IReadOnlyList LocalFunctionsList { get; init; } } } diff --git a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache index 5c2c9822..499ced69 100644 --- a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache +++ b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache @@ -50,10 +50,4 @@ cbuffer _{{FieldName}} : register(b{{BufferIndex}}) {{!Shader entry point}} [NumThreads({{NumThreadsX}}, {{NumThreadsY}}, {{NumThreadsZ}})] -void CSMain(uint3 {{ThreadsIdsVariableName}} : SV_DispatchThreadId) -{ - if ({{ThreadsIdsVariableName}}.x < __x && - {{ThreadsIdsVariableName}}.y < __y && - {{ThreadsIdsVariableName}}.z < __z) -{{&ShaderBody}} -} +{{&EntryPoint}} diff --git a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs index 4a0c78d5..4bf34567 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs @@ -176,7 +176,7 @@ namespace ComputeSharp.Shaders NumThreadsY = threadsY, NumThreadsZ = threadsZ, ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName, - ShaderBody = shaderLoader.MethodBody, + EntryPoint = shaderLoader.EntryPoint, FunctionsList = shaderLoader.FunctionsInfo, LocalFunctionsList = shaderLoader.LocalFunctionsInfo }); diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs deleted file mode 100644 index 7f49623c..00000000 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ /dev/null @@ -1,258 +0,0 @@ -using System; -using System.CodeDom.Compiler; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Reflection.Metadata; -using System.Text.RegularExpressions; -using ComputeSharp.Shaders.Mappings; -using ComputeSharp.Shaders.Translation.Enums; -using ICSharpCode.Decompiler; -using ICSharpCode.Decompiler.CSharp; -using ICSharpCode.Decompiler.Metadata; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.Toolkit.Diagnostics; - -namespace ComputeSharp.Shaders.Translation -{ - /// - /// A that is able to decompile arbitrary methods - /// - internal sealed class MethodDecompiler - { - /// - /// Gets the singleton instance to use - /// - public static MethodDecompiler Instance { get; } = new MethodDecompiler(); - - /// - /// The mapping of available instances targeting different assemblies - /// - private readonly Dictionary Decompilers = new Dictionary(); - - /// - /// The incremental instance for the shader assembly - /// - private Compilation _Compilation; - - /// - /// Creates a new instance - /// - private MethodDecompiler() - { - // Load the assembly paths for all the available dlls - IReadOnlyList assemblyPaths; - if (!string.IsNullOrEmpty(Assembly.GetEntryAssembly()?.Location)) - { - assemblyPaths = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).Select(a => a.Location).ToArray(); - } - else - { - assemblyPaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll").Where(p => - { - try - { - using PEFile _ = new PEFile(p); - return true; - } - catch - { - return false; - } - }).ToArray(); - } - - // Ceate an incremental shader assembly with the available references - IEnumerable metadataReferences = assemblyPaths.Select(p => MetadataReference.CreateFromFile(p)); - _Compilation = CSharpCompilation.Create("ShaderAssembly").WithReferences(metadataReferences); - - // Monitor for new assemblies being loaded - AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad!; - } - - // Increment the shader assembly when a new assembly is loaded - private void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs e) - { - if (!e.LoadedAssembly.IsDynamic) - { - PortableExecutableReference metadataReference = MetadataReference.CreateFromFile(e.LoadedAssembly.Location); - _Compilation = _Compilation.AddReferences(metadataReference); - } - } - - /// - /// Creates a new instance targeting a given assembly - /// - /// The path of the assembly to decompile - /// A instance that can be used on the targeted assembly - [Pure] - private static CSharpDecompiler CreateDecompiler(string assemblyPath) - { - DecompilerSettings decompilerSettings = new DecompilerSettings(ICSharpCode.Decompiler.CSharp.LanguageVersion.Latest) - { - ObjectOrCollectionInitializers = false, - UsingDeclarations = false, - CSharpFormattingOptions = { IndentationString = IndentedTextWriter.DefaultTabString } - }; - - UniversalAssemblyResolver resolver = new UniversalAssemblyResolver(assemblyPath, false, "netstandard"); - return new CSharpDecompiler(assemblyPath, resolver, decompilerSettings); - } - - /// - /// Decompiles a method or the whole declaring type - /// - /// The target to decompile - /// Specifies whether or not to force the decompilation of just the given method, even if not static - /// The decompiled source code - [Pure] - private string DecompileMethodOrDeclaringType(MethodInfo methodInfo, bool methodOnly = false) - { - // Get the handle of the containing type method - string assemblyPath = methodInfo.DeclaringType?.Assembly.Location ?? throw new InvalidOperationException(); - int metadataToken = methodInfo.IsStatic || methodOnly ? methodInfo.MetadataToken : methodInfo.DeclaringType.MetadataToken; - EntityHandle typeHandle = MetadataTokenHelpers.TryAsEntityHandle(metadataToken) ?? throw new InvalidOperationException(); - - // Get or create a decompiler for the target assembly, and decompile the type - if (!Decompilers.TryGetValue(assemblyPath, out CSharpDecompiler? decompiler)) - { - decompiler = CreateDecompiler(assemblyPath); - Decompilers.Add(assemblyPath, decompiler); - } - - return decompiler.DecompileAsString(typeHandle); - } - - /// - /// Decompiles a target method and returns its and info - /// - /// The input to inspect - /// The type of method to decompile - /// The root node for the syntax tree of the input method - /// The semantic model for the input method - public void GetSyntaxTree(MethodInfo methodInfo, MethodType methodType, out MethodDeclarationSyntax rootNode, out SemanticModel semanticModel) - { - string sourceCode = methodType switch - { - MethodType.Execute => GetSyntaxTreeForExecuteMethod(methodInfo), - MethodType.Static => GetSyntaxTreeForStaticMethod(methodInfo), - _ => ThrowHelper.ThrowArgumentException("Invalid method type") - }; - - // Load the type syntax tree - SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode); - - // Get the root node to return - rootNode = syntaxTree - .GetRoot() - .DescendantNodes() - .OfType() - .First(node => node.Identifier.ToString().Equals(methodInfo.Name) || - node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name)); - - // Update the incremental compilation and retrieve the syntax tree for the method - Compilation compilation = _Compilation.AddSyntaxTrees(syntaxTree); - semanticModel = compilation.GetSemanticModel(syntaxTree); - } - - /// - /// Decompiles a target closure method - /// - /// The input to inspect - [Pure] - private string GetSyntaxTreeForExecuteMethod(MethodInfo methodInfo) - { - // Decompile the method source - string sourceCode = DecompileMethodOrDeclaringType(methodInfo); - - // Remove the in keyword from the source - string inFixedSourceCode = Regex.Replace(sourceCode, @"(? - /// Decompiles a target method and returns its and info - /// - /// The input to inspect - [Pure] - private string GetSyntaxTreeForStaticMethod(MethodInfo methodInfo) - { - string - sourceCode = DecompileMethodOrDeclaringType(methodInfo, true), - methodFixedCode = sourceCode.Replace(methodInfo.Name, Regex.Replace(methodInfo.Name, "[<>|]", "_")), - methodWithoutAttributes = CSharpSyntaxTree - .ParseText(methodFixedCode) - .GetRoot() - .DescendantNodes() - .OfType() - .First() - .WithAttributeLists(default) - .ToString(), - prototype = methodWithoutAttributes.Split(Environment.NewLine)[0], - commentedSourceCode = $"// {methodInfo.Name}{Environment.NewLine}{methodWithoutAttributes}", - inFixedSourceCode = Regex.Replace(commentedSourceCode, @"(?().First(); - - return $"// {methodInfo.Name}{Environment.NewLine}{prototype}{Environment.NewLine}{block.ToFullString()}"; - } - - /// - /// Refactors all the inline out expressions with a variable declaration - /// - /// The input source code to process - /// The name of the shader method being processed - [Pure] - private string RefactorInlineOutDeclarations(string source, string entryPoint) - { - // Replace the discards - source = Regex.Replace(source, @"(? $"out {m.Groups[1].Value} {new string(Guid.NewGuid().ToByteArray().Select(b => (char)('a' + b % 26)).ToArray())}"); - - // Fix invalid C# names with @ prefix - source = Regex.Replace(source, @"@(\w+)", m => $"__at__{m.Groups[1].Value}"); - - // Load the syntax tree and the entry node - SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); - MethodDeclarationSyntax rootNode = syntaxTree - .GetRoot() - .DescendantNodes() - .OfType() - .First(node => node.Identifier.ToString().Equals(entryPoint) || - node.GetLeadingTrivia().ToFullString().Contains(entryPoint)); - - // Get the out declarations to replace - var outs = ( - from argument in rootNode.DescendantNodes().OfType() - where argument.RefKindKeyword.IsKind(SyntaxKind.OutKeyword) && - argument.Expression.IsKind(SyntaxKind.DeclarationExpression) - let match = Regex.Match(argument.Expression.ToFullString(), @"([\w.]+) ([\w_]+)") - let mappedType = HlslKnownTypes.GetMappedName(match.Groups[1].Value) - let declaration = $"{mappedType} {match.Groups[2].Value} = ({mappedType})0;" - select declaration).ToArray(); - - // Insert the explicit declarations at the start of the method - int start = rootNode.Body!.ChildNodes().First().SpanStart; - foreach (var declaration in outs.Reverse()) - { - source = source.Insert(start, $"{declaration}{Environment.NewLine} "); - } - - // Remove the out keyword from the source - source = Regex.Replace(source, @"(? /// Gets the generated source code for the method in the current shader. /// - public string MethodBody { get; private set; } + public string EntryPoint { get; private set; } /// /// Gets the collection of items for the shader fields. @@ -232,7 +227,7 @@ namespace ComputeSharp.Shaders.Translation HlslKnownTypes.IsKnownVectorType(type))) { // Captured static delegates with a return type - LoadStaticMethodSource(shader, fieldName, func.Method); + throw new NotImplementedException(); } else ThrowHelper.ThrowArgumentException("Invalid captured variable"); } @@ -243,101 +238,11 @@ namespace ComputeSharp.Shaders.Translation /// The boxed instance to use to build the shader private void LoadMethodSource(object shader) { - // Decompile the shader method - MethodInfo methodInfo = typeof(T).GetMethod(nameof(IComputeShader.Execute))!; - MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Execute, out MethodDeclarationSyntax root, out SemanticModel semanticModel); - - // Rewrite the shader method (eg. to fix the type declarations) - ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, typeof(T)); - root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root); - - // Extract the implicit local functions - var locals = root.DescendantNodes().OfType().ToArray(); - root = root.RemoveNodes(locals, SyntaxRemoveOptions.KeepNoTrivia)!; - foreach (var local in locals) - { - string alignedLocal = local.ToFullString().RemoveLeftPadding().Trim(' ', '\r', '\n'); - alignedLocal = Regex.Replace(alignedLocal, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value); - alignedLocal = HlslKnownKeywords.GetMappedText(alignedLocal); - - this.localFunctionsInfo.Add(new LocalFunctionInfo(alignedLocal)); - } - - // Register the captured static members - foreach (var member in syntaxRewriter.StaticMembers) - { - LoadFieldInfo(shader, member.Value, member.Key); - } - - // Register the captured static methods - foreach (var method in syntaxRewriter.StaticMethods) - { - LoadStaticMethodSource(shader, method.Key, method.Value); - } - - // Get the thread ids identifier name and shader method body - ThreadsIdsVariableName = root.ParameterList.Parameters.First().Identifier.Text; - MethodBody = root.Body!.ToFullString(); - - // Additional preprocessing - MethodBody = Regex.Replace(MethodBody, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value); - MethodBody = MethodBody.TrimEnd('\n', '\r', ' '); - MethodBody = HlslKnownKeywords.GetMappedText(MethodBody); - } - - /// - /// Loads additional static methods used by the shader - /// - /// The boxed instance to use to build the shader - /// The HLSL name of the new method to load - /// The instance for the method to load - private void LoadStaticMethodSource(object shader, string name, MethodInfo methodInfo) - { - // Decompile the target method - MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Static, out MethodDeclarationSyntax root, out SemanticModel semanticModel); - - // Rewrite the method - ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, methodInfo.DeclaringType!); - root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root); - - // Register the captured static members - foreach (var member in syntaxRewriter.StaticMembers) - { - LoadFieldInfo(shader, member.Value, member.Key); - } - - // Register the captured static methods - foreach (var method in syntaxRewriter.StaticMethods) - { - LoadStaticMethodSource(shader, method.Key, method.Value); - } - - // Get the function parameters - IReadOnlyList parameters = ( - from parameter in root.ParameterList.Parameters.Select((p, i) => (Node: p, Index: i)) - let modifiers = parameter.Node.Modifiers - let type = parameter.Node.Type!.ToFullString() - let parameterName = parameter.Node.Identifier.ToFullString() - let last = parameter.Index == root.ParameterList.Parameters.Count - 1 - select new ParameterInfo(modifiers, type, parameterName, last)).ToArray(); - - // Get the function body - string body = root.Body!.ToFullString(); - body = Regex.Replace(body, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value); - body = body.TrimEnd('\n', '\r', ' '); - body = HlslKnownKeywords.GetMappedText(body); - - // Get the final function info instance - FunctionInfo functionInfo = new FunctionInfo( - methodInfo.ReturnType, - $"{methodInfo.DeclaringType!.FullName}{Type.Delimiter}{methodInfo.Name}", - string.Join(", ", methodInfo.GetParameters().Select(p => $"{p.ParameterType.ToFriendlyString()} {p.Name}")), - root.ReturnType.ToString(), - name, - parameters, - body); - - this.functionsInfo.Add(functionInfo); + EntryPoint = ( + from attribute in typeof(T).Assembly.GetCustomAttributes() + where attribute.ShaderTypeName == typeof(T).FullName && + attribute.MethodName == nameof(IComputeShader.Execute) + select attribute.Source).First(); } } }