microsoft / DirectXShaderCompiler

This repo hosts the source for the DirectX Shader Compiler which is based on LLVM/Clang.
Other
3.04k stars 677 forks source link

Should emit error on unsupported cast operator overloading that's silently ignored #5103

Open tex3d opened 1 year ago

tex3d commented 1 year ago

The cast operator syntax was enabled for HLSL 2021, but it is not really supported by the compiler. We silently ignore cast operators and perform casting as we would have without the operator. That is, we allow C-style casting of aggregate types to another type of fewer or equal components.

We should emit an error when someone tries to define a cast operator, so people are not misled that it works, since it's easy to be fooled, when it didn't do what you expected it to do.

struct MyStruct {
  float4 f;

  // We should emit an error that we don't support cast operator overloading:
  operator float4() {
    return 42;
  }
};

MyStruct foo;

float4 main() : OUT {
  // This compiles and merely casts the contents of foo to float4,
  // instead of calling the float4() operator and returning 42.
  return (float4)foo;
}
tex3d commented 1 year ago

Related to #4096.

llvm-beanz commented 1 year ago

We don't handle it in overload resolution, but we do support them in some contexts when we can resolve them correctly:

https://godbolt.org/z/GvsqcnKnY

devshgraphicsprogramming commented 3 months ago

We don't handle it in overload resolution, but we do support them in some contexts when we can resolve them correctly:

https://godbolt.org/z/GvsqcnKnY

you resolve them and yet I can't see any side effects of calling things inside a conversion operator https://godbolt.org/z/31fPhq743 (SPIR-V) https://godbolt.org/z/GGEzsr3E5 (DXIL)

llvm-beanz commented 3 months ago

you resolve them and yet I can't see any side effects of calling things inside a conversion operator https://godbolt.org/z/31fPhq743 (SPIR-V) https://godbolt.org/z/GGEzsr3E5 (DXIL)

I think you are misunderstanding what you're seeing there. DXC explicitly does not resolve overloads in those expressions. Instead it interprets the expression as it is written which is as a flat-conversion cast:

DeclStmt 0x57d610faca28 <line:20:3, col:13>
`-VarDecl 0x57d610fac8e0 <col:3, col:12> col:5 y 'A' cinit
  `-ImplicitCastExpr 0x57d610faca10 <col:9, col:12> 'A' <LValueToRValue>
    `-CStyleCastExpr 0x57d610fac9d0 <col:9, col:12> 'A' lvalue <NoOp>
      `-ImplicitCastExpr 0x57d610fac9b8 <col:12> 'A' <FlatConversion>
        `-ImplicitCastExpr 0x57d610fac9a0 <col:12> 'B' <LValueToRValue>
          `-DeclRefExpr 0x57d610fac950 <col:12> 'B' lvalue Var 0x57d610fac788 'x' 'B'

Compiler Explorer

This is a known bug in DXC where overload resolution only occurs for function calls and a subset of expressions.