using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators.SyntaxRewriters { /// /// A custom type that does postprocessing fixups on the shader main method. /// internal sealed class ExecuteMethodRewriter : CSharpSyntaxRewriter { /// /// The identifier name for the input parameter. /// private readonly string threadIdsIdentifier; /// /// Creates a new instance with the specified parameters. /// /// The identifier name for the input parameter. public ExecuteMethodRewriter(string threadIdsIdentifier) { this.threadIdsIdentifier = threadIdsIdentifier; } /// public TNode? Visit(TNode? node) where TNode : SyntaxNode { return (TNode?)base.Visit(node); } /// public override SyntaxNode VisitParameter(ParameterSyntax node) { var updatedNode = (ParameterSyntax)base.VisitParameter(node)!; return updatedNode.WithIdentifier(Identifier($"{updatedNode.Identifier.Text} : SV_DispatchThreadId")); } /// public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) { var updatedNode = ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!).WithModifiers(TokenList()); // When we're rewriting the main compute shader method, we need to insert a range // check to ensure that invocation outside of the requested range are discarded. // The following snippet creates this prologue before the user provided body: // // if (ids.X < __x && // ids.Y < __y && // ids.Z < __z) // { // // } var rangeCheckExpression = BinaryExpression(SyntaxKind.LogicalAndExpression, BinaryExpression(SyntaxKind.LogicalAndExpression, BinaryExpression(SyntaxKind.LessThanExpression, MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName(this.threadIdsIdentifier), IdentifierName("x")), IdentifierName("__x")), BinaryExpression(SyntaxKind.LessThanExpression, MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName(this.threadIdsIdentifier), IdentifierName("y")), IdentifierName("__y"))), BinaryExpression(SyntaxKind.LessThanExpression, MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName(this.threadIdsIdentifier), IdentifierName("z")), IdentifierName("__z"))); return updatedNode .WithIdentifier(Identifier("CSMain")) .WithBody(Block(IfStatement(rangeCheckExpression, updatedNode.Body!))); } } }