2017-08-25 18:56:42 +03:00
=====================================
HLSL to SPIR-V Feature Mapping Manual
=====================================
2017-04-15 04:18:21 +03:00
.. contents ::
:local:
2017-08-14 19:32:43 +03:00
:depth: 3
2017-04-15 04:18:21 +03:00
Introduction
============
2017-08-25 18:56:42 +03:00
This document describes the mappings from HLSL features to SPIR-V for Vulkan
adopted by the SPIR-V codegen. For how to build, use, or contribute to the
SPIR-V codegen and its internals, please see the
`wiki <https://github.com/Microsoft/DirectXShaderCompiler/wiki/SPIR%E2%80%90V-CodeGen> `_
page.
`SPIR-V <https://www.khronos.org/registry/spir-v/> `_ is a binary intermediate
language for representing graphical-shader stages and compute kernels for
multiple Khronos APIs, such as Vulkan, OpenGL, and OpenCL. At the moment we
only intend to support the Vulkan flavor of SPIR-V.
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
DirectXShaderCompiler is the reference compiler for HLSL. Adding SPIR-V codegen
in DirectXShaderCompiler will enable the usage of HLSL as a frontend language
for Vulkan shader programming. Sharing the same code base also means we can
track the evolution of HLSL more closely and always deliver the best of HLSL to
developers. Moreover, developers will also have a unified compiler toolchain for
targeting both DirectX and Vulkan. We believe this effort will benefit the
general graphics ecosystem.
2017-04-15 04:18:21 +03:00
2017-08-25 18:56:42 +03:00
Note that this document is expected to be an ongoing effort and grow as we
implement more and more HLSL features.
2017-08-14 19:32:43 +03:00
2017-11-07 17:56:10 +03:00
Overview
========
Although they share the same basic concepts, DirectX and Vulkan are still
different graphics APIs with semantic gaps. HLSL is the native shading language
for DirectX, so certain HLSL features do not have corresponding mappings in
Vulkan, and certain Vulkan specific information does not have native ways to
express in HLSL source code. This section describes the general translation
paradigms and how we close some of the major semantic gaps.
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
Note that the term "semantic" is overloaded. In HLSL, it can mean the string
attached to shader input or output. For such cases, we refer it as "HLSL
semantic" or "semantic string". For other cases, we just use the normal
"semantic" term.
2017-04-15 04:18:21 +03:00
2017-11-07 17:56:10 +03:00
Shader entry function
---------------------
HLSL entry functions can read data from the previous shader stage and write
data to the next shader stage via function parameters and return value. On the
contrary, Vulkan requires all SPIR-V entry functions taking no parameters and
returning void. All data passing between stages should use global variables
in the `` Input `` and `` Output `` storage class.
To handle this difference, we emit a wrapper function as the SPIR-V entry
function around the HLSL source code entry function. The wrapper function is
responsible to read data from SPIR-V `` Input `` global variables and prepare
them to the types required in the source code entry function signature, call
the source code entry function, and then decompose the contents in return value
(and `` out `` /`` inout `` parameters) to the types required by the SPIR-V
`` Output `` global variables, and then write out. For details about the wrapper
function, please refer to the `entry function wrapper`_ section.
Shader stage IO interface matching
----------------------------------
HLSL leverages semantic strings to link variables and pass data between shader
stages. Great flexibility is allowed as for how to use the semantic strings.
They can appear on function parameters, function returns, and struct members.
In Vulkan, linking variables and passing data between shader stages is done via
numeric `` Location `` decorations on SPIR-V global variables in the `` Input `` and
`` Output `` storage class.
To help handling such differences, we provide `Vulkan specific attributes`_ to
let the developer to express precisely their intents. The compiler will also try
its best to deduce the mapping from semantic strings to SPIR-V `` Location ``
numbers when such explicit Vulkan specific attributes are absent. Please see the
`HLSL semantic and Vulkan Location`_ section for more details about the mapping
and `` Location `` assignment.
What makes the story complicated is Vulkan's strict requirements on interface
matching. Basically, a variable in the previous stage is considered a match to
a variable in the next stage if and only if they are decorated with the same
`` Location `` number and with the exact same type, except for the outermost
arrayness in hull/domain/geometry shader, which can be ignored regarding
interface matching. This is causing problems together with the flexibility of
HLSL semantic strings.
Some HLSL system-value (SV) semantic strings will be mapped into SPIR-V
variables with builtin decorations, some are not. HLSL non-SV semantic strings
should all be mapped to SPIR-V variables without builtin decorations (but with
`` Location `` decorations).
With these complications, if we are grouping multiple semantic strings in a
struct in the HLSL source code, that struct should be flattened and each of
its members should be mapped separately. For example, for the following:
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
.. code :: hlsl
2017-04-15 04:18:21 +03:00
2017-11-07 17:56:10 +03:00
struct T {
float2 clip0 : SV_ClipDistance0;
float3 cull0 : SV_CullDistance0;
float4 foo : FOO;
};
2017-04-15 04:18:21 +03:00
2017-11-07 17:56:10 +03:00
struct S {
float4 pos : SV_Position;
float2 clip1 : SV_ClipDistance1;
float3 cull1 : SV_CullDistance1;
float4 bar : BAR;
T t;
};
2017-04-15 04:18:21 +03:00
2017-11-07 17:56:10 +03:00
If we have an `` S `` input parameter in pixel shader, we should flatten it
recursively to generate five SPIR-V `` Input `` variables. Three of them are
decorated by the `` Position `` , `` ClipDistance `` , `` CullDistance `` builtin,
and two of them are decorated by the `` Location `` decoration. (Note that
`` clip0 `` and `` clip1 `` are concatenated, also `` cull0 `` and `` cull1 `` .
The `` ClipDistance `` and `` CullDistance `` builtins are special and explained
2018-05-07 17:21:20 +03:00
in the `ClipDistance & CullDistance`_ section.)
2017-11-07 17:56:10 +03:00
Flattening is infective because of Vulkan interface matching rules. If we
flatten a struct in the output of a previous stage, which may create multiple
variables decorated with different `` Location `` numbers, we also need to
flatten it in the input of the next stage. otherwise we may have `` Location ``
mismatch even if we share the same definition of the struct. Because
hull/domain/geometry shader is optional, we can have different chains of shader
stages, which means we need to flatten all shader stage interfaces. For
hull/domain/geometry shader, their inputs/outputs have an additional arrayness.
So if we are seeing an array of structs in these shaders, we need to flatten
them into arrays of its fields.
2017-11-15 16:14:22 +03:00
Vulkan specific features
------------------------
We try to implement Vulkan specific features using the most intuitive and
non-intrusive ways in HLSL, which means we will prefer native language
constructs when possible. If that is inadequate, we then consider attaching
`Vulkan specific attributes`_ to them, or introducing new syntax.
2017-11-26 04:32:39 +03:00
Descriptors
~~~~~~~~~~~
2017-11-15 16:14:22 +03:00
2018-08-03 14:36:18 +03:00
The compiler provides multiple mechanisms to specify which Vulkan descriptor
a particular resource binds to.
In the source code, you can use the `` [[vk::binding(X[, Y])]] `` and
`` [[vk::counter_binding(X)]] `` attribute. The native `` :register() `` attribute
is also respected.
On the command-line, you can use the `` -fvk-{b|s|t|u}-shift `` or
`` -fvk-bind-register `` option.
If you can modify the source code, the `` [[vk::binding(X[, Y])]] `` and
`` [[vk::counter_binding(X)]] `` attribute gives you find-grained control over
descriptor assignment.
If you cannot modify the source code, you can use command-line options to change
how `` :register() `` attribute is handled by the compiler. `` -fvk-bind-register ``
lets you to specify the descriptor for the source at a certain register.
`` -fvk-{b|s|t|u}-shift `` lets you to apply shifts to all register numbers
of a certain register type. They cannot be used together, though.
Without attribute and command-line option, `` :register(xX, spaceY) `` will be
mapped to binding `` X `` in descriptor set `` Y `` . Note that register type `` x ``
is ignored, so this may cause overlap.
The more specific a mechanism is, the higher precedence it has, and command-line
option has higher precedence over source code attribute.
For more details, see `HLSL register and Vulkan binding`_ , `Vulkan specific
attributes`_, and `Vulkan-specific options`_ .
2017-11-15 16:14:22 +03:00
2018-01-22 18:45:56 +03:00
Subpass inputs
~~~~~~~~~~~~~~
2018-04-10 17:25:26 +03:00
Within a Vulkan `rendering pass <https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#renderpass> `_ ,
2018-01-22 18:45:56 +03:00
a subpass can write results to an output target that can then be read by the
next subpass as an input subpass. The "Subpass Input" feature regards the
ability to read an output target.
Subpasses are read through two new builtin resource types, available only in
pixel shader:
.. code :: hlsl
class SubpassInput<T> {
T SubpassLoad();
};
class SubpassInputMS<T> {
T SubpassLoad(int sampleIndex);
};
In the above, `` T `` is a scalar or vector type. If omitted, it will defaults to
`` float4 `` .
Subpass inputs are implicitly addressed by the pixel's (x, y, layer) coordinate.
These objects support reading the subpass input through the methods as shown
in the above.
A subpass input is selected by using a new attribute `` vk::input_attachment_index `` .
For example:
.. code :: hlsl
[[vk::input_attachment_index(i)]] SubpassInput input;
An `` vk::input_attachment_index `` of `` i `` selects the ith entry in the input
pass list. (See Vulkan API spec for more information.)
2017-11-15 16:14:22 +03:00
Push constants
~~~~~~~~~~~~~~
Vulkan push constant blocks are represented using normal global variables of
struct types in HLSL. The variables (not the underlying struct types) should be
annotated with the `` [[vk::push_constant]] `` attribute.
Please note as per the requirements of Vulkan, "there must be no more than one
push constant block statically used per shader entry point."
2018-01-22 23:36:14 +03:00
Specialization constants
~~~~~~~~~~~~~~~~~~~~~~~~
To use Vulkan specialization constants, annotate global constants with the
`` [[vk::constant_id(X)]] `` attribute. For example,
.. code :: hlsl
[[vk::constant_id(1)]] const bool specConstBool = true;
[[vk::constant_id(2)]] const int specConstInt = 42;
[[vk::constant_id(3)]] const float specConstFloat = 1.5;
2019-05-16 07:36:28 +03:00
Shader Record Buffer
~~~~~~~~~~~~~~~~~~~~
SPV_NV_ray_tracing exposes user managed buffer in shader binding table by
using storage class ShaderRecordBufferNV. ConstantBuffer or cbuffer blocks
can now be mapped to this storage class under HLSL by using
`` [[vk::shader_record_nv]] `` annotation. It is applicable only on ConstantBuffer
and cbuffer declarations.
Please note as per the requirements of VK_NV_ray_tracing, "there must be no
more than one shader_record_nv block statically used per shader entry point
otherwise results are undefined."
2017-11-26 04:32:39 +03:00
Builtin variables
~~~~~~~~~~~~~~~~~
Some of the Vulkan builtin variables have no equivalents in native HLSL
language. To support them, `` [[vk::builtin("<builtin>")]] `` is introduced.
2018-03-13 17:07:54 +03:00
Right now the following `` <builtin> `` are supported:
2017-11-26 04:32:39 +03:00
* `` PointSize `` : The GLSL equivalent is `` gl_PointSize `` .
* `` HelperInvocation `` : The GLSL equivalent is `` gl_HelperInvocation `` .
2018-03-13 17:07:54 +03:00
* `` BaseVertex `` : The GLSL equivalent is `` gl_BaseVertexARB `` .
Need `` SPV_KHR_shader_draw_parameters `` extension.
* `` BaseInstance `` : The GLSL equivalent is `` gl_BaseInstanceARB `` .
Need `` SPV_KHR_shader_draw_parameters `` extension.
* `` DrawIndex `` : The GLSL equivalent is `` gl_DrawIDARB `` .
Need `` SPV_KHR_shader_draw_parameters `` extension.
2018-03-23 17:40:02 +03:00
* `` DeviceIndex `` : The GLSL equivalent is `` gl_DeviceIndex `` .
Need `` SPV_KHR_device_group `` extension.
2019-07-11 23:19:23 +03:00
* `` ViewportMaskNV `` : The GLSL equivalent is `` gl_ViewportMask `` .
2017-11-26 04:32:39 +03:00
2018-04-10 17:25:26 +03:00
Please see Vulkan spec. `14.6. Built-In Variables <https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#interfaces-builtin-variables> `_
2017-11-26 04:32:39 +03:00
for detailed explanation of these builtins.
2018-10-01 21:47:11 +03:00
Supported extensions
~~~~~~~~~~~~~~~~~~~~
* SPV_KHR_16bit_storage
* SPV_KHR_device_group
* SPV_KHR_multivew
* SPV_KHR_post_depth_coverage
* SPV_KHR_shader_draw_parameters
* SPV_EXT_descriptor_indexing
* SPV_EXT_fragment_fully_covered
2019-06-07 00:15:21 +03:00
* SPV_EXT_fragment_invocation_density
2018-10-01 21:47:11 +03:00
* SPV_EXT_shader_stencil_support
* SPV_AMD_shader_explicit_vertex_parameter
* SPV_GOOGLE_hlsl_functionality1
2019-07-11 23:19:23 +03:00
* SPV_NV_mesh_shader
2018-10-01 21:47:11 +03:00
2017-11-07 17:56:10 +03:00
Vulkan specific attributes
--------------------------
`C++ attribute specifier sequence <http://en.cppreference.com/w/cpp/language/attributes> `_
2017-11-15 16:14:22 +03:00
is a non-intrusive way of providing Vulkan specific information in HLSL.
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
The namespace `` vk `` will be used for all Vulkan attributes:
2017-08-18 06:56:48 +03:00
- `` location(X) `` : For specifying the location (`` X `` ) numbers for stage
input/output variables. Allowed on function parameters, function returns,
and struct fields.
2017-08-25 18:56:42 +03:00
- `` binding(X[, Y]) `` : For specifying the descriptor set (`` Y `` ) and binding
2017-08-18 06:56:48 +03:00
(`` X `` ) numbers for resource variables. The descriptor set (`` Y `` ) is
2017-08-25 18:56:42 +03:00
optional; if missing, it will be set to 0. Allowed on global variables.
2017-10-24 17:51:50 +03:00
- `` counter_binding(X) `` : For specifying the binding number (`` X `` ) for the
associated counter for RW/Append/Consume structured buffer. The descriptor
set number for the associated counter is always the same as the main resource.
2017-11-15 16:14:22 +03:00
- `` push_constant `` : For marking a variable as the push constant block. Allowed
on global variables of struct type. At most one variable can be marked as
`` push_constant `` in a shader.
2018-07-04 17:58:35 +03:00
- `` offset(X) `` : For manually layout struct members. Annotating a struct member
with this attribute will force the compiler to put the member at offset `` X ``
w.r.t. the beginning of the struct. Only allowed on struct members.
2018-03-28 00:42:16 +03:00
- `` constant_id(X) `` : For marking a global constant as a specialization constant.
2018-01-22 23:36:14 +03:00
Allowed on global variables of boolean/integer/float types.
2018-01-22 18:45:56 +03:00
- `` input_attachment_index(X) `` : To associate the Xth entry in the input pass
list to the annotated object. Only allowed on objects whose type are
`` SubpassInput `` or `` SubpassInputMS `` .
2017-11-26 04:32:39 +03:00
- `` builtin("X") `` : For specifying an entity should be translated into a certain
Vulkan builtin variable. Allowed on function parameters, function returns,
and struct fields.
2018-04-26 23:02:12 +03:00
- `` index(X) `` : For specifying the index at a specific pixel shader output
location. Used for dual-source blending.
2018-07-28 00:16:41 +03:00
- `` post_depth_coverage `` : The input variable decorated with SampleMask will
reflect the result of the EarlyFragmentTests. Only valid on pixel shader entry points.
2017-08-14 19:32:43 +03:00
Only `` vk:: `` attributes in the above list are supported. Other attributes will
result in warnings and be ignored by the compiler. All C++11 attributes will
only trigger warnings and be ignored if not compiling towards SPIR-V.
2017-11-07 17:56:10 +03:00
For example, to specify the layout of resource variables and the location of
interface variables:
.. code :: hlsl
struct S { ... };
[[vk::binding(X, Y), vk::counter_binding(Z)]]
RWStructuredBuffer<S> mySBuffer;
[[vk::location(M)]] float4
main([[vk::location(N)]] float4 input: A) : B
{ ... }
2018-03-28 00:42:16 +03:00
SPIR-V version and extension
----------------------------
2018-04-17 00:16:07 +03:00
SPIR-V CodeGen provides two command-line options for fine-grained SPIR-V target
environment (hence SPIR-V version) and SPIR-V extension control:
- `` -fspv-target-env= `` : for specifying SPIR-V target environment
- `` -fspv-extension= `` : for specifying allowed SPIR-V extensions
`` -fspv-target-env= `` only accepts `` vulkan1.0 `` and `` vulkan1.1 `` right now.
If such an option is not given, the CodeGen defaults to `` vulkan1.0 `` . When
targeting `` vulkan1.0 `` , trying to use features that are only available
in Vulkan 1.1 (SPIR-V 1.3), like `Shader Model 6.0 wave intrinsics`_ , will
trigger a compiler error.
If `` -fspv-extension= `` is not specified, the CodeGen will select suitable
SPIR-V extensions to translate the source code. Otherwise, only extensions
supplied via `` -fspv-extension= `` will be used. If that does not suffice, errors
will be emitted explaining what additional extensions are required to translate
what specific feature in the source code. If you want to allow all KHR
extensions, you can use `` -fspv-extension=KHR `` .
2018-03-28 00:42:16 +03:00
2018-02-21 22:12:01 +03:00
Legalization, optimization, validation
--------------------------------------
After initial translation of the HLSL source code, SPIR-V CodeGen will further
conduct legalization (if needed), optimization (if requested), and validation
(if not turned off). All these three stages are outsourced to `SPIRV-Tools <https://github.com/KhronosGroup/SPIRV-Tools> `_ .
Here are the options controlling these stages:
* `` -fcgl `` : turn off legalization and optimization
* `` -Od `` : turn off optimization
* `` -Vd `` : turn off validation
Legalization
~~~~~~~~~~~~
HLSL is a fairly permissive language considering the flexibility it provides for
manipulating resource objects. The developer can create local copies, pass
them around as function parameters and return values, as long as after certain
transformations (function inlining, constant evaluation and propagating, dead
code elimination, etc.), the compiler can remove all temporary copies and
pinpoint all uses to unique global resource objects.
Resulting from the above property of HLSL, if we translate into SPIR-V for
Vulkan literally from the input HLSL source code, we will sometimes generate
illegal SPIR-V. Certain transformations are needed to legalize the literally
translated SPIR-V. Performing such transformations at the frontend AST level
is cumbersome or impossible (e.g., function inlining). They are better to be
conducted at SPIR-V level. Therefore, legalization is delegated to SPIRV-Tools.
Specifically, we need to legalize the following HLSL source code patterns:
* Using resource types in struct types
* Creating aliases of global resource objects
* Control flows invovling the above cases
Legalization transformations will not run unless the above patterns are
encountered in the source code.
2018-10-22 21:22:44 +03:00
For more details, please see the `SPIR-V cookbook <https://github.com/Microsoft/DirectXShaderCompiler/tree/master/docs/SPIRV-Cookbook.rst> `_ ,
which contains examples of what HLSL code patterns will be accepted and
generate valid SPIR-V for Vulkan.
2018-02-21 22:12:01 +03:00
Optimization
~~~~~~~~~~~~
Optimization is also delegated to SPIRV-Tools. Right now there are no difference
between optimization levels greater than zero; they will all invoke the same
2018-07-31 20:49:19 +03:00
optimization recipe. That is, the recipe behind `` spirv-opt -O `` . If you want to
2018-08-01 17:49:51 +03:00
run a custom optimization recipe, you can do so using the command line option
`` -Oconfig= `` and specifying a comma-separated list of your desired passes.
The passes are invoked in the specified order.
2018-07-31 20:49:19 +03:00
For example, you can specify `` -Oconfig=--loop-unroll,--scalar-replacement=300,--eliminate-dead-code-aggressive ``
2018-08-01 17:49:51 +03:00
to firstly invoke loop unrolling, then invoke scalar replacement of aggregates,
lastly invoke aggressive dead code elimination. All valid options to
`` spirv-opt `` are accepted as components to the comma-separated list.
2018-07-31 20:49:19 +03:00
Here are the typical passes in alphabetical order:
* `` --ccp ``
* `` --cfg-cleanup ``
* `` --convert-local-access-chains ``
* `` --copy-propagate-arrays ``
* `` --eliminate-dead-branches ``
* `` --eliminate-dead-code-aggressive ``
* `` --eliminate-dead-functions ``
* `` --eliminate-local-multi-store ``
* `` --eliminate-local-single-block ``
* `` --eliminate-local-single-store ``
* `` --flatten-decorations ``
* `` --if-conversion ``
* `` --inline-entry-points-exhaustive ``
* `` --local-redundancy-elimination ``
* `` --loop-fission ``
* `` --loop-fusion ``
* `` --loop-unroll ``
* `` --loop-unroll-partial=[<n>] ``
* `` --loop-peeling `` (requires `` --loop-peeling-threshold `` )
* `` --merge-blocks ``
* `` --merge-return ``
* `` --loop-unswitch ``
* `` --private-to-local ``
* `` --reduce-load-size ``
* `` --redundancy-elimination ``
* `` --remove-duplicates ``
* `` --replace-invalid-opcode ``
* `` --ssa-rewrite ``
* `` --scalar-replacement[=<n>] ``
* `` --simplify-instructions ``
* `` --vector-dce ``
2018-08-01 17:49:51 +03:00
Besides, there are two special batch options; each stands for a recommended
recipe by itself:
2018-07-31 20:49:19 +03:00
2018-08-01 17:49:51 +03:00
* `` -O `` : A bunch of passes in an appropriate order that attempt to improve
performance of generated code. Same as `` spirv-opt -O `` . Also same as SPIR-V
CodeGen's default recipe.
* `` -Os `` : A bunch of passes in an appropriate order that attempt to reduce the
size of the generated code. Same as `` spirv-opt -Os `` .
2018-07-31 20:49:19 +03:00
2018-08-01 17:49:51 +03:00
So if you want to run loop unrolling additionally after the default optimization
recipe, you can specify `` -Oconfig=-O,--loop-unroll `` .
2018-07-31 20:49:19 +03:00
2018-08-01 17:49:51 +03:00
For the whole list of accepted passes and details about each one, please see
`` spirv-opt `` 's help manual (`` spirv-opt --help `` ), or the SPIRV-Tools `optimizer header file <https://github.com/KhronosGroup/SPIRV-Tools/blob/master/include/spirv-tools/optimizer.hpp> `_ .
2018-02-21 22:12:01 +03:00
Validation
~~~~~~~~~~
Validation is turned on by default as the last stage of SPIR-V CodeGen. Failing
validation, which indicates there is a CodeGen bug, will trigger a fatal error.
Please file an issue if you see that.
2018-08-01 17:49:51 +03:00
Debugging
---------
By default, the compiler will only emit names for types and variables as debug
information, to aid reading of the generated SPIR-V. The `` -Zi `` option will
let the compiler emit the following additional debug information:
* Full path of the main source file using `` OpSource ``
* Preprocessed source code using `` OpSource `` and `` OpSourceContinued ``
* Line information for certain instructions using `` OpLine `` (WIP)
2018-08-29 18:11:30 +03:00
* DXC Git commit hash using `` OpModuleProcessed `` (requires Vulkan 1.1)
* DXC command-line options used to compile the shader using `` OpModuleProcessed ``
(requires Vulkan 1.1)
2018-08-01 17:49:51 +03:00
We chose to embed preprocessed source code instead of original source code to
avoid pulling in lots of contents unrelated to the current entry point, and
boilerplate contents generated by engines. We may add a mode for selecting
between preprocessed single source code and original separated source code in
the future.
One thing to note is that to keep the line numbers in consistent with the
embedded source, the compiler is invoked twice; the first time is for
preprocessing the source code, and the second time is for feeding the
preprocessed source code as input for a whole compilation. So using `` -Zi ``
means performance penality.
2018-08-29 18:11:30 +03:00
If you want to have fine-grained control over the categories of emitted debug
information, you can use `` -fspv-debug= `` . It accepts:
* `` file `` : for emitting full path of the main source file
* `` source `` : for emitting preprocessed source code (turns on `` file `` implicitly)
* `` line `` : for emitting line information (turns on `` source `` implicitly)
* `` tool `` : for emitting DXC Git commit hash and command-line options
`` -fspv-debug= `` overrules `` -Zi `` . And you can provide multiple instances of
`` -fspv-debug= `` . For example, you can use `` -fspv-debug=file -fspv-debug=tool ``
to turn on emitting file path and DXC information; source code and line
information will not be emitted.
2018-03-12 18:32:00 +03:00
Reflection
----------
Making reflection easier is one of the goals of SPIR-V CodeGen. This section
provides guidelines about how to reflect on certain facts.
Note that we generate `` OpName `` /`` OpMemberName `` instructions for various
types/variables both explicitly defined in the source code and interally created
by the compiler. These names are primarily for debugging purposes in the
compiler. They have "no semantic impact and can safely be removed" according
to the SPIR-V spec. And they are subject to changes without notice. So we do
not suggest to use them for reflection.
2018-03-16 20:40:00 +03:00
Source code shader profile
~~~~~~~~~~~~~~~~~~~~~~~~~~
The source code shader profile version can be re-discovered by the "Version"
operand in `` OpSource `` instruction. For `` *s_<major>_<minor> `` , the "Verison"
operand in `` OpSource `` will be set as `` <major> `` * 100 + ``<minor>`` * 10.
For example, `` vs_5_1 `` will have 510, `` ps_6_2 `` will have 620.
2018-03-17 20:05:31 +03:00
HLSL Semantic
~~~~~~~~~~~~~
HLSL semantic strings are by default not emitted into the SPIR-V binary module.
If you need them, by specifying `` -fspv-reflect `` , the compiler will use
the `` Op*DecorateStringGOOGLE `` instruction in `SPV_GOOGLE_hlsl_funtionality1 <https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/GOOGLE/SPV_GOOGLE_hlsl_functionality1.asciidoc> `_
extension to emit them.
Counter buffers for RW/Append/Consume StructuredBuffer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The association between a counter buffer and its main RW/Append/Consume
StructuredBuffer is conveyed by `` OpDecorateId <structured-buffer-id>
HLSLCounterBufferGOOGLE <counter-buffer-id>`` instruction from the
`SPV_GOOGLE_hlsl_funtionality1 <https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/GOOGLE/SPV_GOOGLE_hlsl_functionality1.asciidoc> `_
extension. This information is by default missing; you need to specify
`` -fspv-reflect `` to direct the compiler to emit them.
2018-03-12 18:32:00 +03:00
Read-only vs. read-write resource types
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are no clear and consistent decorations in the SPIR-V to show whether a
resource type is translated from a read-only (RO) or read-write (RW) HLSL
resource type. Instead, you need to use different checks for reflecting different
resource types:
* HLSL samplers: RO.
* HLSL `` Buffer `` /`` RWBuffer `` /`` Texture* `` /`` RWTexture* `` : Check the "Sampled"
operand in the `` OpTypeImage `` instruction they translated into. "2" means RW,
"1" means RO.
* HLSL constant/texture/structured/byte buffers: Check both `` Block `` /`` BufferBlock ``
and `` NonWritable `` decoration. If decorated with `` Block `` (`` cbuffer `` &
`` ConstantBuffer `` ), then RO; if decorated with `` BufferBlock `` and `` NonWritable ``
(`` tbuffer `` , `` TextureBuffer `` , `` StructuredBuffer `` ), then RO; Otherwise, RW.
2017-08-25 18:56:42 +03:00
HLSL Types
==========
2017-08-14 19:32:43 +03:00
This section lists how various HLSL types are mapped.
2017-04-15 04:18:21 +03:00
Normal scalar types
2017-08-25 18:56:42 +03:00
-------------------
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
`Normal scalar types <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509646(v=vs.85).aspx> `_
in HLSL are relatively easy to handle and can be mapped directly to SPIR-V
2017-08-25 18:56:42 +03:00
type instructions:
2017-04-15 04:18:21 +03:00
2018-01-06 00:52:15 +03:00
============================== ======================= ================== =========== =================================
HLSL Command Line Option SPIR-V Capability Extension
============================== ======================= ================== =========== =================================
`` bool `` `` OpTypeBool ``
`` int `` /`` int32_t `` `` OpTypeInt 32 1 ``
`` int16_t `` `` -enable-16bit-types `` `` OpTypeInt 16 1 `` `` Int16 ``
`` uint `` /`` dword `` /`` uin32_t `` `` OpTypeInt 32 0 ``
`` uint16_t `` `` -enable-16bit-types `` `` OpTypeInt 16 0 `` `` Int16 ``
2018-01-20 00:00:23 +03:00
`` half `` `` OpTypeFloat 32 ``
2018-03-06 19:25:20 +03:00
`` half `` /`` float16_t `` `` -enable-16bit-types `` `` OpTypeFloat 16 `` `` SPV_AMD_gpu_shader_half_float ``
2018-01-06 00:52:15 +03:00
`` float `` /`` float32_t `` `` OpTypeFloat 32 ``
`` snorm float `` `` OpTypeFloat 32 ``
`` unorm float `` `` OpTypeFloat 32 ``
`` double `` /`` float64_t `` `` OpTypeFloat 64 `` `` Float64 ``
============================== ======================= ================== =========== =================================
2017-08-25 18:56:42 +03:00
Please note that `` half `` is translated into 32-bit floating point numbers
2018-09-11 21:49:20 +03:00
if without `` -enable-16bit-types `` because MSDN says that "this data type
is provided only for language compatibility. Direct3D 10 shader targets map
all `` half `` data types to `` float `` data types."
2017-08-25 18:56:42 +03:00
2017-04-15 04:18:21 +03:00
Minimal precision scalar types
2017-08-25 18:56:42 +03:00
------------------------------
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
HLSL also supports various
`minimal precision scalar types <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509646(v=vs.85).aspx> `_ ,
which graphics drivers can implement by using any precision greater than or
equal to their specified bit precision.
2017-08-25 18:56:42 +03:00
There are no direct mappings in SPIR-V for these types. We translate them into
2018-01-06 00:52:15 +03:00
the corresponding 16-bit or 32-bit scalar types with the `` RelaxedPrecision `` decoration.
We use the 16-bit variants if '-enable-16bit-types' command line option is present.
For more information on these types, please refer to:
https://github.com/Microsoft/DirectXShaderCompiler/wiki/16-Bit-Scalar-Types
============== ======================= ================== ==================== ============ =================================
HLSL Command Line Option SPIR-V Decoration Capability Extension
============== ======================= ================== ==================== ============ =================================
`` min16float `` `` OpTypeFloat 32 `` `` RelaxedPrecision ``
`` min10float `` `` OpTypeFloat 32 `` `` RelaxedPrecision ``
`` min16int `` `` OpTypeInt 32 1 `` `` RelaxedPrecision ``
`` min12int `` `` OpTypeInt 32 1 `` `` RelaxedPrecision ``
`` min16uint `` `` OpTypeInt 32 0 `` `` RelaxedPrecision ``
2018-03-06 19:25:20 +03:00
`` min16float `` `` -enable-16bit-types `` `` OpTypeFloat 16 `` `` SPV_AMD_gpu_shader_half_float ``
`` min10float `` `` -enable-16bit-types `` `` OpTypeFloat 16 `` `` SPV_AMD_gpu_shader_half_float ``
2018-01-06 00:52:15 +03:00
`` min16int `` `` -enable-16bit-types `` `` OpTypeInt 16 1 `` `` Int16 ``
`` min12int `` `` -enable-16bit-types `` `` OpTypeInt 16 1 `` `` Int16 ``
`` min16uint `` `` -enable-16bit-types `` `` OpTypeInt 16 0 `` `` Int16 ``
============== ======================= ================== ==================== ============ =================================
2017-04-15 04:18:21 +03:00
2017-08-03 02:27:56 +03:00
Vectors and matrices
2017-08-25 18:56:42 +03:00
--------------------
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
`Vectors <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509707(v=vs.85).aspx> `_
and `matrices <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509623(v=vs.85).aspx> `_
are translated into:
2017-04-15 04:18:21 +03:00
2017-08-25 18:56:42 +03:00
==================================== ====================================================
HLSL SPIR-V
==================================== ====================================================
`` |type|N `` (`` N `` > 1) `` OpTypeVector |type| N ``
`` |type|1 `` The scalar type for `` |type| ``
`` |type|MxN `` (`` M `` > 1, `` N `` > 1) `` %v = OpTypeVector |type| N `` `` OpTypeMatrix %v M ``
`` |type|Mx1 `` (`` M `` > 1) `` OpTypeVector |type| M ``
`` |type|1xN `` (`` N `` > 1) `` OpTypeVector |type| N ``
`` |type|1x1 `` The scalar type for `` |type| ``
==================================== ====================================================
2018-02-12 23:33:41 +03:00
The above table is for float matrices.
A MxN HLSL float matrix is translated into a SPIR-V matrix with M vectors, each with
2017-08-14 19:32:43 +03:00
N elements. Conceptually HLSL matrices are row-major while SPIR-V matrices are
column-major, thus all HLSL matrices are represented by their transposes.
Doing so may require special handling of certain matrix operations:
2017-08-02 19:38:20 +03:00
2017-08-14 19:32:43 +03:00
- **Indexing** : no special handling required. `` matrix[m][n] `` will still access
the correct element since `` m `` /`` n `` means the `` m `` -th/`` n `` -th row/column
2017-08-25 18:56:42 +03:00
in HLSL but `` m `` -th/`` n `` -th vector/element in SPIR-V.
2017-08-14 19:32:43 +03:00
- **Per-element operation** : no special handling required.
- **Matrix multiplication** : need to swap the operands. `` mat1 x mat2 `` should
be translated as `` transpose(mat2) x transpose(mat1) `` . Then the result is
`` transpose(mat1 x mat2) `` .
- **Storage layout** : `` row_major `` /`` column_major `` will be translated into
SPIR-V `` ColMajor `` /`` RowMajor `` decoration. This is because HLSL matrix
row/column becomes SPIR-V matrix column/row. If elements in a row/column are
packed together, they should be loaded into a column/row correspondingly.
2017-08-03 02:27:56 +03:00
2018-02-01 23:21:17 +03:00
See `Appendix A. Matrix Representation`_ for further explanation regarding these design choices.
2018-02-12 23:33:41 +03:00
Since the `` Shader `` capability in SPIR-V does not allow to parameterize matrix
types with non-floating-point types, a non-floating-point MxN matrix is translated
into an array with M elements, with each element being a vector with N elements.
2017-04-15 04:18:21 +03:00
Structs
2017-08-25 18:56:42 +03:00
-------
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
`Structs <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509668(v=vs.85).aspx> `_
in HLSL are defined in the a format similar to C structs. They are translated
2017-08-25 18:56:42 +03:00
into SPIR-V `` OpTypeStruct `` . Depending on the storage classes of the instances,
a single struct definition may generate multiple `` OpTypeStruct `` instructions
in SPIR-V. For example, for the following HLSL source code:
.. code :: hlsl
struct S { ... }
ConstantBuffer<S> myCBuffer;
StructuredBuffer<S> mySBuffer;
float4 main() : A {
S myLocalVar;
...
}
2017-08-14 19:32:43 +03:00
2017-09-21 06:28:22 +03:00
There will be three different `` OpTypeStruct `` generated, one for each variable
2017-08-25 18:56:42 +03:00
defined in the above source code. This is because the `` OpTypeStruct `` for
both `` myCBuffer `` and `` mySBuffer `` will have layout decorations (`` Offset `` ,
`` MatrixStride `` , `` ArrayStride `` , `` RowMajor `` , `` ColMajor `` ). However, their
2018-04-10 17:25:26 +03:00
layout rules are different (by default); `` myCBuffer `` will use vector-relaxed
OpenGL `` std140 `` while `` mySBuffer `` will use vector-relaxed OpenGL `` std430 `` .
`` myLocalVar `` will have its `` OpTypeStruct `` without layout decorations.
Read more about storage classes in the `Constant/Texture/Structured/Byte Buffers`_
section.
2017-04-15 04:18:21 +03:00
2017-08-25 18:56:42 +03:00
Structs used as stage inputs/outputs will have semantics attached to their
members. These semantics are handled in the `entry function wrapper`_ .
Structs used as pixel shader inputs can have optional interpolation modifiers
for their members, which will be translated according to the following table:
=========================== ================= =====================
HLSL Interpolation Modifier SPIR-V Decoration SPIR-V Capability
=========================== ================= =====================
2017-04-15 04:18:21 +03:00
`` linear `` <none>
`` centroid `` `` Centroid ``
`` nointerpolation `` `` Flat ``
`` noperspective `` `` NoPerspective ``
2017-08-25 18:56:42 +03:00
`` sample `` `` Sample `` `` SampleRateShading ``
=========================== ================= =====================
2017-04-15 04:18:21 +03:00
2018-05-03 20:36:09 +03:00
Arrays
------
Sized (either explicitly or implicitly) arrays are translated into SPIR-V
`OpTypeArray` . Unsized arrays are translated into `OpTypeRuntimeArray` .
Arrays, if used for external resources (residing in SPIR-V `Uniform` or
`UniformConstant` storage class), will need layout decorations like SPIR-V
`ArrayStride` decoration. For arrays of opaque types, e.g., HLSL textures
or samplers, we don't decorate with `ArrayStride` decorations since there is
no meaningful strides. Similarly for arrays of structured/byte buffers.
2017-04-15 04:18:21 +03:00
User-defined types
2017-08-25 18:56:42 +03:00
------------------
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
`User-defined types <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509702(v=vs.85).aspx> `_
are type aliases introduced by typedef. No new types are introduced and we can
rely on Clang to resolve to the original types.
2017-04-15 04:18:21 +03:00
[spirv] Support texture and sampler types (#572)
This commit add support for the following types:
* Texture1D, Texture2D, Texture3D, TextureCube
* Texture1DArray, Texture2DArray, TextureCubeArray
* SamplerState, SamplerComparisonState, sampler
Buffer, Texture2DMS, and Texture2DMSArray is not supported yet,
also setting sampler states.
Texture types will be translated OpTypeImage, and sampler types
will be translated into OpTypeSampler.
2017-08-17 07:09:20 +03:00
Samplers
2017-08-25 18:56:42 +03:00
--------
[spirv] Support texture and sampler types (#572)
This commit add support for the following types:
* Texture1D, Texture2D, Texture3D, TextureCube
* Texture1DArray, Texture2DArray, TextureCubeArray
* SamplerState, SamplerComparisonState, sampler
Buffer, Texture2DMS, and Texture2DMSArray is not supported yet,
also setting sampler states.
Texture types will be translated OpTypeImage, and sampler types
will be translated into OpTypeSampler.
2017-08-17 07:09:20 +03:00
All `sampler types <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509644(v=vs.85).aspx> `_
will be translated into SPIR-V `` OpTypeSampler `` .
SPIR-V `` OpTypeSampler `` is an opaque type that cannot be parameterized;
therefore state assignments on sampler types is not supported (yet).
Textures
2017-08-25 18:56:42 +03:00
--------
[spirv] Support texture and sampler types (#572)
This commit add support for the following types:
* Texture1D, Texture2D, Texture3D, TextureCube
* Texture1DArray, Texture2DArray, TextureCubeArray
* SamplerState, SamplerComparisonState, sampler
Buffer, Texture2DMS, and Texture2DMSArray is not supported yet,
also setting sampler states.
Texture types will be translated OpTypeImage, and sampler types
will be translated into OpTypeSampler.
2017-08-17 07:09:20 +03:00
`Texture types <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509700(v=vs.85).aspx> `_
are translated into SPIR-V `` OpTypeImage `` , with parameters:
2018-03-08 20:11:09 +03:00
======================= ==================== ===== =================== ========== ===== ======= == ======= ================ =================
HLSL Vulkan SPIR-V
----------------------- -------------------------- ------------------------------------------------------------------------------------------
Texture Type Descriptor Type RO/RW Storage Class Dim Depth Arrayed MS Sampled Image Format Capability
======================= ==================== ===== =================== ========== ===== ======= == ======= ================ =================
2018-05-11 17:57:26 +03:00
`` Texture1D `` Sampled Image RO `` UniformConstant `` `` 1D `` 2 0 0 1 `` Unknown ``
`` Texture2D `` Sampled Image RO `` UniformConstant `` `` 2D `` 2 0 0 1 `` Unknown ``
`` Texture3D `` Sampled Image RO `` UniformConstant `` `` 3D `` 2 0 0 1 `` Unknown ``
`` TextureCube `` Sampled Image RO `` UniformConstant `` `` Cube `` 2 0 0 1 `` Unknown ``
`` Texture1DArray `` Sampled Image RO `` UniformConstant `` `` 1D `` 2 1 0 1 `` Unknown ``
`` Texture2DArray `` Sampled Image RO `` UniformConstant `` `` 2D `` 2 1 0 1 `` Unknown ``
`` Texture2DMS `` Sampled Image RO `` UniformConstant `` `` 2D `` 2 0 1 1 `` Unknown ``
`` Texture2DMSArray `` Sampled Image RO `` UniformConstant `` `` 2D `` 2 1 1 1 `` Unknown `` `` ImageMSArray ``
`` TextureCubeArray `` Sampled Image RO `` UniformConstant `` `` 3D `` 2 1 0 1 `` Unknown ``
`` Buffer<T> `` Uniform Texel Buffer RO `` UniformConstant `` `` Buffer `` 2 0 0 1 Depends on `` T `` `` SampledBuffer ``
`` RWBuffer<T> `` Storage Texel Buffer RW `` UniformConstant `` `` Buffer `` 2 0 0 2 Depends on `` T `` `` SampledBuffer ``
`` RWTexture1D<T> `` Storage Image RW `` UniformConstant `` `` 1D `` 2 0 0 2 Depends on `` T ``
`` RWTexture2D<T> `` Storage Image RW `` UniformConstant `` `` 2D `` 2 0 0 2 Depends on `` T ``
`` RWTexture3D<T> `` Storage Image RW `` UniformConstant `` `` 3D `` 2 0 0 2 Depends on `` T ``
`` RWTexture1DArray<T> `` Storage Image RW `` UniformConstant `` `` 1D `` 2 1 0 2 Depends on `` T ``
`` RWTexture2DArray<T> `` Storage Image RW `` UniformConstant `` `` 2D `` 2 1 0 2 Depends on `` T ``
2018-03-08 20:11:09 +03:00
======================= ==================== ===== =================== ========== ===== ======= == ======= ================ =================
[spirv] Support texture and sampler types (#572)
This commit add support for the following types:
* Texture1D, Texture2D, Texture3D, TextureCube
* Texture1DArray, Texture2DArray, TextureCubeArray
* SamplerState, SamplerComparisonState, sampler
Buffer, Texture2DMS, and Texture2DMSArray is not supported yet,
also setting sampler states.
Texture types will be translated OpTypeImage, and sampler types
will be translated into OpTypeSampler.
2017-08-17 07:09:20 +03:00
The meanings of the headers in the above table is explained in `` OpTypeImage ``
of the SPIR-V spec.
2017-04-15 04:18:21 +03:00
2018-04-10 17:25:26 +03:00
Constant/Texture/Structured/Byte Buffers
----------------------------------------
2017-04-15 04:18:21 +03:00
2017-08-25 18:56:42 +03:00
There are serveral buffer types in HLSL:
- `` cbuffer `` and `` ConstantBuffer ``
- `` tbuffer `` and `` TextureBuffer ``
- `` StructuredBuffer `` and `` RWStructuredBuffer ``
- `` AppendStructuredBuffer `` and `` ConsumeStructuredBuffer ``
2017-09-21 06:28:22 +03:00
- `` ByteAddressBuffer `` and `` RWByteAddressBuffer ``
Note that `` Buffer `` and `` RWBuffer `` are considered as texture object in HLSL.
They are listed in the above section.
2017-08-25 18:56:42 +03:00
Please see the following sections for the details of each type. As a summary:
2018-04-10 17:25:26 +03:00
=========================== ================== ================================ ==================== =================
HLSL Type Vulkan Buffer Type Default Memory Layout Rule SPIR-V Storage Class SPIR-V Decoration
=========================== ================== ================================ ==================== =================
`` cbuffer `` Uniform Buffer Vector-relaxed OpenGL `` std140 `` `` Uniform `` `` Block ``
`` ConstantBuffer `` Uniform Buffer Vector-relaxed OpenGL `` std140 `` `` Uniform `` `` Block ``
`` tbuffer `` Storage Buffer Vector-relaxed OpenGL `` std430 `` `` Uniform `` `` BufferBlock ``
`` TextureBuffer `` Storage Buffer Vector-relaxed OpenGL `` std430 `` `` Uniform `` `` BufferBlock ``
`` StructuredBuffer `` Storage Buffer Vector-relaxed OpenGL `` std430 `` `` Uniform `` `` BufferBlock ``
`` RWStructuredBuffer `` Storage Buffer Vector-relaxed OpenGL `` std430 `` `` Uniform `` `` BufferBlock ``
`` AppendStructuredBuffer `` Storage Buffer Vector-relaxed OpenGL `` std430 `` `` Uniform `` `` BufferBlock ``
`` ConsumeStructuredBuffer `` Storage Buffer Vector-relaxed OpenGL `` std430 `` `` Uniform `` `` BufferBlock ``
`` ByteAddressBuffer `` Storage Buffer Vector-relaxed OpenGL `` std430 `` `` Uniform `` `` BufferBlock ``
`` RWByteAddressBuffer `` Storage Buffer Vector-relaxed OpenGL `` std430 `` `` Uniform `` `` BufferBlock ``
=========================== ================== ================================ ==================== =================
To know more about the Vulkan buffer types, please refer to the Vulkan spec
`13.1 Descriptor Types <https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#descriptorsets-types> `_ .
Memory layout rules
~~~~~~~~~~~~~~~~~~~
2018-11-20 19:24:57 +03:00
SPIR-V CodeGen supports four sets of memory layout rules for buffer resources
2018-04-10 17:25:26 +03:00
right now:
1. Vector-relaxed OpenGL `` std140 `` for uniform buffers and vector-relaxed
OpenGL `` std430 `` for storage buffers: these rules satisfy Vulkan `"Standard
Uniform Buffer Layout" and "Standard Storage Buffer Layout" <https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#interfaces-resources-layout>`_,
respectively.
They are the default.
2018-04-17 00:16:07 +03:00
2. DirectX memory layout rules for uniform buffers and storage buffers:
2018-04-10 17:25:26 +03:00
they allow packing data on the application side that can be shared with
DirectX. They can be enabled by `` -fvk-use-dx-layout `` .
2018-04-17 00:16:07 +03:00
3. Strict OpenGL `` std140 `` for uniform buffers and strict OpenGL `` std430 ``
for storage buffers: they allow packing data on the application side that
can be shared with OpenGL. They can be enabled by `` -fvk-use-gl-layout `` .
2018-11-20 19:24:57 +03:00
4. Scalar layout rules introduced via `VK_EXT_scalar_block_layout` , which
basically aligns all aggregrate types according to their elements'
natural alignment. They can be enabled by `` -fvk-use-scalar-layout `` .
To use scalar layout, the application side need to request
`` VK_EXT_scalar_block_layout `` . This is also true for using DirectX memory
layout since there is no dedicated DirectX layout extension for Vulkan
(at least for now). So we must request something more permissive.
2018-04-10 17:25:26 +03:00
In the above, "vector-relaxed OpenGL `` std140 `` /`` std430 `` " rules mean OpenGL
2018-03-12 17:21:54 +03:00
`` std140 `` /`` std430 `` rules with the following modification for vector type
alignment:
1. The alignment of a vector type is set to be the alignment of its element type
2018-04-10 17:25:26 +03:00
2. If the above causes an `improper straddle <https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#interfaces-resources-layout> `_ ,
2018-03-12 17:21:54 +03:00
the alignment will be set to 16 bytes.
2018-04-10 17:25:26 +03:00
As an exmaple, for the following HLSL definition:
2018-04-08 19:50:57 +03:00
2018-04-10 17:25:26 +03:00
.. code :: hlsl
2018-03-12 17:21:54 +03:00
2018-04-10 17:25:26 +03:00
struct S {
float3 f;
};
struct T {
float a_float;
float3 b_float3;
S c_S_float3;
float2x3 d_float2x3;
row_major float2x3 e_float2x3;
int f_int_3[3];
float2 g_float2_2[2];
};
We will have the following offsets for each member:
2018-11-20 19:24:57 +03:00
============== ====== ====== ====== ========== ====== ====== ====== ==========
HLSL Uniform Buffer Storage Buffer
-------------- ------------------------------- -------------------------------
Member 1 (VK) 2 (DX) 3 (GL) 4 (Scalar) 1 (VK) 2 (DX) 3 (GL) 4 (Scalar)
============== ====== ====== ====== ========== ====== ====== ====== ==========
`` a_float `` 0 0 0 0 0 0 0 0
`` b_float3 `` 4 4 16 4 4 4 16 4
`` c_S_float3 `` 16 16 32 16 16 16 32 16
`` d_float2x3 `` 32 32 48 28 32 28 48 28
`` e_float2x3 `` 80 80 96 52 64 52 80 52
`` f_int_3 `` 112 112 128 76 96 76 112 76
`` g_float2_2 `` 160 160 176 88 112 88 128 88
============== ====== ====== ====== ========== ====== ====== ====== ==========
2017-08-25 18:56:42 +03:00
2018-07-04 17:58:35 +03:00
If the above layout rules do not satisfy your needs and you want to manually
control the layout of struct members, you can use either
* The native HLSL `` :packoffset() `` attribute: only available for cbuffers; or
* The Vulkan-specific `` [[vk::offset()]] `` attribute: applies to all resources.
`` [[vk::offset]] `` overrules `` :packoffset `` . Attaching `` [[vk::offset]] ``
to a struct memeber affects all variables of the struct type in question. So
sharing the same struct definition having `` [[vk::offset]] `` annotations means
also sharing the layout.
2019-02-12 18:07:20 +03:00
For global variables (which are collected into the `` $Globals `` cbuffer), you
can use the native HLSL `` :register(c#) `` attribute. Note that `` [[vk::offset]] ``
and `` :packoffset `` cannot be applied to these variables.
If `` register(cX) `` is used on any global variable, the offset for that variable
is set to `` X * 16 `` , and the offset for all other global variables without the
`` register(c#) `` annotation will be set to the next available address after
the highest explicit address. For example:
.. code :: hlsl
float x : register(c10); // Offset = 160 (10 * 16)
float y; // Offset = 164 (160 + 4)
float z: register(c1); // Offset = 16 (1 * 16)
2018-07-04 17:58:35 +03:00
These attributes give great flexibility but also responsibility to the
developer; the compiler will just take in what is specified in the source code
and emit it to SPIR-V with no error checking.
2017-08-25 18:56:42 +03:00
`` cbuffer `` and `` ConstantBuffer ``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
These two buffer types are treated as uniform buffers using Vulkan's
terminology. They are translated into an `` OpTypeStruct `` with the
necessary layout decorations (`` Offset `` , `` ArrayStride `` , `` MatrixStride `` ,
`` RowMajor `` , `` ColMajor `` ) and the `` Block `` decoration. The layout rule
2018-04-10 17:25:26 +03:00
used is vector-relaxed OpenGL `` std140 `` (by default). A variable declared as
one of these types will be placed in the `` Uniform `` storage class.
2017-08-25 18:56:42 +03:00
For example, for the following HLSL source code:
.. code :: hlsl
struct T {
float a;
float3 b;
};
ConstantBuffer<T> myCBuffer;
will be translated into
.. code :: spirv
; Layout decoration
OpMemberDecorate %type_ConstantBuffer_T 0 Offset 0
2018-04-10 17:25:26 +03:00
OpMemberDecorate %type_ConstantBuffer_T 0 Offset 4
2017-08-25 18:56:42 +03:00
; Block decoration
OpDecorate %type_ConstantBuffer_T Block
; Types
%type_ConstantBuffer_T = OpTypeStruct %float %v3float
%_ptr_Uniform_type_ConstantBuffer_T = OpTypePointer Uniform %type_ConstantBuffer_T
; Variable
%myCbuffer = OpVariable %_ptr_Uniform_type_ConstantBuffer_T Uniform
2017-04-15 04:18:21 +03:00
2017-11-11 01:07:43 +03:00
`` tbuffer `` and `` TextureBuffer ``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
These two buffer types are treated as storage buffers using Vulkan's
terminology. They are translated into an `` OpTypeStruct `` with the
necessary layout decorations (`` Offset `` , `` ArrayStride `` , `` MatrixStride `` ,
`` RowMajor `` , `` ColMajor `` ) and the `` BufferBlock `` decoration. All the struct
members are also decorated with `` NonWritable `` decoration. The layout rule
2018-04-10 17:25:26 +03:00
used is vector-relaxed OpenGL `` std430 `` (by default). A variable declared as
one of these types will be placed in the `` Uniform `` storage class.
2017-11-11 01:07:43 +03:00
2017-08-25 18:56:42 +03:00
`` StructuredBuffer `` and `` RWStructuredBuffer ``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
`` StructuredBuffer<T> `` /`` RWStructuredBuffer<T> `` is treated as storage buffer
using Vulkan's terminology. It is translated into an `` OpTypeStruct `` containing
an `` OpTypeRuntimeArray `` of type `` T `` , with necessary layout decorations
(`` Offset `` , `` ArrayStride `` , `` MatrixStride `` , `` RowMajor `` , `` ColMajor `` ) and
2018-04-10 17:25:26 +03:00
the `` BufferBlock `` decoration. The default layout rule used is vector-relaxed
OpenGL `` std430 `` . A variable declared as one of these types will be placed in
the `` Uniform `` storage class.
2017-08-25 18:56:42 +03:00
2017-12-21 02:34:25 +03:00
For `` RWStructuredBuffer<T> `` , each variable will have an associated counter
variable generated. The counter variable will be of `` OpTypeStruct `` type, which
only contains a 32-bit integer. The counter variable takes its own binding
number. `` .IncrementCounter() `` /`` .DecrementCounter() `` will modify this counter
variable.
2017-08-25 18:56:42 +03:00
For example, for the following HLSL source code:
.. code :: hlsl
struct T {
float a;
float3 b;
};
StructuredBuffer<T> mySBuffer;
will be translated into
.. code :: spirv
; Layout decoration
OpMemberDecorate %T 0 Offset 0
2018-04-10 17:25:26 +03:00
OpMemberDecorate %T 1 Offset 4
OpDecorate %_runtimearr_T ArrayStride 16
2017-08-25 18:56:42 +03:00
OpMemberDecorate %type_StructuredBuffer_T 0 Offset 0
OpMemberDecorate %type_StructuredBuffer_T 0 NoWritable
; BufferBlock decoration
OpDecorate %type_StructuredBuffer_T BufferBlock
; Types
%T = OpTypeStruct %float %v3float
%_runtimearr_T = OpTypeRuntimeArray %T
%type_StructuredBuffer_T = OpTypeStruct %_runtimearr_T
%_ptr_Uniform_type_StructuredBuffer_T = OpTypePointer Uniform %type_StructuredBuffer_T
; Variable
%myCbuffer = OpVariable %_ptr_Uniform_type_ConstantBuffer_T Uniform
`` AppendStructuredBuffer `` and `` ConsumeStructuredBuffer ``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
`` AppendStructuredBuffer<T> `` /`` ConsumeStructuredBuffer<T> `` is treated as
storage buffer using Vulkan's terminology. It is translated into an
`` OpTypeStruct `` containing an `` OpTypeRuntimeArray `` of type `` T `` , with
necessary layout decorations (`` Offset `` , `` ArrayStride `` , `` MatrixStride `` ,
`` RowMajor `` , `` ColMajor `` ) and the `` BufferBlock `` decoration. The default
2018-04-10 17:25:26 +03:00
layout rule used is vector-relaxed OpenGL `` std430 `` .
2017-08-25 18:56:42 +03:00
A variable declared as one of these types will be placed in the `` Uniform ``
storage class. Besides, each variable will have an associated counter variable
generated. The counter variable will be of `` OpTypeStruct `` type, which only
2017-09-21 06:28:22 +03:00
contains a 32-bit integer. The integer is the total number of elements in the
buffer. The counter variable takes its own binding number.
2017-08-25 18:56:42 +03:00
`` .Append() `` /`` .Consume() `` will use the counter variable as the index and
adjust it accordingly.
For example, for the following HLSL source code:
.. code :: hlsl
struct T {
float a;
float3 b;
};
AppendStructuredBuffer<T> mySBuffer;
will be translated into
.. code :: spirv
; Layout decorations
OpMemberDecorate %T 0 Offset 0
2018-04-10 17:25:26 +03:00
OpMemberDecorate %T 1 Offset 4
OpDecorate %_runtimearr_T ArrayStride 16
2017-08-25 18:56:42 +03:00
OpMemberDecorate %type_AppendStructuredBuffer_T 0 Offset 0
OpDecorate %type_AppendStructuredBuffer_T BufferBlock
OpMemberDecorate %type_ACSBuffer_counter 0 Offset 0
OpDecorate %type_ACSBuffer_counter BufferBlock
; Binding numbers
OpDecorate %myASbuffer DescriptorSet 0
OpDecorate %myASbuffer Binding 0
OpDecorate %counter_var_myASbuffer DescriptorSet 0
OpDecorate %counter_var_myASbuffer Binding 1
; Types
%T = OpTypeStruct %float %v3float
%_runtimearr_T = OpTypeRuntimeArray %T
%type_AppendStructuredBuffer_T = OpTypeStruct %_runtimearr_T
%_ptr_Uniform_type_AppendStructuredBuffer_T = OpTypePointer Uniform %type_AppendStructuredBuffer_T
%type_ACSBuffer_counter = OpTypeStruct %int
%_ptr_Uniform_type_ACSBuffer_counter = OpTypePointer Uniform %type_ACSBuffer_counter
; Variables
%myASbuffer = OpVariable %_ptr_Uniform_type_AppendStructuredBuffer_T Uniform
%counter_var_myASbuffer = OpVariable %_ptr_Uniform_type_ACSBuffer_counter Uniform
2017-09-21 06:28:22 +03:00
`` ByteAddressBuffer `` and `` RWByteAddressBuffer ``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
`` ByteAddressBuffer `` /`` RWByteAddressBuffer `` is treated as storage buffer using
Vulkan's terminology. It is translated into an `` OpTypeStruct `` containing an
`` OpTypeRuntimeArray `` of 32-bit unsigned integers, with `` BufferBlock ``
decoration.
A variable declared as one of these types will be placed in the `` Uniform ``
storage class.
For example, for the following HLSL source code:
.. code :: hlsl
ByteAddressBuffer myBuffer1;
RWByteAddressBuffer myBuffer2;
will be translated into
.. code :: spirv
; Layout decorations
OpDecorate %_runtimearr_uint ArrayStride 4
OpDecorate %type_ByteAddressBuffer BufferBlock
OpMemberDecorate %type_ByteAddressBuffer 0 Offset 0
OpMemberDecorate %type_ByteAddressBuffer 0 NonWritable
OpDecorate %type_RWByteAddressBuffer BufferBlock
OpMemberDecorate %type_RWByteAddressBuffer 0 Offset 0
; Types
%_runtimearr_uint = OpTypeRuntimeArray %uint
%type_ByteAddressBuffer = OpTypeStruct %_runtimearr_uint
%_ptr_Uniform_type_ByteAddressBuffer = OpTypePointer Uniform %type_ByteAddressBuffer
%type_RWByteAddressBuffer = OpTypeStruct %_runtimearr_uint
%_ptr_Uniform_type_RWByteAddressBuffer = OpTypePointer Uniform %type_RWByteAddressBuffer
; Variables
%myBuffer1 = OpVariable %_ptr_Uniform_type_ByteAddressBuffer Uniform
%myBuffer2 = OpVariable %_ptr_Uniform_type_RWByteAddressBuffer Uniform
2017-08-25 18:56:42 +03:00
HLSL Variables and Resources
============================
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
This section lists how various HLSL variables and resources are mapped.
2017-04-15 04:18:21 +03:00
2018-02-02 20:44:48 +03:00
According to `Shader Constants <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509581(v=vs.85).aspx> `_ ,
There are two default constant buffers available, $Global and $Param. Variables
that are placed in the global scope are added implicitly to the $Global cbuffer,
using the same packing method that is used for cbuffers. Uniform parameters in
the parameter list of a function appear in the $Param constant buffer when a
shader is compiled outside of the effects framework.
2018-03-14 18:15:14 +03:00
So all global externally-visible non-resource-type stand-alone variables will
be collected into a cbuffer named as `` $Globals `` , no matter whether they are
statically referenced by the entry point or not. The `` $Globals `` cbuffer
follows the layout rules like normal cbuffer.
2018-02-02 20:44:48 +03:00
2017-04-15 04:18:21 +03:00
Storage class
2017-08-25 18:56:42 +03:00
-------------
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
Normal local variables (without any modifier) will be placed in the `` Function ``
2017-12-21 02:34:25 +03:00
SPIR-V storage class. Normal global variables (without any modifer) will be
placed in the `` Uniform `` or `` UniformConstant `` storage class.
- `` static ``
- Global variables with `` static `` modifier will be placed in the `` Private ``
SPIR-V storage class. Initalizers of such global variables will be translated
into SPIR-V `` OpVariable `` initializers if possible; otherwise, they will be
initialized at the very beginning of the `entry function wrapper`_ using
SPIR-V `` OpStore `` .
- Local variables with `` static `` modifier will also be placed in the
`` Private `` SPIR-V storage class. initializers of such local variables will
also be translated into SPIR-V `` OpVariable `` initializers if possible;
otherwise, they will be initialized at the very beginning of the enclosing
function. To make sure that such a local variable is only initialized once,
a second boolean variable of the `` Private `` SPIR-V storage class will be
generated to mark its initialization status.
- `` groupshared ``
- Global variables with `` groupshared `` modifier will be placed in the
`` Workgroup `` storage class.
2018-02-28 20:12:13 +03:00
- Note that this modifier overrules `` static `` ; if both `` groupshared `` and
`` static `` are applied to a variable, `` static `` will be ignored.
2017-12-21 02:34:25 +03:00
- `` uinform ``
- This does not affect codegen. Variables will be treated like normal global
variables.
- `` extern ``
- This does not affect codegen. Variables will be treated like normal global
variables.
- `` shared ``
- This is a hint to the compiler. It will be ingored.
- `` volatile ``
2017-04-15 04:18:21 +03:00
2017-12-21 02:34:25 +03:00
- This is a hint to the compiler. It will be ingored.
2017-04-15 04:18:21 +03:00
2017-09-01 23:37:36 +03:00
HLSL semantic and Vulkan `` Location ``
2017-11-07 17:56:10 +03:00
-------------------------------------
2017-08-14 19:32:43 +03:00
Direct3D uses HLSL "`semantics <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509647(v=vs.85).aspx> `_ "
to compose and match the interfaces between subsequent stages. These semantic
strings can appear after struct members, function parameters and return
values. E.g.,
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
.. code :: hlsl
2017-04-15 04:18:21 +03:00
struct VSInput {
float4 pos : POSITION;
float3 norm : NORMAL;
};
2017-08-14 19:32:43 +03:00
float4 VSMain(in VSInput input,
in float4 tex : TEXCOORD,
out float4 pos : SV_Position) : TEXCOORD {
pos = input.pos;
return tex;
2017-04-15 04:18:21 +03:00
}
2017-08-14 19:32:43 +03:00
In contrary, Vulkan stage input and output interface matching is via explicit
2018-04-10 17:25:26 +03:00
`` Location `` numbers. Details can be found `here <https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#interfaces-iointerfaces> `_ .
2017-08-14 19:32:43 +03:00
To translate HLSL to SPIR-V for Vulkan, semantic strings need to be mapped to
Vulkan `` Location `` numbers properly. This can be done either explicitly via
information provided by the developer or implicitly by the compiler.
2017-08-25 18:56:42 +03:00
Explicit `` Location `` number assignment
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
`` [[vk::location(X)]] `` can be attached to the entities where semantic are
allowed to attach (struct fields, function parameters, and function returns).
For the above exmaple we can have:
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
.. code :: hlsl
struct VSInput {
[[vk::location(0)]] float4 pos : POSITION;
[[vk::location(1)]] float3 norm : NORMAL;
};
[[vk::location(1)]]
float4 VSMain(in VSInput input,
[[vk::location(2)]]
in float4 tex : TEXCOORD,
out float4 pos : SV_Position) : TEXCOORD {
pos = input.pos;
return tex;
}
In the above, input `` POSITION `` , `` NORMAL `` , and `` TEXCOORD `` will be mapped to
`` Location `` 0, 1, and 2, respectively, and output `` TEXCOORD `` will be mapped
to `` Location `` 1.
[TODO] Another explicit way: using command-line options
2017-08-18 06:59:45 +03:00
Please note that the compiler prohibits mixing the explicit and implicit
2017-08-14 19:32:43 +03:00
approach for the same SigPoint to avoid complexity and fallibility. However,
for a certain shader stage, one SigPoint using the explicit approach while the
other adopting the implicit approach is permitted.
Implicit `` Location `` number assignment
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Without hints from the developer, the compiler will try its best to map
semantics to `` Location `` numbers. However, there is no single rule for this
mapping; semantic strings should be handled case by case.
Firstly, under certain `SigPoints <https://github.com/Microsoft/DirectXShaderCompiler/blob/master/docs/DXIL.rst#hlsl-signatures-and-semantics> `_ ,
some system-value (SV) semantic strings will be translated into SPIR-V
`` BuiltIn `` decorations:
2017-10-24 21:32:38 +03:00
.. table :: Mapping from HLSL SV semantic to SPIR-V builtin and execution mode
2018-03-22 17:08:43 +03:00
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| HLSL Semantic | SigPoint | SPIR-V `` BuiltIn `` | SPIR-V Execution Mode | SPIR-V Capability |
+===========================+=============+==========================+=======================+=============================+
| | VSOut | `` Position `` | N/A | `` Shader `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | HSCPIn | `` Position `` | N/A | `` Shader `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | HSCPOut | `` Position `` | N/A | `` Shader `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | DSCPIn | `` Position `` | N/A | `` Shader `` |
2019-07-11 23:19:23 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| SV_Position | DSOut | `` Position `` | N/A | `` Shader `` |
2018-03-22 17:08:43 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| | GSVIn | `` Position `` | N/A | `` Shader `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | GSOut | `` Position `` | N/A | `` Shader `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | PSIn | `` FragCoord `` | N/A | `` Shader `` |
2019-07-11 23:19:23 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| | MSOut | `` Position `` | N/A | `` Shader `` |
2018-03-22 17:08:43 +03:00
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| | VSOut | `` ClipDistance `` | N/A | `` ClipDistance `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | HSCPIn | `` ClipDistance `` | N/A | `` ClipDistance `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | HSCPOut | `` ClipDistance `` | N/A | `` ClipDistance `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | DSCPIn | `` ClipDistance `` | N/A | `` ClipDistance `` |
2019-07-11 23:19:23 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| SV_ClipDistance | DSOut | `` ClipDistance `` | N/A | `` ClipDistance `` |
2018-03-22 17:08:43 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| | GSVIn | `` ClipDistance `` | N/A | `` ClipDistance `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | GSOut | `` ClipDistance `` | N/A | `` ClipDistance `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | PSIn | `` ClipDistance `` | N/A | `` ClipDistance `` |
2019-07-11 23:19:23 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| | MSOut | `` ClipDistance `` | N/A | `` ClipDistance `` |
2018-03-22 17:08:43 +03:00
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| | VSOut | `` CullDistance `` | N/A | `` CullDistance `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | HSCPIn | `` CullDistance `` | N/A | `` CullDistance `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | HSCPOut | `` CullDistance `` | N/A | `` CullDistance `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | DSCPIn | `` CullDistance `` | N/A | `` CullDistance `` |
2019-07-11 23:19:23 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| SV_CullDistance | DSOut | `` CullDistance `` | N/A | `` CullDistance `` |
2018-03-22 17:08:43 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| | GSVIn | `` CullDistance `` | N/A | `` CullDistance `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | GSOut | `` CullDistance `` | N/A | `` CullDistance `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | PSIn | `` CullDistance `` | N/A | `` CullDistance `` |
2019-07-11 23:19:23 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| | MSOut | `` CullDistance `` | N/A | `` CullDistance `` |
2018-03-22 17:08:43 +03:00
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| SV_VertexID | VSIn | `` VertexIndex `` | N/A | `` Shader `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| SV_InstanceID | VSIn | `` InstanceIndex `` | N/A | `` Shader `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| SV_Depth | PSOut | `` FragDepth `` | N/A | `` Shader `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| SV_DepthGreaterEqual | PSOut | `` FragDepth `` | `` DepthGreater `` | `` Shader `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| SV_DepthLessEqual | PSOut | `` FragDepth `` | `` DepthLess `` | `` Shader `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| SV_IsFrontFace | PSIn | `` FrontFacing `` | N/A | `` Shader `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
2019-07-11 23:19:23 +03:00
| | CSIn | `` GlobalInvocationId `` | N/A | `` Shader `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| SV_DispatchThreadID | MSIn | `` GlobalInvocationId `` | N/A | `` Shader `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | ASIn | `` GlobalInvocationId `` | N/A | `` Shader `` |
2018-03-22 17:08:43 +03:00
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
2019-07-11 23:19:23 +03:00
| | CSIn | `` WorkgroupId `` | N/A | `` Shader `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| SV_GroupID | MSIn | `` WorkgroupId `` | N/A | `` Shader `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | ASIn | `` WorkgroupId `` | N/A | `` Shader `` |
2018-03-22 17:08:43 +03:00
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
2019-07-11 23:19:23 +03:00
| | CSIn | `` LocalInvocationId `` | N/A | `` Shader `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| SV_GroupThreadID | MSIn | `` LocalInvocationId `` | N/A | `` Shader `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | ASIn | `` LocalInvocationId `` | N/A | `` Shader `` |
2018-03-22 17:08:43 +03:00
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
2019-07-11 23:19:23 +03:00
| | CSIn | `` LocalInvocationIndex `` | N/A | `` Shader `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| SV_GroupIndex | MSIn | `` LocalInvocationIndex `` | N/A | `` Shader `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | ASIn | `` LocalInvocationIndex `` | N/A | `` Shader `` |
2018-03-22 17:08:43 +03:00
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| SV_OutputControlPointID | HSIn | `` InvocationId `` | N/A | `` Tessellation `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| SV_GSInstanceID | GSIn | `` InvocationId `` | N/A | `` Geometry `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| SV_DomainLocation | DSIn | `` TessCoord `` | N/A | `` Tessellation `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| | HSIn | `` PrimitiveId `` | N/A | `` Tessellation `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | PCIn | `` PrimitiveId `` | N/A | `` Tessellation `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | DsIn | `` PrimitiveId `` | N/A | `` Tessellation `` |
2019-07-11 23:19:23 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| SV_PrimitiveID | GSIn | `` PrimitiveId `` | N/A | `` Geometry `` |
2018-03-22 17:08:43 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| | GSOut | `` PrimitiveId `` | N/A | `` Geometry `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | PSIn | `` PrimitiveId `` | N/A | `` Geometry `` |
2019-07-11 23:19:23 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| | MSOut | `` PrimitiveId `` | N/A | `` MeshShadingNV `` |
2018-03-22 17:08:43 +03:00
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| | PCOut | `` TessLevelOuter `` | N/A | `` Tessellation `` |
| SV_TessFactor +-------------+--------------------------+-----------------------+-----------------------------+
| | DSIn | `` TessLevelOuter `` | N/A | `` Tessellation `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| | PCOut | `` TessLevelInner `` | N/A | `` Tessellation `` |
| SV_InsideTessFactor +-------------+--------------------------+-----------------------+-----------------------------+
| | DSIn | `` TessLevelInner `` | N/A | `` Tessellation `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| SV_SampleIndex | PSIn | `` SampleId `` | N/A | `` SampleRateShading `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| SV_StencilRef | PSOut | `` FragStencilRefEXT `` | N/A | `` StencilExportEXT `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| SV_Barycentrics | PSIn | `` BaryCoord*AMD `` | N/A | `` Shader `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| | GSOut | `` Layer `` | N/A | `` Geometry `` |
2019-07-11 23:19:23 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| SV_RenderTargetArrayIndex | PSIn | `` Layer `` | N/A | `` Geometry `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | MSOut | `` Layer `` | N/A | `` MeshShadingNV `` |
2018-03-22 17:08:43 +03:00
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| | GSOut | `` ViewportIndex `` | N/A | `` MultiViewport `` |
2019-07-11 23:19:23 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| SV_ViewportArrayIndex | PSIn | `` ViewportIndex `` | N/A | `` MultiViewport `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | MSOut | `` ViewportIndex `` | N/A | `` MeshShadingNV `` |
2018-03-22 17:08:43 +03:00
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| | PSIn | `` SampleMask `` | N/A | `` Shader `` |
| SV_Coverage +-------------+--------------------------+-----------------------+-----------------------------+
| | PSOut | `` SampleMask `` | N/A | `` Shader `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| SV_InnerCoverage | PSIn | `` FullyCoveredEXT `` | N/A | `` FragmentFullyCoveredEXT `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
| | VSIn | `` ViewIndex `` | N/A | `` MultiView `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | HSIn | `` ViewIndex `` | N/A | `` MultiView `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
2019-07-11 23:19:23 +03:00
| | DSIn | `` ViewIndex `` | N/A | `` MultiView `` |
| SV_ViewID +-------------+--------------------------+-----------------------+-----------------------------+
2018-03-22 17:08:43 +03:00
| | GSIn | `` ViewIndex `` | N/A | `` MultiView `` |
| +-------------+--------------------------+-----------------------+-----------------------------+
| | PSIn | `` ViewIndex `` | N/A | `` MultiView `` |
2019-07-11 23:19:23 +03:00
| +-------------+--------------------------+-----------------------+-----------------------------+
| | MSIn | `` ViewIndex `` | N/A | `` MultiView `` |
2018-03-22 17:08:43 +03:00
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
2019-06-07 00:15:21 +03:00
| SV_ShadingRate | PSIn | `` FragSizeEXT `` | N/A | `` FragmentDensityEXT `` |
+---------------------------+-------------+--------------------------+-----------------------+-----------------------------+
2017-08-14 19:32:43 +03:00
For entities (function parameters, function return values, struct fields) with
the above SV semantic strings attached, SPIR-V variables of the
`` Input `` /`` Output `` storage class will be created. They will have the
corresponding SPIR-V `` Builtin `` decorations according to the above table.
2017-08-25 18:56:42 +03:00
SV semantic strings not translated into SPIR-V `` BuiltIn `` decorations will be
2017-08-14 19:32:43 +03:00
handled similarly as non-SV (arbitrary) semantic strings: a SPIR-V variable
of the `` Input `` /`` Output `` storage class will be created for each entity with
2017-08-18 06:59:45 +03:00
such semantic string. Then sort all semantic strings according to declaration
(the default, or if `` -fvk-stage-io-order=decl `` is given) or alphabetical
(if `` -fvk-stage-io-order=alpha `` is given) order, and assign `` Location ``
numbers sequentially to the corresponding SPIR-V variables. Note that this means
2017-08-14 19:32:43 +03:00
flattening all structs if structs are used as function parameters or returns.
There is an exception to the above rule for SV_Target[N]. It will always be
mapped to `` Location `` number N.
2018-05-07 17:21:20 +03:00
`` ClipDistance & CullDistance ``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2017-11-07 17:56:10 +03:00
Variables decorated with `` SV_ClipDistanceX `` can be float or vector of float
type. To map them into one float array in the struct, we firstly sort them
asecendingly according to `` X `` , and then concatenate them tightly. For example,
.. code :: hlsl
struct T {
float clip0: SV_ClipDistance0,
};
struct S {
float3 clip5: SV_ClipDistance5;
...
};
void main(T t, S s, float2 clip2 : SV_ClipDistance2) { ... }
Then we have an float array of size (1 + 2 + 3 =) 6 for `` ClipDistance `` , with
`` clip0 `` at offset 0, `` clip2 `` at offset 1, `` clip5 `` at offset 3.
2017-11-07 23:17:13 +03:00
Decorating a variable or struct member with the `` ClipDistance `` builtin but not
requiring the `` ClipDistance `` capability is legal as long as we don't read or
write the variable or struct member. But as per the way we handle `shader entry
function`_, this is not satisfied because we need to read their contents to
prepare for the source code entry function call or write back them after the
call. So annotating a variable or struct member with `` SV_ClipDistanceX `` means
requiring the `` ClipDistance `` capability in the generated SPIR-V.
2017-11-07 17:56:10 +03:00
Variables decorated with `` SV_CullDistanceX `` are mapped similarly as above.
2017-08-18 06:56:48 +03:00
HLSL register and Vulkan binding
2017-08-25 18:56:42 +03:00
--------------------------------
2017-08-18 06:56:48 +03:00
In shaders for DirectX, resources are accessed via registers; while in shaders
for Vulkan, it is done via descriptor set and binding numbers. The developer
can explicitly annotate variables in HLSL to specify descriptor set and binding
numbers, or leave it to the compiler to derive implicitly from registers.
2017-08-25 18:56:42 +03:00
Explicit binding number assignment
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2017-08-18 06:56:48 +03:00
`` [[vk::binding(X[, Y])]] `` can be attached to global variables to specify the
2017-10-21 05:37:11 +03:00
descriptor set as `` Y `` and binding number as `` X `` . The descriptor set number
2019-06-04 16:35:04 +03:00
is optional; if missing, it will be zero (If `` -auto-binding-space N `` command
line option is used, then descriptor set #N will be used instead of descriptor
set #0). RW/append/consume structured buffers have associated counters, which
will occupy their own Vulkan descriptors. `` [vk::counter_binding(Z)] `` can be
attached to a RW/append/consume structured buffers to specify the binding number
for the associated counter to `` Z `` . Note that the set number of the counter is
always the same as the main buffer.
2017-08-18 06:56:48 +03:00
2017-08-25 18:56:42 +03:00
Implicit binding number assignment
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2017-08-18 06:56:48 +03:00
2017-10-21 05:37:11 +03:00
Without explicit annotations, the compiler will try to deduce descriptor sets
and binding numbers in the following way:
2017-08-18 06:56:48 +03:00
If there is `` :register(xX, spaceY) `` specified for the given global variable,
the corresponding resource will be assigned to descriptor set `` Y `` and binding
2017-10-21 05:37:11 +03:00
number `` X `` , regardless of the register type `` x `` . Note that this will cause
binding number collision if, say, two resources are of different register
type but the same register number. To solve this problem, four command-line
options, `` -fvk-b-shift N M `` , `` -fvk-s-shift N M `` , `` -fvk-t-shift N M `` , and
`` -fvk-u-shift N M `` , are provided to shift by `` N `` all binding numbers
inferred for register type `` b `` , `` s `` , `` t `` , and `` u `` in space `` M `` ,
respectively.
2017-08-18 06:56:48 +03:00
If there is no register specification, the corresponding resource will be
assigned to the next available binding number, starting from 0, in descriptor
2019-06-04 16:35:04 +03:00
set #0 (If `` -auto-binding-space N `` command line option is used, then
descriptor set #N will be used instead of descriptor set #0).
2017-08-18 06:56:48 +03:00
2017-10-21 05:37:11 +03:00
Summary
~~~~~~~
2017-10-03 18:12:08 +03:00
In summary, the compiler essentially assigns binding numbers in three passes.
- Firstly it handles all declarations with explicit `` [[vk::binding(X[, Y])]] ``
annotation.
- Then the compiler processes all remaining declarations with
2017-10-21 05:37:11 +03:00
`` :register(xX, spaceY) `` annotation, by applying the shift passed in using
command-line option `` -fvk-{b|s|t|u}-shift N M `` , if provided.
2017-10-03 18:12:08 +03:00
- Finally, the compiler assigns next available binding numbers to the rest in
the declaration order.
2017-10-21 05:37:11 +03:00
As an example, for the following code:
.. code :: hlsl
struct S { ... };
ConstantBuffer<S> cbuffer1 : register(b0);
Texture2D<float4> texture1 : register(t0);
Texture2D<float4> texture2 : register(t1, space1);
SamplerState sampler1;
[[vk::binding(3)]]
RWBuffer<float4> rwbuffer1 : register(u5, space2);
2017-10-23 21:57:40 +03:00
If we compile with `` -fvk-t-shift 10 0 -fvk-t-shift 20 1 `` :
2017-10-21 05:37:11 +03:00
- `` rwbuffer1 `` will take binding #3 in set #0, since explicit binding
assignment has precedence over the rest.
- `` cbuffer1 `` will take binding #0 in set #0, since that's what deduced from
the register assignment, and there is no shift requested from command line.
- `` texture1 `` will take binding #10 in set #0, and `` texture2 `` will take
binding #21 in set #1, since we requested an 10 shift on t-type registers.
- `` sampler1 `` will take binding 1 in set #0, since that's the next available
binding number in set #0.
2019-05-02 01:28:14 +03:00
HLSL global variables and Vulkan binding
----------------------------------------
As mentioned above, all global externally-visible non-resource-type stand-alone
variables will be collected into a cbuffer named `` $Globals `` . By default,
the `` $Globals `` cbuffer is placed in descriptor set #0, and the binding number
would be the next available binding number in that set. Meaning, the binding number
depends on where the very first global variable is in the code.
Example 1:
.. code :: hlsl
float4 someColors;
// $Globals cbuffer placed at DescriptorSet #0, Binding #0
Texture2D<float4> texture1;
// texture1 placed at DescriptorSet #0, Binding #1
Example 2:
2017-10-21 05:37:11 +03:00
.. code :: hlsl
2019-05-02 01:28:14 +03:00
Texture2D<float4> texture1;
// texture1 placed at DescriptorSet #0, Binding #0
float4 someColors;
// $Globals cbuffer placed at DescriptorSet #0, Binding #1
In order provide more control over the descriptor set and binding number of the
`` $Globals `` cbuffer, you can use the `` -fvk-bind-globals B S `` command line
option, which will place this cbuffer at descriptor set `` S `` , and binding number `` B `` .
Example 3: (compiled with `` -fvk-bind-globals 2 1 `` )
.. code :: hlsl
Texture2D<float4> texture1;
// texture1 placed at DescriptorSet #0, Binding #0
float4 someColors;
// $Globals cbuffer placed at DescriptorSet #1, Binding #2
Note that if the developer chooses to use this command line option, it is their
responsibility to provide proper numbers and avoid binding overlaps.
2017-08-25 18:56:42 +03:00
HLSL Expressions
================
2017-08-14 19:32:43 +03:00
Unless explicitly noted, matrix per-element operations will be conducted on
each component vector and then collected into the result matrix. The following
sections lists the SPIR-V opcodes for scalars and vectors.
2017-04-15 04:18:21 +03:00
[spirv] Vector types, variable initializers, and comparison (#488)
* [spirv] Translate vector types and handle variable initializers
* Translated vector types and operations on vector types
* +, -, *, /, % on vector <op> vector and vector <op> scalar
* Prefix increment on vectors
* < on vector <op> vector and vector <op> scalar
* Covered both constant initializer and variable initializer
* Applied constant modifier to variables
* [spirv] Translate all comparision operators
* Covers <, <=, >, >=, ==, !=
* For both scalars and vectors
* Also update docs about arithmetic and comparison operators
2017-07-31 19:13:45 +03:00
Arithmetic operators
2017-08-25 18:56:42 +03:00
--------------------
[spirv] Vector types, variable initializers, and comparison (#488)
* [spirv] Translate vector types and handle variable initializers
* Translated vector types and operations on vector types
* +, -, *, /, % on vector <op> vector and vector <op> scalar
* Prefix increment on vectors
* < on vector <op> vector and vector <op> scalar
* Covered both constant initializer and variable initializer
* Applied constant modifier to variables
* [spirv] Translate all comparision operators
* Covers <, <=, >, >=, ==, !=
* For both scalars and vectors
* Also update docs about arithmetic and comparison operators
2017-07-31 19:13:45 +03:00
2017-08-14 19:32:43 +03:00
`Arithmetic operators <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509631(v=vs.85).aspx#Additive_and_Multiplicative_Operators> `_
(`` + `` , `` - `` , `` * `` , `` / `` , `` % `` ) are translated into their corresponding
SPIR-V opcodes according to the following table.
[spirv] Vector types, variable initializers, and comparison (#488)
* [spirv] Translate vector types and handle variable initializers
* Translated vector types and operations on vector types
* +, -, *, /, % on vector <op> vector and vector <op> scalar
* Prefix increment on vectors
* < on vector <op> vector and vector <op> scalar
* Covered both constant initializer and variable initializer
* Applied constant modifier to variables
* [spirv] Translate all comparision operators
* Covers <, <=, >, >=, ==, !=
* For both scalars and vectors
* Also update docs about arithmetic and comparison operators
2017-07-31 19:13:45 +03:00
+-------+-----------------------------+-------------------------------+--------------------+
| | (Vector of) Signed Integers | (Vector of) Unsigned Integers | (Vector of) Floats |
2017-08-14 19:32:43 +03:00
+=======+=============================+===============================+====================+
[spirv] Vector types, variable initializers, and comparison (#488)
* [spirv] Translate vector types and handle variable initializers
* Translated vector types and operations on vector types
* +, -, *, /, % on vector <op> vector and vector <op> scalar
* Prefix increment on vectors
* < on vector <op> vector and vector <op> scalar
* Covered both constant initializer and variable initializer
* Applied constant modifier to variables
* [spirv] Translate all comparision operators
* Covers <, <=, >, >=, ==, !=
* For both scalars and vectors
* Also update docs about arithmetic and comparison operators
2017-07-31 19:13:45 +03:00
| `` + `` | `` OpIAdd `` | `` OpFAdd `` |
+-------+-------------------------------------------------------------+--------------------+
| `` - `` | `` OpISub `` | `` OpFSub `` |
+-------+-------------------------------------------------------------+--------------------+
| `` * `` | `` OpIMul `` | `` OpFMul `` |
+-------+-----------------------------+-------------------------------+--------------------+
| `` / `` | `` OpSDiv `` | `` OpUDiv `` | `` OpFDiv `` |
+-------+-----------------------------+-------------------------------+--------------------+
| `` % `` | `` OpSRem `` | `` OpUMod `` | `` OpFRem `` |
+-------+-----------------------------+-------------------------------+--------------------+
2017-08-14 19:32:43 +03:00
Note that for modulo operation, SPIR-V has two sets of instructions: `` Op*Rem ``
and `` Op*Mod `` . For `` Op*Rem `` , the sign of a non-0 result comes from the first
operand; while for `` Op*Mod `` , the sign of a non-0 result comes from the second
operand. HLSL doc does not mandate which set of instructions modulo operations
should be translated into; it only says "the % operator is defined only in cases
where either both sides are positive or both sides are negative." So technically
it's undefined behavior to use the modulo operation with operands of different
signs. But considering HLSL's C heritage and the behavior of Clang frontend, we
translate modulo operators into `` Op*Rem `` (there is no `` OpURem `` ).
[spirv] Vector types, variable initializers, and comparison (#488)
* [spirv] Translate vector types and handle variable initializers
* Translated vector types and operations on vector types
* +, -, *, /, % on vector <op> vector and vector <op> scalar
* Prefix increment on vectors
* < on vector <op> vector and vector <op> scalar
* Covered both constant initializer and variable initializer
* Applied constant modifier to variables
* [spirv] Translate all comparision operators
* Covers <, <=, >, >=, ==, !=
* For both scalars and vectors
* Also update docs about arithmetic and comparison operators
2017-07-31 19:13:45 +03:00
2017-08-14 19:32:43 +03:00
For multiplications of float vectors and float scalars, the dedicated SPIR-V
operation `` OpVectorTimesScalar `` will be used. Similarly, for multiplications
of float matrices and float scalars, `` OpMatrixTimesScalar `` will be generated.
[spirv] Vector types, variable initializers, and comparison (#488)
* [spirv] Translate vector types and handle variable initializers
* Translated vector types and operations on vector types
* +, -, *, /, % on vector <op> vector and vector <op> scalar
* Prefix increment on vectors
* < on vector <op> vector and vector <op> scalar
* Covered both constant initializer and variable initializer
* Applied constant modifier to variables
* [spirv] Translate all comparision operators
* Covers <, <=, >, >=, ==, !=
* For both scalars and vectors
* Also update docs about arithmetic and comparison operators
2017-07-31 19:13:45 +03:00
[spirv] Translate bitwise operators (#495)
* Covers ~, &, |, ^, <<, >>, &=, |=, ^=, <<=, >>=
* For int/uint and vector of int/uint
2017-08-01 02:14:59 +03:00
Bitwise operators
2017-08-25 18:56:42 +03:00
-----------------
[spirv] Translate bitwise operators (#495)
* Covers ~, &, |, ^, <<, >>, &=, |=, ^=, <<=, >>=
* For int/uint and vector of int/uint
2017-08-01 02:14:59 +03:00
2017-08-14 19:32:43 +03:00
`Bitwise operators <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509631(v=vs.85).aspx#Bitwise_Operators> `_
(`` ~ `` , `` & `` , `` | `` , `` ^ `` , `` << `` , `` >> `` ) are translated into their
corresponding SPIR-V opcodes according to the following table.
[spirv] Translate bitwise operators (#495)
* Covers ~, &, |, ^, <<, >>, &=, |=, ^=, <<=, >>=
* For int/uint and vector of int/uint
2017-08-01 02:14:59 +03:00
+--------+-----------------------------+-------------------------------+
| | (Vector of) Signed Integers | (Vector of) Unsigned Integers |
2017-08-14 19:32:43 +03:00
+========+=============================+===============================+
[spirv] Translate bitwise operators (#495)
* Covers ~, &, |, ^, <<, >>, &=, |=, ^=, <<=, >>=
* For int/uint and vector of int/uint
2017-08-01 02:14:59 +03:00
| `` ~ `` | `` OpNot `` |
+--------+-------------------------------------------------------------+
| `` & `` | `` OpBitwiseAnd `` |
+--------+-------------------------------------------------------------+
| `` | `` | `` OpBitwiseOr `` |
+--------+-----------------------------+-------------------------------+
| `` ^ `` | `` OpBitwiseXor `` |
+--------+-----------------------------+-------------------------------+
| `` << `` | `` OpShiftLeftLogical `` |
+--------+-----------------------------+-------------------------------+
| `` >> `` | `` OpShiftRightArithmetic `` | `` OpShiftRightLogical `` |
+--------+-----------------------------+-------------------------------+
2018-03-17 03:19:20 +03:00
Note that for `` << `` /`` >> `` , the right hand side will be culled: only the `` n ``
- 1 least significant bits are considered, where `` n `` is the bitwidth of the
left hand side.
[spirv] Vector types, variable initializers, and comparison (#488)
* [spirv] Translate vector types and handle variable initializers
* Translated vector types and operations on vector types
* +, -, *, /, % on vector <op> vector and vector <op> scalar
* Prefix increment on vectors
* < on vector <op> vector and vector <op> scalar
* Covered both constant initializer and variable initializer
* Applied constant modifier to variables
* [spirv] Translate all comparision operators
* Covers <, <=, >, >=, ==, !=
* For both scalars and vectors
* Also update docs about arithmetic and comparison operators
2017-07-31 19:13:45 +03:00
Comparison operators
2017-08-25 18:56:42 +03:00
--------------------
[spirv] Vector types, variable initializers, and comparison (#488)
* [spirv] Translate vector types and handle variable initializers
* Translated vector types and operations on vector types
* +, -, *, /, % on vector <op> vector and vector <op> scalar
* Prefix increment on vectors
* < on vector <op> vector and vector <op> scalar
* Covered both constant initializer and variable initializer
* Applied constant modifier to variables
* [spirv] Translate all comparision operators
* Covers <, <=, >, >=, ==, !=
* For both scalars and vectors
* Also update docs about arithmetic and comparison operators
2017-07-31 19:13:45 +03:00
2017-08-14 19:32:43 +03:00
`Comparison operators <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509631(v=vs.85).aspx#Comparison_Operators> `_
(`` < `` , `` <= `` , `` > `` , `` >= `` , `` == `` , `` != `` ) are translated into their
corresponding SPIR-V opcodes according to the following table.
[spirv] Vector types, variable initializers, and comparison (#488)
* [spirv] Translate vector types and handle variable initializers
* Translated vector types and operations on vector types
* +, -, *, /, % on vector <op> vector and vector <op> scalar
* Prefix increment on vectors
* < on vector <op> vector and vector <op> scalar
* Covered both constant initializer and variable initializer
* Applied constant modifier to variables
* [spirv] Translate all comparision operators
* Covers <, <=, >, >=, ==, !=
* For both scalars and vectors
* Also update docs about arithmetic and comparison operators
2017-07-31 19:13:45 +03:00
+--------+-----------------------------+-------------------------------+------------------------------+
| | (Vector of) Signed Integers | (Vector of) Unsigned Integers | (Vector of) Floats |
2017-08-14 19:32:43 +03:00
+========+=============================+===============================+==============================+
[spirv] Vector types, variable initializers, and comparison (#488)
* [spirv] Translate vector types and handle variable initializers
* Translated vector types and operations on vector types
* +, -, *, /, % on vector <op> vector and vector <op> scalar
* Prefix increment on vectors
* < on vector <op> vector and vector <op> scalar
* Covered both constant initializer and variable initializer
* Applied constant modifier to variables
* [spirv] Translate all comparision operators
* Covers <, <=, >, >=, ==, !=
* For both scalars and vectors
* Also update docs about arithmetic and comparison operators
2017-07-31 19:13:45 +03:00
| `` < `` | `` OpSLessThan `` | `` OpULessThan `` | `` OpFOrdLessThan `` |
+--------+-----------------------------+-------------------------------+------------------------------+
| `` <= `` | `` OpSLessThanEqual `` | `` OpULessThanEqual `` | `` OpFOrdLessThanEqual `` |
+--------+-----------------------------+-------------------------------+------------------------------+
| `` > `` | `` OpSGreaterThan `` | `` OpUGreaterThan `` | `` OpFOrdGreaterThan `` |
+--------+-----------------------------+-------------------------------+------------------------------+
| `` >= `` | `` OpSGreaterThanEqual `` | `` OpUGreaterThanEqual `` | `` OpFOrdGreaterThanEqual `` |
+--------+-----------------------------+-------------------------------+------------------------------+
| `` == `` | `` OpIEqual `` | `` OpFOrdEqual `` |
+--------+-------------------------------------------------------------+------------------------------+
| `` != `` | `` OpINotEqual `` | `` OpFOrdNotEqual `` |
+--------+-------------------------------------------------------------+------------------------------+
2017-08-14 19:32:43 +03:00
Note that for comparison of (vectors of) floats, SPIR-V has two sets of
instructions: `` OpFOrd* `` , `` OpFUnord* `` . We translate into `` OpFOrd* `` ones.
2017-04-15 04:18:21 +03:00
2017-08-01 21:25:32 +03:00
Boolean math operators
2017-08-25 18:56:42 +03:00
----------------------
2017-08-01 21:25:32 +03:00
2017-08-14 19:32:43 +03:00
`Boolean match operators <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509631(v=vs.85).aspx#Boolean_Math_Operators> `_
(`` && `` , `` || `` , `` ?: `` ) are translated into their corresponding SPIR-V opcodes
according to the following table.
2017-08-01 21:25:32 +03:00
+--------+----------------------+
| | (Vector of) Booleans |
2017-08-14 19:32:43 +03:00
+========+======================+
2017-08-01 21:25:32 +03:00
| `` && `` | `` OpLogicalAnd `` |
+--------+----------------------+
| `` || `` | `` OpLogicalOr `` |
+--------+----------------------+
| `` ?: `` | `` OpSelect `` |
+--------+----------------------+
2017-08-14 19:32:43 +03:00
Please note that "unlike short-circuit evaluation of `` && `` , `` || `` , and `` ?: ``
in C, HLSL expressions never short-circuit an evaluation because they are vector
operations. All sides of the expression are always evaluated."
2017-08-01 21:25:32 +03:00
2017-08-01 19:10:48 +03:00
Unary operators
2017-08-25 18:56:42 +03:00
---------------
2017-08-01 19:10:48 +03:00
2017-08-09 08:18:51 +03:00
For `unary operators <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509631(v=vs.85).aspx#Unary_Operators> `_ :
2017-08-01 19:10:48 +03:00
2017-08-14 19:32:43 +03:00
- `` ! `` is translated into `` OpLogicalNot `` . Parsing will gurantee the operands
are of boolean types by inserting necessary casts.
2017-08-01 19:10:48 +03:00
- `` + `` requires no additional SPIR-V instructions.
2017-08-14 19:32:43 +03:00
- `` - `` is translated into `` OpSNegate `` and `` OpFNegate `` for (vectors of)
integers and floats, respectively.
2017-08-01 19:10:48 +03:00
2017-08-02 02:31:25 +03:00
Casts
2017-08-25 18:56:42 +03:00
-----
2017-08-02 02:31:25 +03:00
Casting between (vectors) of scalar types is translated according to the following table:
+------------+-------------------+-------------------+-------------------+-------------------+
| From \\ To | Bool | SInt | UInt | Float |
2017-08-14 19:32:43 +03:00
+============+===================+===================+===================+===================+
2017-08-02 02:31:25 +03:00
| Bool | no-op | select between one and zero |
+------------+-------------------+-------------------+-------------------+-------------------+
| SInt | | no-op | `` OpBitcast `` | `` OpConvertSToF `` |
+------------+ +-------------------+-------------------+-------------------+
| UInt | compare with zero | `` OpBitcast `` | no-op | `` OpConvertUToF `` |
+------------+ +-------------------+-------------------+-------------------+
| Float | | `` OpConvertFToS `` | `` OpConvertFToU `` | no-op |
+------------+-------------------+-------------------+-------------------+-------------------+
2017-11-03 15:37:46 +03:00
It is also feasible in HLSL to cast a float matrix to another float matrix with a smaller size.
This is known as matrix truncation cast. For instance, the following code casts a 3x4 matrix
into a 2x3 matrix.
.. code :: hlsl
float3x4 m = { 1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12 };
float2x3 a = (float2x3)m;
Such casting takes the upper-left most corner of the original matrix to generate the result.
In the above example, matrix `` a `` will have 2 rows, with 3 columns each. First row will be
`` 1, 2, 3 `` and the second row will be `` 5, 6, 7 `` .
2017-08-03 02:27:56 +03:00
Indexing operator
2017-08-25 18:56:42 +03:00
-----------------
2017-08-03 02:27:56 +03:00
2017-08-14 19:32:43 +03:00
The `` [] `` operator can also be used to access elements in a matrix or vector.
A matrix whose row and/or column count is 1 will be translated into a vector or
scalar. If a variable is used as the index for the dimension whose count is 1,
that variable will be ignored in the generated SPIR-V code. This is because
out-of-bound indexing triggers undefined behavior anyway. For example, for a
1xN matrix `` mat `` , `` mat[index][0] `` will be translated into
`` OpAccessChain ... %mat %uint_0 `` . Similarly, variable index into a size 1
vector will also be ignored and the only element will be always returned.
2017-08-03 02:27:56 +03:00
2017-09-21 06:28:22 +03:00
Assignment operators
--------------------
Assigning to struct object may involve decomposing the source struct object and
assign each element separately and recursively. This happens when the source
struct object is of different memory layout from the destination struct object.
For example, for the following source code:
.. code :: hlsl
struct S {
float a;
float2 b;
float2x3 c;
};
ConstantBuffer<S> cbuf;
RWStructuredBuffer<S> sbuf;
...
sbuf[0] = cbuf[0];
...
We need to assign each element because `` ConstantBuffer `` and
`` RWStructuredBuffer `` has different memory layout.
2017-08-25 18:56:42 +03:00
HLSL Control Flows
==================
2017-04-15 04:18:21 +03:00
2017-08-14 19:32:43 +03:00
This section lists how various HLSL control flows are mapped.
2017-08-09 08:18:51 +03:00
2017-08-14 19:32:43 +03:00
Switch statement
2017-08-25 18:56:42 +03:00
----------------
2017-08-09 08:18:51 +03:00
2017-08-14 19:32:43 +03:00
HLSL `switch statements <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509669(v=vs.85).aspx> `_
are translated into SPIR-V using:
2017-08-09 08:18:51 +03:00
2017-08-14 19:32:43 +03:00
- **OpSwitch** : if (all case values are integer literals or constant integer
variables) and (no attribute or the `` forcecase `` attribute is specified)
- **A series of if statements** : for all other scenarios (e.g., when
`` flatten `` , `` branch `` , or `` call `` attribute is specified)
Loops (for, while, do)
2017-08-25 18:56:42 +03:00
----------------------
2017-08-09 08:18:51 +03:00
2017-08-14 19:32:43 +03:00
HLSL `for statements <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509602(v=vs.85).aspx> `_ ,
`while statements <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509708(v=vs.85).aspx> `_ ,
and `do statements <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509593(v=vs.85).aspx> `_
are translated into SPIR-V by constructing all necessary basic blocks and using
`` OpLoopMerge `` to organize as structured loops.
The HLSL attributes for these statements are translated into SPIR-V loop control
masks according to the following table:
2017-08-09 08:18:51 +03:00
+-------------------------+--------------------------------------------------+
| HLSL loop attribute | SPIR-V Loop Control Mask |
2017-08-14 19:32:43 +03:00
+=========================+==================================================+
2017-08-09 08:18:51 +03:00
| `` unroll(x) `` | `` Unroll `` |
+-------------------------+--------------------------------------------------+
| `` loop `` | `` DontUnroll `` |
+-------------------------+--------------------------------------------------+
| `` fastopt `` | `` DontUnroll `` |
+-------------------------+--------------------------------------------------+
| `` allow_uav_condition `` | Currently Unimplemented |
+-------------------------+--------------------------------------------------+
2017-04-15 04:18:21 +03:00
2017-08-25 18:56:42 +03:00
HLSL Functions
==============
2017-07-28 18:59:49 +03:00
2017-08-14 19:32:43 +03:00
All functions reachable from the entry-point function will be translated into
SPIR-V code. Functions not reachable from the entry-point function will be
ignored.
2017-07-28 18:59:49 +03:00
2017-08-12 02:08:27 +03:00
Entry function wrapper
2017-08-25 18:56:42 +03:00
----------------------
2017-08-12 02:08:27 +03:00
2017-08-14 19:32:43 +03:00
HLSL entry functions takes in parameters and returns values. These parameters
and return values can have semantics attached or if they are struct type,
the struct fields can have semantics attached. However, in Vulkan, the entry
function must be of the `` void(void) `` signature. To handle this difference,
for a given entry function `` main `` , we will emit a wrapper function for it.
The wrapper function will take the name of the source code entry function,
while the source code entry function will have its name prefixed with "src.".
The wrapper function reads in stage input/builtin variables created according
to semantics and groups them into composites meeting the requirements of the
source code entry point. Then the wrapper calls the source code entry point.
The return value is extracted and components of it will be written to stage
output/builtin variables created according to semantics. For example:
2017-08-12 02:08:27 +03:00
2017-08-14 19:32:43 +03:00
.. code :: hlsl
2017-08-12 02:08:27 +03:00
// HLSL source code
struct S {
bool a : A;
uint2 b: B;
float2x3 c: C;
};
struct T {
S x;
int y: D;
};
T main(T input) {
return input;
}
2017-08-14 19:32:43 +03:00
.. code :: spirv
; SPIR-V code
2017-08-12 02:08:27 +03:00
%in_var_A = OpVariable %_ptr_Input_bool Input
%in_var_B = OpVariable %_ptr_Input_v2uint Input
%in_var_C = OpVariable %_ptr_Input_mat2v3float Input
%in_var_D = OpVariable %_ptr_Input_int Input
%out_var_A = OpVariable %_ptr_Output_bool Output
%out_var_B = OpVariable %_ptr_Output_v2uint Output
%out_var_C = OpVariable %_ptr_Output_mat2v3float Output
%out_var_D = OpVariable %_ptr_Output_int Output
; Wrapper function starts
2017-09-21 06:28:22 +03:00
%main = OpFunction %void None ...
... = OpLabel
2017-08-12 02:08:27 +03:00
%param_var_input = OpVariable %_ptr_Function_T Function
; Load stage input variables and group into the expected composite
2017-09-21 06:28:22 +03:00
%inA = OpLoad %bool %in_var_A
%inB = OpLoad %v2uint %in_var_B
%inC = OpLoad %mat2v3float %in_var_C
%inS = OpCompositeConstruct %S %inA %inB %inC
%inD = OpLoad %int %in_var_D
%inT = OpCompositeConstruct %T %inS %inD
OpStore %param_var_input %inT
2017-08-12 02:08:27 +03:00
2017-09-21 06:28:22 +03:00
%ret = OpFunctionCall %T %src_main %param_var_input
2017-08-12 02:08:27 +03:00
; Extract component values from the composite and store into stage output variables
2017-09-21 06:28:22 +03:00
%outS = OpCompositeExtract %S %ret 0
%outA = OpCompositeExtract %bool %outS 0
OpStore %out_var_A %outA
%outB = OpCompositeExtract %v2uint %outS 1
OpStore %out_var_B %outB
%outC = OpCompositeExtract %mat2v3float %outS 2
OpStore %out_var_C %outC
%outD = OpCompositeExtract %int %ret 1
OpStore %out_var_D %outD
2017-08-12 02:08:27 +03:00
OpReturn
OpFunctionEnd
; Source code entry point starts
%src_main = OpFunction %T None ...
2017-08-14 19:32:43 +03:00
In this way, we can concentrate all stage input/output/builtin variable
manipulation in the wrapper function and handle the source code entry function
just like other nomal functions.
2017-08-12 02:08:27 +03:00
2017-07-28 18:59:49 +03:00
Function parameter
2017-08-25 18:56:42 +03:00
------------------
2017-07-28 18:59:49 +03:00
2017-08-14 19:32:43 +03:00
For a function `` f `` which has a parameter of type `` T `` , the generated SPIR-V
signature will use type `` T* `` for the parameter. At every call site of `` f `` ,
additional local variables will be allocated to hold the actual arguments.
The local variables are passed in as direct function arguments. For example:
.. code :: hlsl
2017-07-28 18:59:49 +03:00
// HLSL source code
float4 f(float a, int b) { ... }
void caller(...) {
...
float4 result = f(...);
...
}
2017-08-14 19:32:43 +03:00
.. code :: spirv
; SPIR-V code
2017-07-28 18:59:49 +03:00
...
%i32PtrType = OpTypePointer Function %int
%f32PtrType = OpTypePointer Function %float
%fnType = OpTypeFunction %v4float %f32PtrType %i32PtrType
...
%f = OpFunction %v4float None %fnType
%a = OpFunctionParameter %f32PtrType
%b = OpFunctionParameter %i32PtrType
...
%caller = OpFunction ...
...
%aAlloca = OpVariable %_ptr_Function_float Function
%bAlloca = OpVariable %_ptr_Function_int Function
...
OpStore %aAlloca ...
OpStore %bAlloca ...
%result = OpFunctioncall %v4float %f %aAlloca %bAlloca
...
2017-08-14 19:32:43 +03:00
This approach gives us unified handling of function parameters and local
variables: both of them are accessed via load/store instructions.
2017-07-28 18:59:49 +03:00
2017-08-01 04:09:02 +03:00
Intrinsic functions
2017-08-25 18:56:42 +03:00
-------------------
2017-04-15 04:18:21 +03:00
2017-10-24 21:32:38 +03:00
The following intrinsic HLSL functions have no direct SPIR-V opcode or GLSL
extended instruction mapping, so they are handled with additional steps:
2017-08-01 04:09:02 +03:00
2017-08-14 19:32:43 +03:00
- `` dot `` : performs dot product of two vectors, each containing floats or
integers. If the two parameters are vectors of floats, we use SPIR-V's
`` OpDot `` instruction to perform the translation. If the two parameters are
2017-09-25 19:23:06 +03:00
vectors of integers, we multiply corresponding vector elements using
2017-08-14 19:32:43 +03:00
`` OpIMul `` and accumulate the results using `` OpIAdd `` to compute the dot
product.
2017-08-25 18:56:42 +03:00
- `` mul `` : performs multiplications. Each argument may be a scalar, vector,
or matrix. Depending on the argument type, this will be translated into
one of the multiplication instructions.
2017-08-14 19:32:43 +03:00
- `` all `` : returns true if all components of the given scalar, vector, or
matrix are true. Performs conversions to boolean where necessary. Uses SPIR-V
`` OpAll `` for scalar arguments and vector arguments. For matrix arguments,
performs `` OpAll `` on each row, and then again on the vector containing the
results of all rows.
- `` any `` : returns true if any component of the given scalar, vector, or matrix
is true. Performs conversions to boolean where necessary. Uses SPIR-V
`` OpAny `` for scalar arguments and vector arguments. For matrix arguments,
performs `` OpAny `` on each row, and then again on the vector containing the
results of all rows.
- `` asfloat `` : converts the component type of a scalar/vector/matrix from float,
uint, or int into float. Uses `` OpBitcast `` . This method currently does not
support taking non-float matrix arguments.
- `` asint `` : converts the component type of a scalar/vector/matrix from float or
uint into int. Uses `` OpBitcast `` . This method currently does not support
conversion into integer matrices.
- `` asuint `` : converts the component type of a scalar/vector/matrix from float
or int into uint. Uses `` OpBitcast `` . This method currently does not support
2017-11-03 15:38:08 +03:00
- `` asuint `` : Converts a double into two 32-bit unsigned integers. Uses SPIR-V `` OpBitCast `` .
- `` asdouble `` : Converts two 32-bit unsigned integers into a double, or four 32-bit unsigned
integers into two doubles. Uses SPIR-V `` OpVectorShuffle `` and `` OpBitCast `` .
2017-08-14 19:32:43 +03:00
conversion into unsigned integer matrices.
2017-09-26 19:18:23 +03:00
- `` isfinite `` : Determines if the specified value is finite. Since `` OpIsFinite ``
2017-10-24 21:32:38 +03:00
requires the `` Kernel `` capability, translation is done using `` OpIsNan `` and
`` OpIsInf `` . A given value is finite iff it is not NaN and not infinite.
- `` clip `` : Discards the current pixel if the specified value is less than zero.
Uses conditional control flow as well as SPIR-V `` OpKill `` .
- `` rcp `` : Calculates a fast, approximate, per-component reciprocal.
Uses SIR-V `` OpFDiv `` .
2017-10-31 17:14:56 +03:00
- `` lit `` : Returns a lighting coefficient vector. This vector is a float4 with
components of (ambient, diffuse, specular, 1). How `` diffuse `` and `` specular ``
are calculated are explained `here <https://msdn.microsoft.com/en-us/library/windows/desktop/bb509619(v=vs.85).aspx> `_ .
2017-11-14 19:09:51 +03:00
- `` D3DCOLORtoUBYTE4 `` : Converts a floating-point, 4D vector set by a D3DCOLOR to a UBYTE4.
This is achieved by performing `` int4(input.zyxw * 255.002) `` using SPIR-V `` OpVectorShuffle `` ,
`` OpVectorTimesScalar `` , and `` OpConvertFToS `` , respectively.
2017-11-15 18:14:24 +03:00
- `` dst `` : Calculates a distance vector. The resulting vector, `` dest `` , has the following specifications:
2017-11-23 02:16:15 +03:00
`` dest.x = 1.0 `` , `` dest.y = src0.y * src1.y `` , `` dest.z = src0.z `` , and `` dest.w = src1.w `` .
2017-11-15 18:14:24 +03:00
Uses SPIR-V `` OpCompositeExtract `` and `` OpFMul `` .
2017-10-24 21:32:38 +03:00
Using SPIR-V opcode
~~~~~~~~~~~~~~~~~~~
2017-10-31 17:14:56 +03:00
The following intrinsic HLSL functions have direct SPIR-V opcodes for them:
2017-10-24 21:32:38 +03:00
2017-11-13 22:08:13 +03:00
==================================== =================================
HLSL Intrinsic Function SPIR-V Opcode
==================================== =================================
`` AllMemoryBarrier `` `` OpMemoryBarrier ``
`` AllMemoryBarrierWithGroupSync `` `` OpControlBarrier ``
`` countbits `` `` OpBitCount ``
`` DeviceMemoryBarrier `` `` OpMemoryBarrier ``
`` DeviceMemoryBarrierWithGroupSync `` `` OpControlBarrier ``
`` ddx `` `` OpDPdx ``
`` ddy `` `` OpDPdy ``
`` ddx_coarse `` `` OpDPdxCoarse ``
`` ddy_coarse `` `` OpDPdyCoarse ``
`` ddx_fine `` `` OpDPdxFine ``
`` ddy_fine `` `` OpDPdyFine ``
`` fmod `` `` OpFMod ``
`` fwidth `` `` OpFwidth ``
`` GroupMemoryBarrier `` `` OpMemoryBarrier ``
`` GroupMemoryBarrierWithGroupSync `` `` OpControlBarrier ``
`` InterlockedAdd `` `` OpAtomicIAdd ``
`` InterlockedAnd `` `` OpAtomicAnd ``
`` InterlockedOr `` `` OpAtomicOr ``
`` InterlockedXor `` `` OpAtomicXor ``
`` InterlockedMin `` `` OpAtomicUMin `` /`` OpAtomicSMin ``
`` InterlockedMax `` `` OpAtomicUMax `` /`` OpAtomicSMax ``
`` InterlockedExchange `` `` OpAtomicExchange ``
`` InterlockedCompareExchange `` `` OpAtomicCompareExchange ``
`` InterlockedCompareStore `` `` OpAtomicCompareExchange ``
`` isnan `` `` OpIsNan ``
`` isInf `` `` OpIsInf ``
`` reversebits `` `` OpBitReverse ``
`` transpose `` `` OpTranspose ``
2017-12-11 22:02:21 +03:00
`` CheckAccessFullyMapped `` `` OpImageSparseTexelsResident ``
2017-11-13 22:08:13 +03:00
==================================== =================================
2017-08-14 19:32:43 +03:00
2017-08-25 18:56:42 +03:00
Using GLSL extended instructions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2017-10-31 17:14:56 +03:00
The following intrinsic HLSL functions are translated using their equivalent
2017-08-25 18:56:42 +03:00
instruction in the `GLSL extended instruction set <https://www.khronos.org/registry/spir-v/specs/1.0/GLSL.std.450.html> `_ .
2017-09-28 17:28:46 +03:00
======================= ===================================
2017-08-25 18:56:42 +03:00
HLSL Intrinsic Function GLSL Extended Instruction
2017-09-28 17:28:46 +03:00
======================= ===================================
2017-08-25 18:56:42 +03:00
`` abs `` `` SAbs `` /`` FAbs ``
`` acos `` `` Acos ``
`` asin `` `` Asin ``
`` atan `` `` Atan ``
2017-09-26 19:18:23 +03:00
`` atan2 `` `` Atan2 ``
2017-08-25 18:56:42 +03:00
`` ceil `` `` Ceil ``
`` clamp `` `` SClamp `` /`` UClamp `` /`` FClamp ``
`` cos `` `` Cos ``
`` cosh `` `` Cosh ``
2017-09-26 19:18:23 +03:00
`` cross `` `` Cross ``
2017-08-25 18:56:42 +03:00
`` degrees `` `` Degrees ``
2017-09-26 19:18:23 +03:00
`` distance `` `` Distance ``
2017-08-25 18:56:42 +03:00
`` radians `` `` Radian ``
`` determinant `` `` Determinant ``
`` exp `` `` Exp ``
`` exp2 `` `` exp2 ``
2017-11-10 20:31:52 +03:00
`` f16tof32 `` `` UnpackHalf2x16 ``
`` f32tof16 `` `` PackHalf2x16 ``
2017-10-16 20:53:08 +03:00
`` faceforward `` `` FaceForward ``
2017-09-26 19:18:23 +03:00
`` firstbithigh `` `` FindSMsb `` / `` FindUMsb ``
`` firstbitlow `` `` FindILsb ``
2017-08-25 18:56:42 +03:00
`` floor `` `` Floor ``
2017-09-26 19:18:23 +03:00
`` fma `` `` Fma ``
`` frac `` `` Fract ``
2017-09-28 17:28:46 +03:00
`` frexp `` `` FrexpStruct ``
`` ldexp `` `` Ldexp ``
2017-08-25 18:56:42 +03:00
`` length `` `` Length ``
2017-09-28 17:28:46 +03:00
`` lerp `` `` FMix ``
2017-08-25 18:56:42 +03:00
`` log `` `` Log ``
2017-09-28 17:28:46 +03:00
`` log10 `` `` Log2 `` (scaled by `` 1/log2(10) `` )
2017-08-25 18:56:42 +03:00
`` log2 `` `` Log2 ``
2017-09-28 17:28:46 +03:00
`` mad `` `` Fma ``
2017-08-25 18:56:42 +03:00
`` max `` `` SMax `` /`` UMax `` /`` FMax ``
`` min `` `` SMin `` /`` UMin `` /`` FMin ``
2017-09-28 17:28:46 +03:00
`` modf `` `` ModfStruct ``
2017-08-25 18:56:42 +03:00
`` normalize `` `` Normalize ``
`` pow `` `` Pow ``
`` reflect `` `` Reflect ``
2017-09-26 19:18:23 +03:00
`` refract `` `` Refract ``
2017-08-25 18:56:42 +03:00
`` round `` `` Round ``
`` rsqrt `` `` InverseSqrt ``
2017-09-26 19:18:23 +03:00
`` saturate `` `` FClamp ``
2017-08-25 18:56:42 +03:00
`` sign `` `` SSign `` /`` FSign ``
`` sin `` `` Sin ``
2017-09-26 19:18:23 +03:00
`` sincos `` `` Sin `` and `` Cos ``
2017-08-25 18:56:42 +03:00
`` sinh `` `` Sinh ``
2017-09-26 19:18:23 +03:00
`` smoothstep `` `` SmoothStep ``
`` sqrt `` `` Sqrt ``
`` step `` `` Step ``
2017-08-25 18:56:42 +03:00
`` tan `` `` Tan ``
`` tanh `` `` Tanh ``
`` trunc `` `` Trunc ``
2017-10-21 05:37:11 +03:00
======================= ===================================
2017-09-21 06:28:22 +03:00
2018-05-08 20:18:28 +03:00
Synchronization intrinsics
~~~~~~~~~~~~~~~~~~~~~~~~~~
Synchronization intrinsics are translated into `` OpMemoryBarrier `` (for those
non-`` WithGroupSync `` variants) or `` OpControlBarrier `` (for those `` WithGroupSync ``
variants) instructions with parameters:
======================= ============ ===== ======= ========= ==============
HLSL SPIR-V SPIR-V Memory Semantics
----------------------- ------------ --------------------------------------
Intrinsic Memory Scope Image Uniform Workgroup AcquireRelease
======================= ============ ===== ======= ========= ==============
`` AllMemoryBarrier `` Device ✓ ✓ ✓ ✓
`` DeviceMemoryBarrier `` Device ✓ ✓ ✓
`` GroupMemoryBarrier `` Workgroup ✓ ✓
======================= ============ ===== ======= ========= ==============
For the `` *WithGroupSync `` intrinsics, SPIR-V memory scope and semantics are the
same as their counterparts in the above. They have an additional execution
scope:
==================================== ======================
HLSL Intrinsic SPIR-V Execution Scope
==================================== ======================
`` AllMemoryBarrierWithGroupSync `` Workgroup
`` DeviceMemoryBarrierWithGroupSync `` Workgroup
`` GroupMemoryBarrierWithGroupSync `` Workgroup
==================================== ======================
2017-10-17 17:46:08 +03:00
HLSL OO features
================
A HLSL struct/class member method is translated into a normal SPIR-V function,
whose signature has an additional first parameter for the struct/class called
upon. Every calling site of the method is generated to pass in the object as
the first argument.
HLSL struct/class static member variables are translated into SPIR-V variables
in the `` Private `` storage class.
2017-09-21 06:28:22 +03:00
HLSL Methods
============
This section lists how various HLSL methods are mapped.
2017-09-29 21:56:10 +03:00
Buffers
-------
2017-09-21 06:28:22 +03:00
2017-09-29 21:56:10 +03:00
`` Buffer ``
~~~~~~~~~~
2017-09-25 19:23:06 +03:00
2017-09-29 21:56:10 +03:00
`` .Load() ``
+++++++++++
Since Buffers are represented as `` OpTypeImage `` with `` Sampled `` set to 1
(meaning to be used with a sampler), `` OpImageFetch `` is used to perform this
operation. The return value of `` OpImageFetch `` is always a four-component
vector; so proper additional instructions are generated to truncate the vector
and return the desired number of elements.
2017-12-13 01:38:30 +03:00
If an output unsigned integer `` status `` argument is present, `` OpImageSparseFetch ``
is used instead. The resulting SPIR-V `` Residency Code `` will be written to `` status `` .
2017-09-25 19:23:06 +03:00
2017-09-29 21:56:10 +03:00
`` operator[] ``
++++++++++++++
Handled similarly as `` .Load() `` .
2017-09-25 19:23:06 +03:00
`` .GetDimensions() ``
2017-09-29 21:56:10 +03:00
++++++++++++++++++++
2017-09-25 19:23:06 +03:00
Since Buffers are represented as `` OpTypeImage `` with dimension of `` Buffer `` ,
`` OpImageQuerySize `` is used to perform this operation.
`` RWBuffer ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~
2017-09-25 19:23:06 +03:00
2017-09-29 21:56:10 +03:00
`` .Load() ``
+++++++++++
Since RWBuffers are represented as `` OpTypeImage `` with `` Sampled `` set to 2
(meaning to be used without a sampler), `` OpImageRead `` is used to perform this
2017-12-13 01:38:30 +03:00
operation. If an output unsigned integer `` status `` argument is present, `` OpImageSparseRead ``
is used instead. The resulting SPIR-V `` Residency Code `` will be written to `` status `` .
2017-09-25 19:23:06 +03:00
2017-09-29 21:56:10 +03:00
`` operator[] ``
++++++++++++++
Using `` operator[] `` for reading is handled similarly as `` .Load() `` , while for
writing, the `` OpImageWrite `` instruction is generated.
2017-09-25 19:23:06 +03:00
`` .GetDimensions() ``
2017-09-29 21:56:10 +03:00
++++++++++++++++++++
Since RWBuffers are represented as `` OpTypeImage `` with dimension of `` Buffer `` ,
`` OpImageQuerySize `` is used to perform this operation.
2017-09-25 19:23:06 +03:00
2017-09-29 21:56:10 +03:00
`` StructuredBuffer `` and `` RWStructuredBuffer ``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2017-09-25 19:23:06 +03:00
`` .GetDimensions() ``
2017-09-29 21:56:10 +03:00
++++++++++++++++++++
Since StructuredBuffers/RWStructuredBuffers are represented as a struct with one
member that is a runtime array of structures, `` OpArrayLength `` is invoked on
the runtime array in order to find the dimension.
2017-09-25 19:23:06 +03:00
`` ByteAddressBuffer ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~~~~~~~~~
2017-09-25 19:23:06 +03:00
`` .GetDimensions() ``
2017-09-29 21:56:10 +03:00
++++++++++++++++++++
2017-09-25 19:23:06 +03:00
Since ByteAddressBuffers are represented as a struct with one member that is a
runtime array of unsigned integers, `` OpArrayLength `` is invoked on the runtime array
in order to find the number of unsigned integers. This is then multiplied by 4 to find
the number of bytes.
2017-09-26 19:19:22 +03:00
`` .Load() `` , `` .Load2() `` , `` .Load3() `` , `` .Load4() ``
2017-09-29 21:56:10 +03:00
+++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-09-26 19:19:22 +03:00
ByteAddressBuffers are represented as a struct with one member that is a runtime array of
unsigned integers. The `` address `` argument passed to the function is first divided by 4
in order to find the offset into the array (because each array element is 4 bytes). The
SPIR-V `` OpAccessChain `` instruction is then used to access that offset, and `` OpLoad `` is
used to load a 32-bit unsigned integer. For `` Load2 `` , `` Load3 `` , and `` Load4 `` , this is
done 2, 3, and 4 times, respectively. Each time the word offset is incremented by 1 before
performing `` OpAccessChain `` . After all `` OpLoad `` operations are performed, a vector is
constructed with all the resulting values.
2017-09-25 19:23:06 +03:00
`` RWByteAddressBuffer ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~~~~~~~~~~~
2017-09-25 19:23:06 +03:00
`` .GetDimensions() ``
2017-09-29 21:56:10 +03:00
++++++++++++++++++++
2017-09-25 19:23:06 +03:00
Since RWByteAddressBuffers are represented as a struct with one member that is a
runtime array of unsigned integers, `` OpArrayLength `` is invoked on the runtime array
in order to find the number of unsigned integers. This is then multiplied by 4 to find
the number of bytes.
2017-09-26 19:19:22 +03:00
`` .Load() `` , `` .Load2() `` , `` .Load3() `` , `` .Load4() ``
2017-09-29 21:56:10 +03:00
+++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-09-26 19:19:22 +03:00
RWByteAddressBuffers are represented as a struct with one member that is a runtime array of
unsigned integers. The `` address `` argument passed to the function is first divided by 4
in order to find the offset into the array (because each array element is 4 bytes). The
SPIR-V `` OpAccessChain `` instruction is then used to access that offset, and `` OpLoad `` is
used to load a 32-bit unsigned integer. For `` Load2 `` , `` Load3 `` , and `` Load4 `` , this is
done 2, 3, and 4 times, respectively. Each time the word offset is incremented by 1 before
performing `` OpAccessChain `` . After all `` OpLoad `` operations are performed, a vector is
constructed with all the resulting values.
`` .Store() `` , `` .Store2() `` , `` .Store3() `` , `` .Store4() ``
2017-09-29 21:56:10 +03:00
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-09-26 19:19:22 +03:00
RWByteAddressBuffers are represented as a struct with one member that is a runtime array of
unsigned integers. The `` address `` argument passed to the function is first divided by 4
in order to find the offset into the array (because each array element is 4 bytes). The
SPIR-V `` OpAccessChain `` instruction is then used to access that offset, and `` OpStore `` is
used to store a 32-bit unsigned integer. For `` Store2 `` , `` Store3 `` , and `` Store4 `` , this is
done 2, 3, and 4 times, respectively. Each time the word offset is incremented by 1 before
performing `` OpAccessChain `` .
2017-10-06 16:59:13 +03:00
`` .Interlocked*() ``
+++++++++++++++++++
================================= =================================
HLSL Intrinsic Method SPIR-V Opcode
================================= =================================
`` .InterlockedAdd() `` `` OpAtomicIAdd ``
`` .InterlockedAnd() `` `` OpAtomicAnd ``
`` .InterlockedOr() `` `` OpAtomicOr ``
`` .InterlockedXor() `` `` OpAtomicXor ``
`` .InterlockedMin() `` `` OpAtomicUMin `` /`` OpAtomicSMin ``
`` .InterlockedMax() `` `` OpAtomicUMax `` /`` OpAtomicSMax ``
`` .InterlockedExchange() `` `` OpAtomicExchange ``
`` .InterlockedCompareExchange() `` `` OpAtomicCompareExchange ``
`` .InterlockedCompareStore() `` `` OpAtomicCompareExchange ``
================================= =================================
2017-09-29 21:56:10 +03:00
`` AppendStructuredBuffer ``
~~~~~~~~~~~~~~~~~~~~~~~~~~
`` .Append() ``
+++++++++++++
The associated counter number will be increased by 1 using `` OpAtomicIAdd `` .
The return value of `` OpAtomicIAdd `` , which is the original count number, will
be used as the index for storing the new element. E.g., for `` buf.Append(vec) `` :
.. code :: spirv
%counter = OpAccessChain %_ptr_Uniform_int %counter_var_buf %uint_0
%index = OpAtomicIAdd %uint %counter %uint_1 %uint_0 %uint_1
%ptr = OpAccessChain %_ptr_Uniform_v4float %buf %uint_0 %index
%val = OpLoad %v4float %vec
OpStore %ptr %val
`` .GetDimensions() ``
++++++++++++++++++++
Since AppendStructuredBuffers are represented as a struct with one member that
is a runtime array, `` OpArrayLength `` is invoked on the runtime array in order
to find the number of elements. The stride is also calculated based on GLSL
`` std430 `` as explained above.
`` ConsumeStructuredBuffer ``
~~~~~~~~~~~~~~~~~~~~~~~~~~~
`` .Consume() ``
++++++++++++++
The associated counter number will be decreased by 1 using `` OpAtomicISub `` .
The return value of `` OpAtomicISub `` minus 1, which is the new count number,
will be used as the index for reading the new element. E.g., for
`` buf.Consume(vec) `` :
.. code :: spirv
%counter = OpAccessChain %_ptr_Uniform_int %counter_var_buf %uint_0
%prev = OpAtomicISub %uint %counter %uint_1 %uint_0 %uint_1
%index = OpISub %uint %prev %uint_1
%ptr = OpAccessChain %_ptr_Uniform_v4float %buf %uint_0 %index
%val = OpLoad %v4float %vec
OpStore %ptr %val
`` .GetDimensions() ``
++++++++++++++++++++
Since ConsumeStructuredBuffers are represented as a struct with one member that
is a runtime array, `` OpArrayLength `` is invoked on the runtime array in order
to find the number of elements. The stride is also calculated based on GLSL
`` std430 `` as explained above.
Read-only textures
------------------
Methods common to all texture types are explained in the "common texture methods"
section. Methods unique to a specific texture type is explained in the section
for that texture type.
Common texture methods
~~~~~~~~~~~~~~~~~~~~~~
2017-12-13 01:38:30 +03:00
`` .Sample(sampler, location[, offset][, clamp][, Status]) ``
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-09-29 21:56:10 +03:00
Not available to `` Texture2DMS `` and `` Texture2DMSArray `` .
The `` OpImageSampleImplicitLod `` instruction is used to translate `` .Sample() ``
since texture types are represented as `` OpTypeImage `` . An `` OpSampledImage `` is
created based on the `` sampler `` passed to the function. The resulting sampled
image and the `` location `` passed to the function are used as arguments to
`` OpImageSampleImplicitLod `` , with the optional `` offset `` tranlated into
2017-12-13 01:38:30 +03:00
addtional SPIR-V image operands `` ConstOffset `` or `` Offset `` on it. The optional
`` clamp `` argument will be translated to the `` MinLod `` image operand.
2017-09-29 21:56:10 +03:00
2017-12-13 01:38:30 +03:00
If an output unsigned integer `` status `` argument is present,
`` OpImageSparseSampleImplicitLod `` is used instead. The resulting SPIR-V
`` Residency Code `` will be written to `` status `` .
2017-10-10 22:36:37 +03:00
2017-12-13 01:38:30 +03:00
`` .SampleLevel(sampler, location, lod[, offset][, Status]) ``
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-09-29 21:56:10 +03:00
Not available to `` Texture2DMS `` and `` Texture2DMSArray `` .
The `` OpImageSampleExplicitLod `` instruction is used to translate this method.
An `` OpSampledImage `` is created based on the `` sampler `` passed to the function.
The resulting sampled image and the `` location `` passed to the function are used
as arguments to `` OpImageSampleExplicitLod `` . The `` lod `` passed to the function
is attached to the instruction as an SPIR-V image operands `` Lod `` . The optional
`` offset `` is also tranlated into addtional SPIR-V image operands `` ConstOffset ``
or `` Offset `` on it.
2017-12-13 01:38:30 +03:00
If an output unsigned integer `` status `` argument is present,
`` OpImageSparseSampleExplicitLod `` is used instead. The resulting SPIR-V
`` Residency Code `` will be written to `` status `` .
2017-10-10 22:36:37 +03:00
2017-12-13 01:38:30 +03:00
`` .SampleGrad(sampler, location, ddx, ddy[, offset][, clamp][, Status]) ``
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-09-29 21:56:10 +03:00
Not available to `` Texture2DMS `` and `` Texture2DMSArray `` .
Similarly to `` .SampleLevel `` , the `` ddx `` and `` ddy `` parameter are attached to
the `` OpImageSampleExplicitLod `` instruction as an SPIR-V image operands
2017-12-13 01:38:30 +03:00
`` Grad `` . The optional `` clamp `` argument will be translated into the `` MinLod ``
image operand.
2017-09-29 21:56:10 +03:00
2017-12-13 01:38:30 +03:00
If an output unsigned integer `` status `` argument is present,
`` OpImageSparseSampleExplicitLod `` is used instead. The resulting SPIR-V
`` Residency Code `` will be written to `` status `` .
2017-10-10 22:36:37 +03:00
2017-12-13 01:38:30 +03:00
`` .SampleBias(sampler, location, bias[, offset][, clamp][, Status]) ``
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-09-29 21:56:10 +03:00
Not available to `` Texture2DMS `` and `` Texture2DMSArray `` .
The translation is similar to `` .Sample() `` , with the `` bias `` parameter
attached to the `` OpImageSampleImplicitLod `` instruction as an SPIR-V image
operands `` Bias `` .
2017-12-13 01:38:30 +03:00
If an output unsigned integer `` status `` argument is present,
`` OpImageSparseSampleImplicitLod `` is used instead. The resulting SPIR-V
`` Residency Code `` will be written to `` status `` .
2017-10-10 22:36:37 +03:00
2017-12-13 01:38:30 +03:00
`` .SampleCmp(sampler, location, comparator[, offset][, clamp][, Status]) ``
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-10-12 18:34:38 +03:00
Not available to `` Texture3D `` , `` Texture2DMS `` , and `` Texture2DMSArray `` .
The translation is similar to `` .Sample() `` , but the
`` OpImageSampleDrefImplicitLod `` instruction are used.
2017-12-13 01:38:30 +03:00
If an output unsigned integer `` status `` argument is present,
`` OpImageSparseSampleDrefImplicitLod `` is used instead. The resulting SPIR-V
`` Residency Code `` will be written to `` status `` .
`` .SampleCmpLevelZero(sampler, location, comparator[, offset][, Status]) ``
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-10-12 18:34:38 +03:00
Not available to `` Texture3D `` , `` Texture2DMS `` , and `` Texture2DMSArray `` .
The translation is similar to `` .Sample() `` , but the
`` OpImageSampleDrefExplicitLod `` instruction are used, with the additional
`` Lod `` image operands set to 0.0.
2017-12-13 01:38:30 +03:00
If an output unsigned integer `` status `` argument is present,
`` OpImageSparseSampleDrefExplicitLod `` is used instead. The resulting SPIR-V
`` Residency Code `` will be written to `` status `` .
2017-10-10 22:36:37 +03:00
`` .Gather() ``
+++++++++++++
2017-09-29 21:56:10 +03:00
Available to `` Texture2D `` , `` Texture2DArray `` , `` TextureCube `` , and
`` TextureCubeArray `` .
The translation is similar to `` .Sample() `` , but the `` OpImageGather ``
2017-10-10 22:36:37 +03:00
instruction is used, with component setting to 0.
2017-12-13 01:38:30 +03:00
If an output unsigned integer `` status `` argument is present,
`` OpImageSparseGather `` is used instead. The resulting SPIR-V
`` Residency Code `` will be written to `` status `` .
2017-10-10 22:36:37 +03:00
`` .GatherRed() `` , `` .GatherGreen() `` , `` .GatherBlue() `` , `` .GatherAlpha() ``
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Available to `` Texture2D `` , `` Texture2DArray `` , `` TextureCube `` , and
`` TextureCubeArray `` .
The `` OpImageGather `` instruction is used to translate these functions, with
component setting to 0, 1, 2, and 3 respectively.
There are a few overloads for these functions:
- For those overloads taking 4 offset parameters, those offset parameters will
be conveyed as an additional `` ConstOffsets `` image operands to the
2018-04-17 00:21:02 +03:00
instruction if those offset parameters are all constants. Otherwise,
4 separate `` OpImageGather `` instructions will be emitted to get each texel
from each offset, using the `` Offset `` image operands.
2017-12-13 01:38:30 +03:00
- For those overloads with the `` status `` parameter, `` OpImageSparseGather ``
is used instead, and the resulting SPIR-V `` Residency Code `` will be
written to `` status `` .
2017-09-29 21:56:10 +03:00
2017-10-12 22:35:29 +03:00
`` .GatherCmp() ``
++++++++++++++++
Available to `` Texture2D `` , `` Texture2DArray `` , `` TextureCube `` , and
`` TextureCubeArray `` .
The translation is similar to `` .Sample() `` , but the `` OpImageDrefGather ``
instruction is used.
2017-12-13 01:38:30 +03:00
For the overload with the output unsigned integer `` status `` argument,
`` OpImageSparseDrefGather `` is used instead. The resulting SPIR-V
`` Residency Code `` will be written to `` status `` .
2017-10-12 22:35:29 +03:00
2017-10-13 18:21:38 +03:00
`` .GatherCmpRed() ``
+++++++++++++++++++
Available to `` Texture2D `` , `` Texture2DArray `` , `` TextureCube `` , and
`` TextureCubeArray `` .
The translation is the same as `` .GatherCmp() `` .
2017-09-29 21:56:10 +03:00
`` .Load(location[, sampleIndex][, offset]) ``
++++++++++++++++++++++++++++++++++++++++++++
The `` OpImageFetch `` instruction is used for translation because texture types
are represented as `` OpTypeImage `` . The last element in the `` location ``
parameter will be used as arguments to the `` Lod `` SPIR-V image operand attached
to the `` OpImageFetch `` instruction, and the rest are used as the coordinate
argument to the instruction. `` offset `` is handled similarly to `` .Sample() `` .
The return value of `` OpImageFetch `` is always a four-component vector; so
proper additional instructions are generated to truncate the vector and return
the desired number of elements.
2017-12-13 01:38:30 +03:00
For the overload with the output unsigned integer `` status `` argument,
`` OpImageSparseFetch `` is used instead. The resulting SPIR-V
`` Residency Code `` will be written to `` status `` .
2017-10-10 22:36:37 +03:00
2017-09-29 21:56:10 +03:00
`` operator[] ``
++++++++++++++
Handled similarly as `` .Load() `` .
`` .mips[lod][position] ``
++++++++++++++++++++++++
Not available to `` TextureCube `` , `` TextureCubeArray `` , `` Texture2DMS `` , and
`` Texture2DMSArray `` .
This method is translated into the `` OpImageFetch `` instruction. The `` lod ``
parameter is attached to the instruction as the parameter to the `` Lod `` SPIR-V
image operands. The `` position `` parameter are used as the coordinate to the
instruction directly.
2018-07-04 22:55:21 +03:00
`` .CalculateLevelOfDetail() `` and `` .CalculateLevelOfDetailUnclamped() ``
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-09-29 21:56:10 +03:00
Not available to `` Texture2DMS `` and `` Texture2DMSArray `` .
Since texture types are represented as `` OpTypeImage `` , the `` OpImageQueryLod ``
instruction is used for translation. An `` OpSampledImage `` is created based on
the `` SamplerState `` passed to the function. The resulting sampled image and
the coordinate passed to the function are used to invoke `` OpImageQueryLod `` .
The result of `` OpImageQueryLod `` is a `` float2 `` . The first element contains
2018-07-04 22:55:21 +03:00
the mipmap array layer. The second element contains the unclamped level of detail.
2017-09-29 21:56:10 +03:00
2017-09-25 19:23:06 +03:00
`` Texture1D ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~
2017-09-25 19:23:06 +03:00
`` .GetDimensions(width) `` or `` .GetDimensions(MipLevel, width, NumLevels) ``
2017-09-29 21:56:10 +03:00
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-09-25 19:23:06 +03:00
Since Texture1D is represented as `` OpTypeImage `` , the `` OpImageQuerySizeLod `` instruction
is used for translation. If a `` MipLevel `` argument is passed to `` GetDimensions `` , it will
be used as the `` Lod `` parameter of the query instruction. Otherwise, `` Lod `` of `` 0 `` be used.
`` Texture1DArray ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~~~~~~
2017-09-25 19:23:06 +03:00
`` .GetDimensions(width, elements) `` or `` .GetDimensions(MipLevel, width, elements, NumLevels) ``
2017-09-29 21:56:10 +03:00
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-09-25 19:23:06 +03:00
Since Texture1DArray is represented as `` OpTypeImage `` , the `` OpImageQuerySizeLod `` instruction
is used for translation. If a `` MipLevel `` argument is present, it will be used as the
`` Lod `` parameter of the query instruction. Otherwise, `` Lod `` of `` 0 `` be used.
`` Texture2D ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~
2017-09-25 19:23:06 +03:00
`` .GetDimensions(width, height) `` or `` .GetDimensions(MipLevel, width, height, NumLevels) ``
2017-09-29 21:56:10 +03:00
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-09-25 19:23:06 +03:00
Since Texture2D is represented as `` OpTypeImage `` , the `` OpImageQuerySizeLod `` instruction
is used for translation. If a `` MipLevel `` argument is present, it will be used as the
`` Lod `` parameter of the query instruction. Otherwise, `` Lod `` of `` 0 `` be used.
`` Texture2DArray ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~~~~~~
2017-09-25 19:23:06 +03:00
`` .GetDimensions(width, height, elements) `` or `` .GetDimensions(MipLevel, width, height, elements, NumLevels) ``
2017-09-29 21:56:10 +03:00
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-09-25 19:23:06 +03:00
Since Texture2DArray is represented as `` OpTypeImage `` , the `` OpImageQuerySizeLod `` instruction
is used for translation. If a `` MipLevel `` argument is present, it will be used as the
`` Lod `` parameter of the query instruction. Otherwise, `` Lod `` of `` 0 `` be used.
`` Texture3D ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~
2017-09-25 19:23:06 +03:00
`` .GetDimensions(width, height, depth) `` or `` .GetDimensions(MipLevel, width, height, depth, NumLevels) ``
2017-09-29 21:56:10 +03:00
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-09-25 19:23:06 +03:00
Since Texture3D is represented as `` OpTypeImage `` , the `` OpImageQuerySizeLod `` instruction
is used for translation. If a `` MipLevel `` argument is present, it will be used as the
`` Lod `` parameter of the query instruction. Otherwise, `` Lod `` of `` 0 `` be used.
`` Texture2DMS ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~~~
`` .sample[sample][position] ``
+++++++++++++++++++++++++++++
This method is translated into the `` OpImageFetch `` instruction. The `` sample ``
parameter is attached to the instruction as the parameter to the `` Sample ``
SPIR-V image operands. The `` position `` parameter are used as the coordinate to
the instruction directly.
2017-09-25 19:23:06 +03:00
`` .GetDimensions(width, height, numSamples) ``
2017-09-29 21:56:10 +03:00
+++++++++++++++++++++++++++++++++++++++++++++
2017-09-25 19:23:06 +03:00
Since Texture2DMS is represented as `` OpTypeImage `` with `` MS `` of `` 1 `` , the `` OpImageQuerySize `` instruction
is used to get the width and the height. Furthermore, `` OpImageQuerySamples `` is used to get the numSamples.
2018-01-20 00:00:23 +03:00
`` .GetSamplePosition(index) ``
+++++++++++++++++++++++++++++
There are no direct mapping SPIR-V instructions for this method. Right now, it
is translated into the SPIR-V code for the following HLSL source code:
.. code :: hlsl
// count is the number of samples in the Texture2DMS(Array)
// index is the index of the sample we are trying to get the position
static const float2 pos2[] = {
{ 4.0/16.0, 4.0/16.0 }, {-4.0/16.0, -4.0/16.0 },
};
static const float2 pos4[] = {
{-2.0/16.0, -6.0/16.0 }, { 6.0/16.0, -2.0/16.0 }, {-6.0/16.0, 2.0/16.0 }, { 2.0/16.0, 6.0/16.0 },
};
static const float2 pos8[] = {
{ 1.0/16.0, -3.0/16.0 }, {-1.0/16.0, 3.0/16.0 }, { 5.0/16.0, 1.0/16.0 }, {-3.0/16.0, -5.0/16.0 },
{-5.0/16.0, 5.0/16.0 }, {-7.0/16.0, -1.0/16.0 }, { 3.0/16.0, 7.0/16.0 }, { 7.0/16.0, -7.0/16.0 },
};
static const float2 pos16[] = {
{ 1.0/16.0, 1.0/16.0 }, {-1.0/16.0, -3.0/16.0 }, {-3.0/16.0, 2.0/16.0 }, { 4.0/16.0, -1.0/16.0 },
{-5.0/16.0, -2.0/16.0 }, { 2.0/16.0, 5.0/16.0 }, { 5.0/16.0, 3.0/16.0 }, { 3.0/16.0, -5.0/16.0 },
{-2.0/16.0, 6.0/16.0 }, { 0.0/16.0, -7.0/16.0 }, {-4.0/16.0, -6.0/16.0 }, {-6.0/16.0, 4.0/16.0 },
{-8.0/16.0, 0.0/16.0 }, { 7.0/16.0, -4.0/16.0 }, { 6.0/16.0, 7.0/16.0 }, {-7.0/16.0, -8.0/16.0 },
};
float2 position = float2(0.0f, 0.0f);
if (count == 2) {
position = pos2[index];
} else if (count == 4) {
position = pos4[index];
} else if (count == 8) {
position = pos8[index];
} else if (count == 16) {
position = pos16[index];
}
From the above, it's clear that the current implementation only supports standard
sample settings, i.e., with 1, 2, 4, 8, or 16 samples. For other cases, the
implementation will just return `(float2)0` .
2017-09-25 19:23:06 +03:00
`` Texture2DMSArray ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~~~~~~~~
`` .sample[sample][position] ``
+++++++++++++++++++++++++++++
This method is translated into the `` OpImageFetch `` instruction. The `` sample ``
parameter is attached to the instruction as the parameter to the `` Sample ``
SPIR-V image operands. The `` position `` parameter are used as the coordinate to
the instruction directly.
2017-09-25 19:23:06 +03:00
`` .GetDimensions(width, height, elements, numSamples) ``
2017-09-29 21:56:10 +03:00
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
2017-09-25 19:23:06 +03:00
Since Texture2DMS is represented as `` OpTypeImage `` with `` MS `` of `` 1 `` , the `` OpImageQuerySize `` instruction
is used to get the width, the height, and the elements. Furthermore, `` OpImageQuerySamples `` is used to get the numSamples.
2018-01-20 00:00:23 +03:00
`` .GetSamplePosition(index) ``
+++++++++++++++++++++++++++++
Similar to Texture2D.
2017-09-27 21:15:32 +03:00
`` TextureCube ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~~~
2017-09-27 21:15:32 +03:00
`` TextureCubeArray ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~~~~~~~~
2017-09-27 21:15:32 +03:00
2017-09-29 21:56:10 +03:00
Read-write textures
-------------------
Methods common to all texture types are explained in the "common texture methods"
section. Methods unique to a specific texture type is explained in the section
for that texture type.
Common texture methods
~~~~~~~~~~~~~~~~~~~~~~
`` .Load() ``
+++++++++++
Since read-write texture types are represented as `` OpTypeImage `` with
`` Sampled `` set to 2 (meaning to be used without a sampler), `` OpImageRead `` is
used to perform this operation.
2017-12-13 01:38:30 +03:00
For the overload with the output unsigned integer `` status `` argument,
`` OpImageSparseRead `` is used instead. The resulting SPIR-V
`` Residency Code `` will be written to `` status `` .
2017-09-29 21:56:10 +03:00
`` operator[] ``
++++++++++++++
Using `` operator[] `` for reading is handled similarly as `` .Load() `` , while for
writing, the `` OpImageWrite `` instruction is generated.
2017-09-27 21:15:32 +03:00
2017-09-25 19:23:06 +03:00
`` RWTexture1D ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~~~
2017-09-25 19:23:06 +03:00
`` .GetDimensions(width) ``
2017-09-29 21:56:10 +03:00
+++++++++++++++++++++++++
2017-09-25 19:23:06 +03:00
The `` OpImageQuerySize `` instruction is used to find the width.
`` RWTexture1DArray ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~~~~~~~~
2017-09-25 19:23:06 +03:00
`` .GetDimensions(width, elements) ``
2017-09-29 21:56:10 +03:00
+++++++++++++++++++++++++++++++++++
2017-10-12 18:34:38 +03:00
The `` OpImageQuerySize `` instruction is used to get a uint2. The first element
is the width, and the second is the elements.
2017-09-25 19:23:06 +03:00
`` RWTexture2D ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~~~
2017-09-25 19:23:06 +03:00
`` .GetDimensions(width, height) ``
2017-09-29 21:56:10 +03:00
+++++++++++++++++++++++++++++++++
2017-09-25 19:23:06 +03:00
The `` OpImageQuerySize `` instruction is used to get a uint2. The first element is the width, and the second
element is the height.
`` RWTexture2DArray ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~~~~~~~~
2017-09-25 19:23:06 +03:00
`` .GetDimensions(width, height, elements) ``
2017-09-29 21:56:10 +03:00
+++++++++++++++++++++++++++++++++++++++++++
2017-09-25 19:23:06 +03:00
The `` OpImageQuerySize `` instruction is used to get a uint3. The first element is the width, the second
element is the height, and the third is the elements.
`` RWTexture3D ``
2017-09-29 21:56:10 +03:00
~~~~~~~~~~~~~~~
2017-09-25 19:23:06 +03:00
`` .GetDimensions(width, height, depth) ``
2017-09-29 21:56:10 +03:00
++++++++++++++++++++++++++++++++++++++++
2017-09-25 19:23:06 +03:00
The `` OpImageQuerySize `` instruction is used to get a uint3. The first element is the width, the second
element is the height, and the third element is the depth.
2017-10-16 22:47:29 +03:00
2017-10-24 21:32:38 +03:00
HLSL Shader Stages
==================
Hull Shaders
------------
2017-10-16 22:47:29 +03:00
Hull shaders corresponds to Tessellation Control Shaders (TCS) in Vulkan.
This section describes how Hull shaders are translated to SPIR-V for Vulkan.
Hull Entry Point Attributes
2017-10-24 21:32:38 +03:00
~~~~~~~~~~~~~~~~~~~~~~~~~~~
2017-10-16 22:47:29 +03:00
The following HLSL attributes are attached to the main entry point of hull shaders
and are translated to SPIR-V execution modes according to the table below:
2017-10-24 21:32:38 +03:00
.. table :: Mapping from HLSL attribute to SPIR-V execution mode
2017-10-16 22:47:29 +03:00
+-------------------------+---------------------+--------------------------+
| HLSL Attribute | value | SPIR-V Execution Mode |
+=========================+=====================+==========================+
| | `` quad `` | `` Quads `` |
| +---------------------+--------------------------+
| `` domain `` | `` tri `` | `` Triangles `` |
| +---------------------+--------------------------+
| | `` isoline `` | `` Isoline `` |
+-------------------------+---------------------+--------------------------+
| | `` integer `` | `` SpacingEqual `` |
| +---------------------+--------------------------+
| | `` fractional_even `` | `` SpacingFractionalEven ` ` |
| `` partitioning `` +---------------------+--------------------------+
| | `` fractional_odd `` | `` SpacingFractionalOdd `` |
| +---------------------+--------------------------+
| | `` pow2 `` | N/A |
+-------------------------+---------------------+--------------------------+
| | `` point `` | `` PointMode `` |
| +---------------------+--------------------------+
| | `` line `` | N/A |
| `` outputtopology `` +---------------------+--------------------------+
| | `` triangle_cw `` | `` VertexOrderCw `` |
| +---------------------+--------------------------+
| | `` triangle_ccw `` | `` VertexOrderCcw `` |
+-------------------------+---------------------+--------------------------+
|`` outputcontrolpoints `` | `` n `` | `` OutputVertices n `` |
+-------------------------+---------------------+--------------------------+
The `` patchconstfunc `` attribute does not have a direct equivalent in SPIR-V.
2017-10-17 17:46:08 +03:00
It specifies the name of the Patch Constant Function. This function is run only
2017-10-16 22:47:29 +03:00
once per patch. This is further described below.
InputPatch and OutputPatch
2017-10-24 21:32:38 +03:00
~~~~~~~~~~~~~~~~~~~~~~~~~~
2017-10-16 22:47:29 +03:00
Both of `` InputPatch<T, N> `` and `` OutputPatch<T, N> `` are translated to an array
of constant size `` N `` where each element is of type `` T `` .
InputPatch can be passed to the Hull shader main entry function as well as the
patch constant function. This would include information about each of the `` N ``
vertices that are input to the tessellation control shader.
OutputPatch is an array containing `` N `` elements (where `` N `` is the number of
output vertices). Each element of the array contains information about an
output vertex. OutputPatch may also be passed to the patch constant function.
2017-10-17 17:46:08 +03:00
The SPIR-V `` InvocationID `` (`` SV_OutputControlPointID `` in HLSL) is used to index
2017-10-16 22:47:29 +03:00
into the InputPatch and OutputPatch arrays to read/write information for the given
vertex.
2017-10-17 17:46:08 +03:00
The hull main entry function in HLSL returns only one value (say, of type `` T `` ), but
2017-10-16 22:47:29 +03:00
that function is in fact executed once for each control point. The Vulkan spec requires that
2017-10-17 17:46:08 +03:00
"Tessellation control shader per-vertex output variables and blocks, and tessellation control,
2017-10-16 22:47:29 +03:00
tessellation evaluation, and geometry shader per-vertex input variables and blocks are required
2017-10-17 17:46:08 +03:00
to be declared as arrays, with each element representing input or output values for a single vertex
2017-10-16 22:47:29 +03:00
of a multi-vertex primitive". Therefore, we need to create a stage output variable that is an array
2017-10-17 17:46:08 +03:00
with elements of type `` T `` . The number of elements of the array is equal to the number of
output control points. Each final output control point is written into the corresponding element in
2017-10-16 22:47:29 +03:00
the array using SV_OutputControlPointID as the index.
Patch Constant Function
2017-10-24 21:32:38 +03:00
~~~~~~~~~~~~~~~~~~~~~~~
2017-10-16 22:47:29 +03:00
As mentioned above, the patch constant function is to be invoked only once per patch.
As a result, in the SPIR-V module, the `entry function wrapper`_ will first invoke the
main entry function, and then use an `` OpControlBarrier `` to wait for all vertex
processing to finish. After the barrier, *only* the first thread (with InvocationID of 0)
will invoke the patch constant function.
2017-10-17 17:46:08 +03:00
The information resulting from the patch constant function will also be returned
2017-10-16 22:47:29 +03:00
as stage output variables. The output struct of the patch constant function must include
`` SV_TessFactor `` and `` SV_InsideTessFactor `` fields which will translate to
2017-10-17 17:46:08 +03:00
`` TessLevelOuter `` and `` TessLevelInner `` builtin variables, respectively. And the rest
2017-10-16 22:47:29 +03:00
will be flattened and translated into normal stage output variables, one for each field.
2017-10-21 05:37:11 +03:00
2017-10-25 16:25:38 +03:00
Geometry Shaders
----------------
This section describes how geometry shaders are translated to SPIR-V for Vulkan.
Geometry Shader Entry Point Attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following HLSL attribute is attached to the main entry point of geometry shaders
and is translated to SPIR-V execution mode as follows:
.. table :: Mapping from geometry shader HLSL attribute to SPIR-V execution mode
+-------------------------+---------------------+--------------------------+
| HLSL Attribute | value | SPIR-V Execution Mode |
+=========================+=====================+==========================+
|`` maxvertexcount `` | `` n `` | `` OutputVertices n `` |
+-------------------------+---------------------+--------------------------+
2017-11-13 18:43:31 +03:00
|`` instance `` | `` n `` | `` Invocations n `` |
+-------------------------+---------------------+--------------------------+
2017-10-25 16:25:38 +03:00
2017-10-25 23:02:23 +03:00
Translation for Primitive Types
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Geometry shader vertex inputs may be qualified with primitive types. Only one primitive type
is allowed to be used in a given geometry shader. The following table shows the SPIR-V execution
mode that is used in order to represent the given primitive type.
.. table :: Mapping from geometry shader primitive type to SPIR-V execution mode
+---------------------+-----------------------------+
| HLSL Primitive Type | SPIR-V Execution Mode |
+=====================+=============================+
|`` point `` | `` InputPoints `` |
+---------------------+-----------------------------+
|`` line `` | `` InputLines `` |
+---------------------+-----------------------------+
|`` triangle `` | `` Triangles `` |
+---------------------+-----------------------------+
|`` lineadj `` | `` InputLinesAdjacency `` |
+---------------------+-----------------------------+
|`` triangleadj `` | `` InputTrianglesAdjacency `` |
+---------------------+-----------------------------+
2017-10-26 21:02:40 +03:00
Translation of Output Stream Types
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Supported output stream types in geometry shaders are: `` PointStream<T> `` ,
`` LineStream<T> `` , and `` TriangleStream<T> `` . These types are translated as the underlying
type `` T `` , which is recursively flattened into stand-alone variables for each field.
Furthermore, output stream objects passed to geometry shader entry points are
required to be annotated with `` inout `` , but the generated SPIR-V only contains
stage output variables for them.
The following table shows the SPIR-V execution mode that is used in order to represent the
given output stream.
.. table :: Mapping from geometry shader output stream type to SPIR-V execution mode
+---------------------+-----------------------------+
| HLSL Output Stream | SPIR-V Execution Mode |
+=====================+=============================+
|`` PointStream `` | `` OutputPoints `` |
+---------------------+-----------------------------+
|`` LineStream `` | `` OutputLineStrip `` |
+---------------------+-----------------------------+
|`` TriangleStream `` | `` OutputTriangleStrip `` |
+---------------------+-----------------------------+
2017-11-08 19:41:43 +03:00
In other shader stages, stage output variables are only written in the `entry
function wrapper`_ after calling the source code entry function. However,
geometry shaders can output as many vertices as they wish, by calling the
`` .Append() `` method on the output stream object. Therefore, it is incorrect to
have only one flush in the entry function wrapper like other stages. Instead,
each time a `` *Stream<T>::Append() `` is encountered, all stage output variables
behind `` T `` will be flushed before SPIR-V `` OpEmitVertex `` instruction is
generated. `` .RestartStrip() `` method calls will be translated into the SPIR-V
`` OpEndPrimitive `` instruction.
2017-10-25 16:25:38 +03:00
2019-02-27 17:58:59 +03:00
Raytracing Shader Stages
------------------------
DirectX Raytracing adds six new shader stages for raytracing namely ray generation, intersection, closest-hit,
any-hit, miss and callable.
| Refer to following pages for details:
| https://docs.microsoft.com/en-us/windows/desktop/direct3d12/direct3d-12-raytracing
| https://docs.microsoft.com/en-us/windows/desktop/direct3d12/direct3d-12-raytracing-hlsl-reference
Flow chart for various stages in a raytracing pipeline is as follows:
::
+---------------------+
| Ray generation |
+---------------------+
|
TraceRay() | +--------------+
| _ _ _ _ _ _ _ _ | Any Hit |
| | +--------------+
V V ^
+---------------------+ |
| Acceleration | +--------------+
| Structure | | Intersection |
| Traversal | +--------------+
+---------------------+ ^
| | |
| |_ _ _ _ _ _ _ _ _ _ _|
|
|
V
+--------------------+ +-------------+
| Is Hit ? | | Callable |
+--------------------+ +-------------+
| |
Yes | | No
V V
+---------+ +------+
| Closest | | Miss |
| Hit | | |
+---------+ +------+
| *Note : DXC does not add special shader profiles for raytracing under -T option.*
| *All raytracing shaders must be compiled as library using lib_6_3/lib_6_4 profile option.*
Ray Generation Stage
~~~~~~~~~~~~~~~~~~~~
| Ray generation shaders start ray tracing work and work on a compute-like 3D grid of threads.
| Entry functions of this stage type are annotated with **[shader("raygeneration")]** in HLSL source.
| Such entry functions must return void and do not accept any arguments.
| For example:
.. code :: hlsl
RaytracingAccelerationStructure rs;
struct Payload
{
float4 color;
};
[shader("raygeneration")]
void main() {
Payload myPayload = { float4(0.0f,0.0f,0.0f,0.0f) };
RayDesc rayDesc;
rayDesc.Origin = float3(0.0f, 0.0f, 0.0f);
rayDesc.Direction = float3(0.0f, 0.0f, -1.0f);
rayDesc.TMin = 0.0f;
rayDesc.TMax = 1000.0f;
TraceRay(rs, 0x0, 0xff, 0, 1, 0, rayDesc, myPayload);
}
Intersection Stage
~~~~~~~~~~~~~~~~~~
| Intersection shader stage is used to implement arbitrary ray-primitive intersections such spheres or axis-aligned bounding boxes (AABB). Triangle primitives do not require a custom intersection shader.
| Entry functions of this stage are annotated with **[shader("intersection")]** in HLSL source.
| Such entry functions must return void and do not accept any arguments.
| For example:
.. code :: hlsl
struct Attribute
{
float2 bary;
};
[shader("intersection")]
void main() {
Attribute myHitAttribute = { float2(0.0f,0.0f) };
ReportHit(0.0f, 0U, myHitAttribute);
}
Closest-Hit Stage
~~~~~~~~~~~~~~~~~
| Hit shaders are invoked when a ray primitive intersection is found. A closest-hit shader
| is invoked for the closest intersection point along a ray and can be used to compute interactions
| at intersection point or spawn secondary rays.
| Entry functions of this stage are annotated with **[shader("closesthit")]** in HLSL source.
| Such entry functions must return void and accept exactly two arguments. First argument must be an inout
| variable of user defined structure type and second argument must be a in variable of user defined structure type.
| For example:
.. code :: hlsl
struct Attribute
{
float2 bary;
};
struct Payload {
float4 color;
};
[shader("closesthit")]
void main(inout Payload a, in Attribute b) {
a.color = float4(0.0f,1.0f,0.0f,0.0f);
}
Any-Hit Stage
~~~~~~~~~~~~~~~~~
| Hit shaders are invoked when a ray primitive intersection is found. An any-hit shader
| is invoked for all intersections along a ray with a primitive.
| Entry functions of this stage are annotated with **[shader("anyhit")]** in HLSL source.
| Such entry functions must return void and accept exactly two arguments. First argument must be an inout
| variable of user defined structure type and second argument must be an in variable of user defined structure type.
| For example:
.. code :: hlsl
struct Attribute
{
float2 bary;
};
struct Payload {
float4 color;
};
[shader("anyhit")]
void main(inout Payload a, in Attribute b) {
a.color = float4(0.0f,1.0f,0.0f,0.0f);
}
Miss Stage
~~~~~~~~~~
| Miss shaders are invoked when no intersection is found.
| Entry functions of this stage are annotated with **[shader("miss")]** in HLSL source.
| Such entry functions return void and accept exactly one argument. First argument must be an inout variable of user defined structure type.
| For example:
.. code :: hlsl
struct Payload {
float4 color;
};
[shader("miss")]
void main(inout Payload a) {
a.color = float4(0.0f,1.0f,0.0f,0.0f);
}
Callable Stage
~~~~~~~~~~~~~~
| Callables are generic function calls which can be invoked from either raygeneration, closest-hit,
| miss or callable shader stages.
| Entry functions of this stage are annotated with **[shader("callable")]** in HLSL source.
| Such entry functions must return void and accept exactly one argument. First argument must be an inout
| variable of user defined structure type.
| For example:
.. code :: hlsl
struct CallData {
float4 data;
};
[shader("callable")]
void main(inout CallData a) {
a.color = float4(0.0f,1.0f,0.0f,0.0f);
}
2019-07-11 23:19:23 +03:00
Mesh and Amplification Shaders
------------------------------
2019-08-06 18:12:43 +03:00
| DirectX adds 2 new shader stages for using MeshShading pipeline namely Mesh and Amplification.
| Amplification shaders corresponds to Task Shaders in Vulkan.
|
2019-07-11 23:19:23 +03:00
| Refer to following HLSL and SPIR-V specs for details:
| https://docs.microsoft.com/<TBD>
| https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/NV/SPV_NV_mesh_shader.asciidoc
2019-08-06 18:12:43 +03:00
|
| This section describes how Mesh and Amplification shaders are translated to SPIR-V for Vulkan.
2019-07-11 23:19:23 +03:00
Entry Point Attributes
~~~~~~~~~~~~~~~~~~~~~~
The following HLSL attributes are attached to the main entry point of Mesh and/or Amplification
shaders and are translated to SPIR-V execution modes according to the table below:
.. table :: Mapping from HLSL attribute to SPIR-V execution mode
2019-08-06 18:12:43 +03:00
+-------------------+--------------------+-------------------------+
| HLSL Attribute | Value | SPIR-V Execution Mode |
+===================+====================+=========================+
|`` outputtopology `` | `` point `` | `` OutputPoints `` |
| +--------------------+-------------------------+
|`` (Mesh shader) `` | `` line `` | `` OutputLinesNV `` |
| +--------------------+-------------------------+
| | `` triangle `` | `` OutputTrianglesNV `` |
+-------------------+--------------------+-------------------------+
| `` numthreads `` | `` X, Y, Z `` | `` LocalSize X, Y, Z `` |
| | | |
| | `` (X*Y*Z <= 128) `` | |
+-------------------+--------------------+-------------------------+
2019-07-11 23:19:23 +03:00
Intrinsics
~~~~~~~~~~
The following HLSL intrinsics are used in Mesh or Amplification shaders
and are translated to SPIR-V intrinsics according to the table below:
.. table :: Mapping from HLSL intrinsics to SPIR-V intrinsics
2019-08-06 18:12:43 +03:00
+---------------------------+--------------------+-----------------------------------------+
| HLSL Intrinsic | Parameters | SPIR-V Intrinsic |
+===========================+====================+=========================================+
| `` SetMeshOutputCounts `` | `` numVertices `` | `` PrimitiveCountNV numPrimitives `` |
| | | |
| `` (Mesh shader) `` | `` numPrimitives `` | |
+---------------------------+--------------------+-----------------------------------------+
| `` DispatchMesh `` | `` ThreadX `` | `` OpControlBarrier `` |
| | | |
| `` (Amplification shader) ` ` | ` ` ThreadY `` | `` TaskCountNV ThreadX*ThreadY*ThreadZ `` |
| | | |
| | `` ThreadZ `` | |
| | | |
| | `` MeshPayload `` | |
+---------------------------+--------------------+-----------------------------------------+
| Note : For `` DispatchMesh `` intrinsic, we also emit `` MeshPayload `` as output block with `` PerTaskNV `` decoration
2019-07-11 23:19:23 +03:00
Mesh Interface Variables
~~~~~~~~~~~~~~~~~~~~~~~~
2019-08-06 18:12:43 +03:00
| Interface variables are defined for Mesh shaders using HLSL modifiers.
| Following table gives high level overview of the mapping:
|
2019-07-11 23:19:23 +03:00
.. table :: Mapping from HLSL modifiers to SPIR-V definitions
+-----------------+-------------------------------------------------------------------------+
| HLSL modifier | SPIR-V definition |
+=================+=========================================================================+
| `` indices `` | Maps to SPIR-V intrinsic `` PrimitiveIndicesNV `` |
2019-08-06 18:12:43 +03:00
| | |
2019-07-11 23:19:23 +03:00
| | Defines SPIR-V Execution Mode `` OutputPrimitivesNV <array-size> `` |
+-----------------+-------------------------------------------------------------------------+
| `` vertices `` | Maps to per-vertex out attributes |
2019-08-06 18:12:43 +03:00
| | |
2019-07-11 23:19:23 +03:00
| | Defines existing SPIR-V Execution Mode `` OutputVertices <array-size> `` |
+-----------------+-------------------------------------------------------------------------+
| `` primitives `` | Maps to per-primitive out attributes with `` PerPrimitiveNV `` decoration |
+-----------------+-------------------------------------------------------------------------+
| `` payload `` | Maps to per-task in attributes with `` PerTaskNV `` decoration |
+-----------------+-------------------------------------------------------------------------+
2019-02-27 17:58:59 +03:00
Raytracing in Vulkan and SPIRV
==============================
| SPIR-V codegen is currently supported for NVIDIA platforms via SPV_NV_ray_tracing extension
| SPIR-V specification for reference:
| https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/NV/SPV_NV_ray_tracing.asciidoc
| Vulkan ray tracing samples:
| https://developer.nvidia.com/rtx/raytracing/vkray
Raytracing Mapping to SPIR-V
----------------------------
Intrinsics
~~~~~~~~~~
| Following table provides mapping for system value intrinsics along with supported shader stages.
============================ ============================ ====== ============ =========== ======= ======== ========
HLSL SPIR-V HLSL Shader Stage
---------------------------- ---------------------------- ---------------------------------------------------------
System Value Intrinsic Builtin Raygen Intersection Closest Hit Any Hit Miss Callable
============================ ============================ ====== ============ =========== ======= ======== ========
`` DispatchRaysIndex() `` `` LaunchIdNV `` ✓ ✓ ✓ ✓ ✓ ✓
`` DispatchRaysDimensions() `` `` LaunchSizeNV `` ✓ ✓ ✓ ✓ ✓ ✓
`` WorldRayOrigin() `` `` WorldRayOriginNV `` ✓ ✓ ✓ ✓
`` WorldRayDirection() `` `` WorldRayDirectionNV `` ✓ ✓ ✓ ✓
`` RayTMin() `` `` RayTminNV `` ✓ ✓ ✓ ✓
`` RayTCurrent() `` `` HitTNV `` ✓ ✓ ✓ ✓
`` RayFlags() `` `` IncomingRayFlagsNV `` ✓ ✓ ✓ ✓
`` InstanceIndex() `` `` InstanceId `` ✓ ✓ ✓
`` InstanceID() `` `` InstanceCustomIndexNV `` ✓ ✓ ✓
`` PrimitiveIndex() `` `` PrimitiveId `` ✓ ✓ ✓
`` ObjectRayOrigin() `` `` ObjectRayOriginNV `` ✓ ✓ ✓
`` ObjectRayDirection() `` `` ObjectRayDirectionNV `` ✓ ✓ ✓
`` ObjectToWorld3x4() `` `` ObjectToWorldNV `` ✓ ✓ ✓
`` ObjectToWorld4x3() `` `` ObjectToWorldNV `` ✓ ✓ ✓
`` WorldToObject3x4() `` `` WorldToObjectNV `` ✓ ✓ ✓
`` WorldToObject4x3() `` `` WorldToObjectNV `` ✓ ✓ ✓
`` HitKind() `` `` HitKindNV `` ✓ ✓ ✓
============================ ============================ ====== ============ =========== ======= ======== ========
| *There is no separate builtin for transposed matrices ObjectToWorld3x4 and WorldToObject3x4 in SPIR-V hence we internally transpose during translation*
| Following table provides mapping for other intrinsics along with supported shader stages.
=========================== ============================ ====== ============ =========== ======= ===== ========
HLSL SPIR-V HLSL Shader Stage
--------------------------- ---------------------------- ------------------------------------------------------
Intrinsic Opcode Raygen Intersection Closest Hit Any Hit Miss Callable
=========================== ============================ ====== ============ =========== ======= ===== ========
`` TraceRay `` `` OpTraceNV `` ✓ ✓ ✓
`` ReportHit `` `` OpReportIntersectionNV `` ✓ ✓
`` IgnoreHit `` `` OpIgnoreIntersectionNV `` ✓ ✓
`` AcceptHitAndEndSearch `` `` OpTerminateRayNV `` ✓ ✓
`` CallShader `` `` OpExecuteCallable `` ✓ ✓ ✓ ✓
=========================== ============================ ====== ============ =========== ======= ===== ========
Resource Types
~~~~~~~~~~~~~~
| Following table provides mapping for new resource types supported in all raytracing shaders.
=================================== =================================
HLSL Type SPIR-V Opcode
----------------------------------- ---------------------------------
`` RaytracingAccelerationStructure `` `` OpTypeAccelerationStructureNV ``
=================================== =================================
Interface Variables
~~~~~~~~~~~~~~~~~~~
| Interface variables are created for various ray tracing storage classes based on intrinsic/shader stage
| Following table gives high level overview of the mapping.
=========================== ===========================================================
SPIR-V Storage Class Created For
--------------------------- -----------------------------------------------------------
`` RayPayloadNV `` Last argument to TraceRay
`` IncomingRayPayloadNV `` First argument of entry for AnyHit/ClosestHit & Miss stage
`` HitAttributeNV `` Last argument to ReportHit
`` CallableDataNV `` Last argument to CallShader
`` IncomingCallableDataNV `` First argument of entry for Callable stage
=========================== ===========================================================
2018-02-21 18:34:01 +03:00
Shader Model 6.0 Wave Intrinsics
================================
2018-03-13 22:24:48 +03:00
2018-04-17 00:16:07 +03:00
Note that Wave intrinsics requires SPIR-V 1.3, which is supported by Vulkan 1.1.
If you use wave intrinsics in your source code, you will need to specify
-fspv-target-env=vulkan1.1 via the command line to target Vulkan 1.1.
2018-03-13 22:24:48 +03:00
Shader model 6.0 introduces a set of wave operations. Apart from
`` WaveGetLaneCount() `` and `` WaveGetLaneIndex() `` , which are translated into
loading from SPIR-V builtin variable `` SubgroupSize `` and
`` SubgroupLocalInvocationId `` respectively, the rest are translated into SPIR-V
group operations with `` Subgroup `` scope according to the following chart:
============= ============================ =================================== ======================
Wave Category Wave Intrinsics SPIR-V Opcode SPIR-V Group Operation
============= ============================ =================================== ======================
Query `` WaveIsFirstLane() `` `` OpGroupNonUniformElect ``
Vote `` WaveActiveAnyTrue() `` `` OpGroupNonUniformAny ``
Vote `` WaveActiveAllTrue() `` `` OpGroupNonUniformAll ``
Vote `` WaveActiveBallot() `` `` OpGroupNonUniformBallot ``
Reduction `` WaveActiveAllEqual() `` `` OpGroupNonUniformAllEqual `` `` Reduction ``
Reduction `` WaveActiveCountBits() `` `` OpGroupNonUniformBallotBitCount `` `` Reduction ``
Reduction `` WaveActiveSum() `` `` OpGroupNonUniform*Add `` `` Reduction ``
Reduction `` WaveActiveProduct() `` `` OpGroupNonUniform*Mul `` `` Reduction ``
Reduction `` WaveActiveBitAdd() `` `` OpGroupNonUniformBitwiseAnd `` `` Reduction ``
Reduction `` WaveActiveBitOr() `` `` OpGroupNonUniformBitwiseOr `` `` Reduction ``
Reduction `` WaveActiveBitXor() `` `` OpGroupNonUniformBitwiseXor `` `` Reduction ``
Reduction `` WaveActiveMin() `` `` OpGroupNonUniform*Min `` `` Reduction ``
Reduction `` WaveActiveMax() `` `` OpGroupNonUniform*Max `` `` Reduction ``
Scan/Prefix `` WavePrefixSum() `` `` OpGroupNonUniform*Add `` `` ExclusiveScan ``
Scan/Prefix `` WavePrefixProduct() `` `` OpGroupNonUniform*Mul `` `` ExclusiveScan ``
2018-03-16 20:40:00 +03:00
Scan/Prefix `` WavePrefixCountBits() `` `` OpGroupNonUniformBallotBitCount `` `` ExclusiveScan ``
2018-03-13 22:24:48 +03:00
Broadcast `` WaveReadLaneAt() `` `` OpGroupNonUniformBroadcast ``
Broadcast `` WaveReadLaneFirst() `` `` OpGroupNonUniformBroadcastFirst ``
Quad `` QuadReadAcrossX() `` `` OpGroupNonUniformQuadSwap ``
Quad `` QuadReadAcrossY() `` `` OpGroupNonUniformQuadSwap ``
Quad `` QuadReadAcrossDiagonal() `` `` OpGroupNonUniformQuadSwap ``
Quad `` QuadReadLaneAt() `` `` OpGroupNonUniformQuadBroadcast ``
============= ============================ =================================== ======================
2018-03-01 23:48:09 +03:00
2018-08-01 17:49:51 +03:00
Supported Command-line Options
==============================
Command-line options supported by SPIR-V CodeGen are listed below. They are
also recognized by the library API calls.
General options
---------------
- `` -T `` : specifies shader profile
- `` -E `` : specifies entry point
- `` -D `` : Defines macro
- `` -I `` : Adds directory to include search path
- `` -O{|0|1|2|3} `` : Specifies optimization level
- `` -enable-16bit-types `` : enables 16-bit types and disables min precision types
- `` -Zpc `` : Packs matrices in column-major order by deafult
- `` -Zpr `` : Packs matrices in row-major order by deafult
- `` -Fc `` : outputs SPIR-V disassembly to the given file
- `` -Fe `` : outputs warnings and errors to the given file
- `` -Fo `` : outputs SPIR-V code to the given file
- `` -Fh `` : outputs SPIR-V code as a header file
- `` -Vn `` : specifies the variable name for SPIR-V code in generated header file
- `` -Zi `` : Emits more debug information (see `Debugging`_ )
- `` -Cc `` : colorizes SPIR-V disassembly
- `` -No `` : adds instruction byte offsets to SPIR-V disassembly
- `` -H `` : Shows header includes and nesting depth
- `` -Vi `` : Shows details about the include process
- `` -Vd `` : Disables SPIR-V verification
- `` -WX `` : Treats warnings as errors
- `` -no-warnings `` : Suppresses all warnings
- `` -flegacy-macro-expansion `` : expands the operands before performing
token-pasting operation (fxc behavior)
Vulkan-specific options
-----------------------
2017-10-21 05:37:11 +03:00
The following command line options are added into `` dxc `` to support SPIR-V
codegen for Vulkan:
- `` -spirv `` : Generates SPIR-V code.
- `` -fvk-b-shift N M `` : Shifts by `` N `` the inferred binding numbers for all
resources in b-type registers of space `` M `` . Specifically, for a resouce
attached with `` :register(bX, spaceM) `` but not `` [vk::binding(...)] `` ,
sets its Vulkan descriptor set to `` M `` and binding number to `` X + N `` . If
you need to shift the inferred binding numbers for more than one space,
provide more than one such option. If more than one such option is provided
2018-04-13 22:40:44 +03:00
for the same space, the last one takes effect. If you need to shift the
inferred binding numbers for all sets, use `` all `` as `` M `` .
See `HLSL register and Vulkan binding`_ for explanation and examples.
2017-10-21 05:37:11 +03:00
- `` -fvk-t-shift N M `` , similar to `` -fvk-b-shift `` , but for t-type registers.
- `` -fvk-s-shift N M `` , similar to `` -fvk-b-shift `` , but for s-type registers.
- `` -fvk-u-shift N M `` , similar to `` -fvk-b-shift `` , but for u-type registers.
2018-08-03 14:36:18 +03:00
- `` -fvk-bind-register xX Y N M `` (short alias: `` -vkbr `` ): Binds the resouce
at `` register(xX, spaceY) `` to descriptor set `` M `` and binding `` N `` . This
option cannot be used together with other binding assignment options.
It requires all source code resources have `` :register() `` attribute and
all registers have corresponding Vulkan descriptors specified using this
option.
2019-05-02 01:28:14 +03:00
- `` -fvk-bind-globals N M `` : Places the `` $Globals `` cbuffer at
descriptor set #M and binding #N. See `HLSL global variables and Vulkan binding`_
for explanation and examples.
2018-04-10 17:25:26 +03:00
- `` -fvk-use-gl-layout `` : Uses strict OpenGL `` std140 `` /`` std430 ``
layout rules for resources.
2018-04-08 19:50:57 +03:00
- `` -fvk-use-dx-layout `` : Uses DirectX layout rules for resources.
2018-07-19 17:34:51 +03:00
- `` -fvk-invert-y `` : Negates (additively inverts) SV_Position.y before writing
to stage output. Used to accommodate the difference between Vulkan's
coordinate system and DirectX's. Only allowed in VS/DS/GS.
2018-07-25 03:46:14 +03:00
- `` -fvk-use-dx-position-w `` : Reciprocates (multiplicatively inverts)
SV_Position.w after reading from stage input. Used to accommodate the
difference between Vulkan DirectX: the w component of SV_Position in PS is
stored as 1/w in Vulkan. Only recognized in PS; applying to other stages
is no-op.
2017-10-21 05:37:11 +03:00
- `` -fvk-stage-io-order={alpha|decl} `` : Assigns the stage input/output variable
location number according to alphabetical order or declaration order. See
`HLSL semantic and Vulkan Location`_ for more details.
2018-03-17 20:05:31 +03:00
- `` -fspv-reflect `` : Emits additional SPIR-V instructions to aid reflection.
2018-08-29 18:11:30 +03:00
- `` -fspv-debug=<category> `` : Controls what category of debug information
should be emitted. Accepted values are `` file `` , `` source `` , `` line `` , and
`` tool `` . See `Debugging`_ for more details.
2018-03-28 00:42:16 +03:00
- `` -fspv-extension=<extension> `` : Only allows using `` <extension> `` in CodeGen.
2018-04-03 22:21:23 +03:00
If you want to allow multiple extensions, provide more than one such option. If you
want to allow *all* KHR extensions, use `` -fspv-extension=KHR `` .
2018-04-03 16:12:51 +03:00
- `` -fspv-target-env=<env> `` : Specifies the target environment for this compilation.
The current valid options are `` vulkan1.0 `` and `` vulkan1.1 `` . If no target
environment is provided, `` vulkan1.0 `` is used as default.
2019-08-14 16:45:01 +03:00
- `` -fspv-flatten-resource-arrays `` : Flattens arrays of textures and samplers
into individual resources, each taking one binding number. For example, an
array of 3 textures will become 3 texture resources taking 3 binding numbers.
This makes the behavior similar to DX. Without this option, you would get 1
array object taking 1 binding number. Note that arrays of
{RW|Append|Consume}StructuredBuffers are currently not supported in the
2019-08-22 21:40:35 +03:00
SPIR-V backend. Also note that this requires the optimizer to be able to
resolve all array accesses with constant indeces. Therefore, all loops using
the resource arrays must be marked with `` [unroll] `` .
2018-05-16 21:32:30 +03:00
- `` -Wno-vk-ignored-features `` : Does not emit warnings on ignored features
resulting from no Vulkan support, e.g., cbuffer member initializer.
2017-11-16 22:23:03 +03:00
Unsupported HLSL Features
=========================
The following HLSL language features are not supported in SPIR-V codegen,
either because of no Vulkan equivalents at the moment, or because of deprecation.
* Literal/immediate sampler state: deprecated feature. The compiler will
emit a warning and ignore it.
* `` abort() `` intrinsic function: no Vulkan equivalent. The compiler will emit
an error.
* `` GetRenderTargetSampleCount() `` intrinsic function: no Vulkan equivalent.
(Its GLSL counterpart is `` gl_NumSamples `` , which is not available in GLSL for
Vulkan.) The compiler will emit an error.
* `` GetRenderTargetSamplePosition() `` intrinsic function: no Vulkan equivalent.
(`` gl_SamplePosition `` provides similar functionality but it's only for the
sample currently being processed.) The compiler will emit an error.
* `` tex*() `` intrinsic functions: deprecated features. The compiler will
emit errors.
* `` .GatherCmpGreen() `` , `` .GatherCmpBlue() `` , `` .GatherCmpAlpha() `` intrinsic
method: no Vulkan equivalent. (SPIR-V `` OpImageDrefGather `` instruction does
not take component as input.) The compiler will emit an error.
2017-12-13 01:38:30 +03:00
* Since `` StructuredBuffer `` , `` RWStructuredBuffer `` , `` ByteAddressBuffer `` , and
`` RWByteAddressBuffer `` are not represented as image types in SPIR-V, using the
output unsigned integer `` status `` argument in their `` Load* `` methods is not
supported. Using these methods with the `` status `` argument will cause a compiler error.
2017-12-19 00:48:16 +03:00
* Applying `` row_major `` or `` column_major `` attributes to a stand-alone matrix will be
ignored by the compiler because `` RowMajor `` and `` ColMajor `` decorations in SPIR-V are
only allowed to be applied to members of structures. A warning will be issued by the compiler.
2017-12-19 21:37:48 +03:00
* The Hull shader `` partitioning `` attribute may not have the `` pow2 `` value. The compiler
will emit an error. Other attribute values are supported and described in the
2018-01-03 18:13:04 +03:00
`Hull Entry Point Attributes`_ section.
* `` cbuffer `` /`` tbuffer `` member initializer: no Vulkan equivalent. The compiler
will emit an warning and ignore it.
2018-02-01 23:21:17 +03:00
Appendix
==========
Appendix A. Matrix Representation
---------------------------------
Consider a matrix in HLSL defined as `` float2x3 m; `` . Conceptually, this is a matrix with 2 rows and 3 columns.
2018-08-28 02:40:11 +03:00
This means that you can access its elements via expressions such as `` m[i][j] `` , where `` i `` can be `` {0, 1} `` and `` j `` can be `` {0, 1, 2} `` .
2018-02-01 23:21:17 +03:00
Now let's look how matrices are defined in SPIR-V:
.. code :: spirv
%columnType = OpTypeVector %float <number of rows>
%matType = OpTypeMatrix %columnType <number of columns>
As you can see, SPIR-V conceptually represents matrices as a collection of vectors where each vector is a *column* .
Now, let's represent our float2x3 matrix in SPIR-V. If we choose a naive translation (3 columns, each of which is a vector of size 2), we get:
.. code :: spirv
%v2float = OpTypeVector %float 2
%mat3v2float = OpTypeMatrix %v2float 3
Now, let's use this naive translation to access into the matrix (e.g. `` m[0][2] `` ). This is evaluated by first finding `` n = m[0] `` , and then finding `` n[2] `` .
Notice that in HLSL, `` m[0] `` represents a row, which is a vector of size 3. But accessing the first dimension of the SPIR-V matrix give us
the first column which is a vector of size 2.
.. code :: spirv
2018-02-02 20:44:48 +03:00
2018-02-01 23:21:17 +03:00
; n is a vector of size 2
%n = OpAccessChain %v2float %m %int_0
Notice that in HLSL access `` m[i][j] `` , `` i `` can be `` {0, 1} `` and `` j `` can be `` {0, 1, 2} `` .
But in SPIR-V OpAccessChain access, the first index (`` i `` ) can be `` {0, 1, 2} `` and the second index (`` j `` ) can be `` {1, 0} `` .
Therefore, the naive translation does not work well with indexing.
As a result, we must translate a given HLSL float2x3 matrix (with 2 rows and 3 columns) as a SPIR-V matrix with 3 rows and 2 columns:
.. code :: spirv
%v3float = OpTypeVector %float 3
%mat2v3float = OpTypeMatrix %v3float 2
This way, all accesses into the matrix can be naturally handled correctly.
Packing
~~~~~~~
The HLSL `` row_major `` and `` column_major `` type modifiers change the way packing is done.
The following table provides an example which should make our translation more clear:
+------------------+---------------------------+---------------------------+-----------------------------+-------------------+
| Host CPU Data | HLSL Variable | GPU (HLSL Representation) | GPU (SPIR-V Representation) | SPIR-V Decoration |
+==================+===========================+===========================+=============================+===================+
|`` {1,2,3,4,5,6} `` | `` float2x3 `` | `` [1 3 5] `` | `` [1 2] `` | |
| | | | | |
| | | `` [2 4 6] `` | `` [3 4] `` | `` RowMajor `` |
| | | | | |
| | | | `` [5 6] `` | |
+------------------+---------------------------+---------------------------+-----------------------------+-------------------+
|`` {1,2,3,4,5,6} `` | `` column_major float2x3 `` | `` [1 3 5] `` | `` [1 2] `` | |
| | | | | |
| | | `` [2 4 6] `` | `` [3 4] `` | `` RowMajor `` |
| | | | | |
| | | | `` [5 6] `` | |
+------------------+---------------------------+---------------------------+-----------------------------+-------------------+
|`` {1,2,3,4,5,6} `` | `` row_major float2x3 `` | `` [1 2 3] `` | `` [1 4] `` | |
| | | | | |
| | | `` [4 5 6] `` | `` [2 5] `` | `` ColMajor `` |
| | | | | |
| | | | `` [3 6] `` | |
+------------------+---------------------------+---------------------------+-----------------------------+-------------------+