From ca46b9a726e38b542263cb517bd4ea2917643919 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 24 Jun 2024 18:58:43 -0700 Subject: [PATCH] Move operator logic to 'HlslOperatorsSyntaxProcessor' --- ...mputeSharp.SourceGeneration.Hlsl.projitems | 1 + .../HlslOperatorsSyntaxProcessor.cs | 151 ++++++++++++++++++ .../SyntaxRewriters/HlslSourceRewriter.cs | 74 +-------- 3 files changed, 160 insertions(+), 66 deletions(-) create mode 100644 src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslOperatorsSyntaxProcessor.cs diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems index 0124d463..253adccf 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -32,6 +32,7 @@ + diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslOperatorsSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslOperatorsSyntaxProcessor.cs new file mode 100644 index 00000000..699d7e09 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslOperatorsSyntaxProcessor.cs @@ -0,0 +1,151 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGeneration.SyntaxProcessors; + +/// +/// A processor responsible for processing special HLSL operators. +/// +internal static class HlslOperatorsSyntaxProcessor +{ + /// + /// Tries to process a custom operator from an input expression node. + /// + /// The original syntax node being processed. + /// The updated node to propagate and potentially rewrite. + /// The instance to use. + /// The cancellation token for the operation. + /// The rewritten node, if successfully produced. + /// Whether a rewritten node was produced. + public static bool TryProcessCustomOperator( + ExpressionSyntax originalNode, + ExpressionSyntax updatedNode, + SemanticModel semanticModel, + CancellationToken token, + [NotNullWhen(true)] out ExpressionSyntax? rewrittenNode) + { + // Process binary operations to see if the target operator method is an intrinsic + if (semanticModel.GetOperation(originalNode, token) is not IBinaryOperation operation) + { + rewrittenNode = null; + + return false; + } + + // Pre-filter candidates based on the operation type, to minimize allocations + if (!HlslKnownOperators.IsCandidateOperator(operation.OperatorKind)) + { + rewrittenNode = null; + + return false; + } + + // Get the binary nodes, in case we need them for rewriting + GetBinaryNodes(updatedNode, out ExpressionSyntax leftNode, out ExpressionSyntax rightNode); + + // First, try to handle unsigned right shift operators, which are a special case. + // This is because they require explicit rewriting, and not just a change in method name. + // We need to do this after pre-filtering, as this is also supported on 'int' and 'uint'. + if (operation.OperatorKind == BinaryOperatorKind.UnsignedRightShift) + { + string typeName = operation.LeftOperand.Type!.GetFullyQualifiedMetadataName(); + + // If the left operand is already unsigned, there's no rewriting to do other + // than just replacing '>>>' with '>>', since the former doesn't exist in HLSL. + if (HlslKnownTypes.IsKnownUnsignedIntegerType(typeName)) + { + rewrittenNode = BinaryExpression(SyntaxKind.RightShiftExpression, leftNode, rightNode); + + return true; + } + + // Rewrite the syntax tree as follows: + // + // x >>> y => (TYPE_X)((UNSIGNED_TYPE_X)x >> y) + if (HlslKnownTypes.IsKnownSignedIntegerType(typeName)) + { + string typeNameOfLeftOperand = HlslKnownTypes.GetMappedName(typeName); + string unsignedTypeName = 'u' + typeNameOfLeftOperand; + + rewrittenNode = + CastExpression( + IdentifierName(typeNameOfLeftOperand), + ParenthesizedExpression( + BinaryExpression( + SyntaxKind.RightShiftExpression, + CastExpression(IdentifierName(unsignedTypeName), leftNode), + rightNode))); + + return true; + } + + // All other cases are unsupported, so just return the original tree + rewrittenNode = null; + + return false; + } + + // Also pre-filter just operators that are defined in ComputeSharp primitives + if (operation is not { OperatorMethod: { ContainingType.ContainingNamespace.Name: "ComputeSharp" } method }) + { + rewrittenNode = null; + + return false; + } + + // If the operator is indeed an HLSL overload, replace the expression with an invocation. + // That is, do the following transformation: + // + // x * y => (x, y) + if (HlslKnownOperators.TryGetMappedName(method.GetFullyQualifiedMetadataName(), method.Parameters.Select(static p => p.Type.Name), out string? mapped)) + { + rewrittenNode = + InvocationExpression(IdentifierName(mapped!)) + .AddArgumentListArguments( + Argument(leftNode), + Argument(rightNode)); + + return true; + } + + rewrittenNode = null; + + return false; + } + + /// + /// Extracts the binary children from an expression node. + /// + /// The input expression node. + /// The resulting left child node. + /// The resulting right child node. + /// Thrown if is of an unsupported type. + private static void GetBinaryNodes( + ExpressionSyntax node, + out ExpressionSyntax left, + out ExpressionSyntax right) + { + switch (node) + { + case BinaryExpressionSyntax binaryExpression: + left = binaryExpression.Left; + right = binaryExpression.Right; + break; + case AssignmentExpressionSyntax assignmentExpression: + left = assignmentExpression.Left; + right = assignmentExpression.Right; + break; + default: + throw new NotSupportedException("Invalid input expression node."); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs index dfac4ddd..0d242e7d 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs @@ -7,6 +7,7 @@ using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxProcessors; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -376,73 +377,14 @@ internal abstract partial class HlslSourceRewriter( BinaryExpressionSyntax updatedNode = (BinaryExpressionSyntax)base.VisitBinaryExpression(node)!; - // Process binary operations to see if the target operator method is an intrinsic - if (SemanticModel.For(node).GetOperation(node, CancellationToken) is not IBinaryOperation operation) + if (HlslOperatorsSyntaxProcessor.TryProcessCustomOperator( + originalNode: node, + updatedNode: updatedNode, + semanticModel: SemanticModel.For(node), + token: CancellationToken, + rewrittenNode: out ExpressionSyntax? rewrittenNode)) { - return updatedNode; - } - - // Pre-filter candidates based on the operation type, to minimize allocations - if (!HlslKnownOperators.IsCandidateOperator(operation.OperatorKind)) - { - return updatedNode; - } - - // First, try to handle unsigned right shift operators, which are a special case. - // This is because they require explicit rewriting, and not just a change in method name. - // We need to do this after pre-filtering, as this is also supported on 'int' and 'uint'. - if (operation.OperatorKind == BinaryOperatorKind.UnsignedRightShift) - { - string typeName = operation.LeftOperand.Type!.GetFullyQualifiedMetadataName(); - - // If the left operand is already unsigned, there's no rewriting to do other - // than just replacing '>>>' with '>>', since the former doesn't exist in HLSL. - if (HlslKnownTypes.IsKnownUnsignedIntegerType(typeName)) - { - return BinaryExpression(SyntaxKind.RightShiftExpression, updatedNode.Left, updatedNode.Right); - } - - // Rewrite the syntax tree as follows: - // - // x >>> y => (TYPE_X)((UNSIGNED_TYPE_X)x >> y) - if (HlslKnownTypes.IsKnownSignedIntegerType(typeName)) - { - string typeNameOfLeftOperand = HlslKnownTypes.GetMappedName(typeName); - string unsignedTypeName = 'u' + typeNameOfLeftOperand; - - return - CastExpression( - IdentifierName(typeNameOfLeftOperand), - ParenthesizedExpression( - BinaryExpression( - SyntaxKind.RightShiftExpression, - CastExpression( - IdentifierName(unsignedTypeName), - updatedNode.Left), - updatedNode.Right))); - } - - // All other cases are unsupported, so just return the original tree - return updatedNode; - } - - // Also pre-filter just operators that are defined in ComputeSharp primitives - if (operation is not { OperatorMethod: { ContainingType.ContainingNamespace.Name: "ComputeSharp" } method }) - { - return updatedNode; - } - - // If the operator is indeed an HLSL overload, replace the expression with an invocation. - // That is, do the following transformation: - // - // x * y => (x, y) - if (HlslKnownOperators.TryGetMappedName(method.GetFullyQualifiedMetadataName(), method.Parameters.Select(static p => p.Type.Name), out string? mapped)) - { - return - InvocationExpression(IdentifierName(mapped!)) - .AddArgumentListArguments( - Argument(updatedNode.Left), - Argument(updatedNode.Right)); + return rewrittenNode; } return updatedNode;