Contents:
Gallium is essentially an API for writing graphics drivers in a largely device-agnostic fashion. It provides several objects which encapsulate the core services of graphics hardware in a straightforward manner.
Debugging utilities in gallium.
All drivers respond to a set of common debug environment variables, as well as some driver-specific variables. Set them as normal environment variables for the platform or operating system you are running. For example, for Linux this can be done by typing “export var=value” into a console and then running the program from that console.
This option controls if the debug variables should be printed to stderr. This is probably the most useful variable, since it allows you to find which variables a driver uses.
Controls if the Remote Debugger should be used.
If set, this variable will cause the Trace output to be written to the specified file. Paths may be relative or absolute; relative paths are relative to the working directory. For example, setting it to “trace.xml” will cause the trace to be written to a file of the same name in the working directory.
Dump information about the current CPU that the driver is running on.
Gallium has a built-in shader sanity checker. This option controls whether the shader sanity checker prints its warnings and errors to stderr.
Whether the Draw module will attempt to use LLVM for vertex and geometry shaders.
Debug Flags for the i915 driver.
Stop the i915 driver from submitting commands to the hardware.
Dump all commands going to the hardware.
Debug Flags for the llvmpipe driver.
Number of threads that the llvmpipe driver should use.
Debug Flags for the freedreno driver.
The variables of type “flags” all take a string with comma-separated flags to enable different debugging for different parts of the drivers or state tracker. If set to “help”, the driver will print a list of flags which the variable accepts. Order does not matter.
The remote debugger, commonly known as rbug, allows for runtime inspections of Context, Screen, Resources and derived objects and Shader objects; and pausing and stepping of Draw calls. Is used with rbug-gui which is hosted outside of the main mesa repository. rbug is can be used over a network connection, so the debugger does not need to be on the same machine.
TGSI, Tungsten Graphics Shader Infrastructure, is an intermediate language for describing shaders. Since Gallium is inherently shaderful, shaders are an important part of the API. TGSI is the only intermediate representation used by all drivers.
All TGSI instructions, known as opcodes, operate on arbitrary-precision floating-point four-component vectors. An opcode may have up to one destination register, known as dst, and between zero and three source registers, called src0 through src2, or simply src if there is only one.
Some instructions, like I2F, permit re-interpretation of vector components as integers. Other instructions permit using registers as two-component vectors with double precision; see Double ISA.
When an instruction has a scalar result, the result is usually copied into each of the components of dst. When this happens, the result is said to be replicated to dst. RCP is one such instruction.
TGSI supports modifiers on inputs (as well as saturate modifier on instructions).
For inputs which have a floating point type, both absolute value and negation modifiers are supported (with absolute value being applied first). TGSI_OPCODE_MOV is considered to have float input type for applying modifiers.
For inputs which have signed or unsigned type only the negate modifier is supported.
These opcodes are guaranteed to be available regardless of the driver being used.
This instruction replicates its result.
This instruction replicates its result. The results are undefined for src <= 0.
This instruction replicates its result. The results are undefined for src < 0.
This instruction replicates its result.
This instruction replicates its result.
Perform a * b + c with no intermediate rounding step.
This instruction replicates its result.
This instruction replicates its result.
This instruction replicates its result.
This instruction replicates its result.
This instruction replicates its result.
The fine variant is only used when PIPE_CAP_TGSI_FS_FINE_DERIVATIVE is advertised. When it is, the fine version guarantees one derivative per row while DDX is allowed to be the same for the entire 2x2 quad.
The fine variant is only used when PIPE_CAP_TGSI_FS_FINE_DERIVATIVE is advertised. When it is, the fine version guarantees one derivative per column while DDY is allowed to be the same for the entire 2x2 quad.
TBD
TBD
TBD
TBD
This instruction replicates its result.
for array textures src0.y contains the slice for 1D, and src0.z contain the slice for 2D.
for shadow textures with no arrays (and not cube map), src0.z contains the reference value.
for shadow textures with arrays, src0.z contains the reference value for 1D arrays, and src0.w contains the reference value for 2D arrays and cube maps.
for cube map array shadow textures, the reference value cannot be passed in src0.w, and TEX2 must be used instead.
this is the same as TEX, but uses another reg to encode the reference value.
TBD
Note
Considered for removal.
TBD
Note
Considered for removal.
TBD
Note
Considered for removal.
TBD
Note
Considered for removal.
Conditional discard. Allowed in fragment shaders only.
Unconditional discard. Allowed in fragment shaders only.
for cube map array textures and shadow cube maps, the bias value cannot be passed in src0.w, and TXB2 must be used instead.
if the target is a shadow texture, the reference value is always in src.z (this prevents shadow 3d and shadow 2d arrays from using this instruction, but this is not needed).
this is the same as TXB, but uses another reg to encode the lod bias value for cube map arrays and shadow cube maps. Presumably shadow 2d arrays and shadow 3d targets could use this encoding too, but this is not legal.
shadow cube map arrays are neither possible nor required.
This instruction replicates its result.
for cube map array textures, the explicit lod value cannot be passed in src0.w, and TXL2 must be used instead.
if the target is a shadow texture, the reference value is always in src.z (this prevents shadow 3d / 2d array / cube targets from using this instruction, but this is not needed).
this is the same as TXL, but uses another reg to encode the explicit lod value. Presumably shadow 3d / 2d array / cube targets could use this encoding too, but this is not legal.
shadow cube map arrays are neither possible nor required.
push(src.x) push(src.y) push(src.z) push(src.w)
Note
Considered for cleanup.
Note
Considered for removal.
dst.w = pop() dst.z = pop() dst.y = pop() dst.x = pop()
Note
Considered for cleanup.
Note
Considered for removal.
TBD
Note
Considered for cleanup.
Note
Considered for removal.
These opcodes are primarily provided for special-use computational shaders. Support for these opcodes indicated by a special pipe capability bit (TBD).
XXX doesn’t look like most of the opcodes really belong here.
Moves the contents of the source register, assumed to be an integer, into the destination register, which is assumed to be an address (ADDR) register.
As per NV_gpu_shader4, extract a single texel from a specified texture image. The source sampler may not be a CUBE or SHADOW. src 0 is a four-component signed integer vector used to identify the single texel accessed. 3 components + level. Just like texture instructions, an optional offset vector is provided, which is subject to various driver restrictions (regarding range, source of offsets). TXF(uint_vec coord, int_vec offset).
As per NV_gpu_program4, retrieve the dimensions of the texture depending on the target. For 1D (width), 2D/RECT/CUBE (width, height), 3D (width, height, depth), 1D array (width, layers), 2D array (width, height, layers). Also return the number of accessible levels (last_level - first_level + 1) in W.
For components which don’t return a resource dimension, their value is undefined.
As per ARB_texture_gather, gathers the four texels to be used in a bi-linear filtering operation and packs them into a single register. Only works with 2D, 2D array, cubemaps, and cubemaps arrays. For 2D textures, only the addressing modes of the sampler and the top level of any mip pyramid are used. Set W to zero. It behaves like the TEX instruction, but a filtered sample is not generated. The four samples that contribute to filtering are placed into xyzw in clockwise order, starting with the (u,v) texture coordinate delta at the following locations (-, +), (+, +), (+, -), (-, -), where the magnitude of the deltas are half a texel.
PIPE_CAP_TEXTURE_SM5 enhances this instruction to support shadow per-sample depth compares, single component selection, and a non-constant offset. It doesn’t allow support for the GL independent offset to get i0,j0. This would require another CAP is hw can do it natively. For now we lower that before TGSI.
(with SM5 - cube array shadow)
Compute the LOD information that the texture pipe would use to access the texture. The Y component contains the computed LOD lambda_prime. The X component contains the LOD that will be accessed, based on min/max lod’s and mipmap filters.
These opcodes are used for integer operations. Support for these opcodes indicated by PIPE_SHADER_CAP_INTEGERS (all of them?)
Rounding is unspecified (round to nearest even suggested).
Rounding is unspecified (round to nearest even suggested).
Rounding is towards zero (truncate). Values outside signed range (including NaNs) produce undefined results.
Rounding is towards zero (truncate). Values outside unsigned range (including NaNs) produce undefined results.
This instruction works the same for signed and unsigned integers. The low 32bit of the result is returned.
This instruction works the same for signed and unsigned integers. The multiplication returns the low 32bit (as does the result itself).
This instruction works the same for signed and unsigned integers. The low 32bit of the result is returned.
The high 32bits of the multiplication of 2 signed integers are returned.
The high 32bits of the multiplication of 2 unsigned integers are returned.
TBD: behavior for division by zero.
For division by zero, 0xffffffff is returned.
If second arg is zero, 0xffffffff is returned.
The shift count is masked with 0x1f before the shift is applied.
The shift count is masked with 0x1f before the shift is applied.
The shift count is masked with 0x1f before the shift is applied.
Same comparison as SLT but returns integer instead of 1.0/0.0 float
Same comparison as SGE but returns integer instead of 1.0/0.0 float
Same comparison as SEQ but returns integer instead of 1.0/0.0 float
Same comparison as SNE but returns integer instead of 1.0/0.0 float
Two’s complement.
These opcodes are used for bit-level manipulation of integers.
See SM5 instruction of the same name. Extracts a set of bits from the input, and sign-extends them if the high bit of the extracted window is set.
Pseudocode:
def ibfe(value, offset, bits):
offset = offset & 0x1f
bits = bits & 0x1f
if bits == 0: return 0
# Note: >> sign-extends
if width + offset < 32:
return (value << (32 - offset - bits)) >> (32 - bits)
else:
return value >> offset
See SM5 instruction of the same name. Extracts a set of bits from the input, without any sign-extension.
Pseudocode:
def ubfe(value, offset, bits):
offset = offset & 0x1f
bits = bits & 0x1f
if bits == 0: return 0
# Note: >> does not sign-extend
if width + offset < 32:
return (value << (32 - offset - bits)) >> (32 - bits)
else:
return value >> offset
See SM5 instruction of the same name. Replaces a bit region of ‘base’ with the low bits of ‘insert’.
Pseudocode:
def bfi(base, insert, offset, bits):
offset = offset & 0x1f
bits = bits & 0x1f
mask = ((1 << bits) - 1) << offset
return ((insert << offset) & mask) | (base & ~mask)
See SM5 instruction BFREV. Reverses the bits of the argument.
See SM5 instruction COUNTBITS. Counts the number of set bits in the argument.
See SM5 instruction FIRSTBIT_LO. Computes the 0-based index of the first set bit of the argument. Returns -1 if none are set.
See SM5 instruction FIRSTBIT_SHI. Computes the 0-based index of the highest non-sign bit of the argument (i.e. highest 0 bit for negative numbers, highest 1 bit for positive numbers). Returns -1 if all bits are the same (i.e. for inputs 0 and -1).
See SM5 instruction FIRSTBIT_HI. Computes the 0-based index of the highest set bit of the argument. Returns -1 if none are set.
These opcodes are only supported in geometry shaders; they have no meaning in any other type of shader.
Generate a new vertex for the current primitive into the specified vertex stream using the values in the output registers.
Complete the current primitive in the specified vertex stream (consisting of the emitted vertices), and start a new one.
These opcodes are part of GLSL‘s opcode set. Support for these opcodes is determined by a special capability bit, GLSL. Some require glsl version 1.30 (UIF/BREAKC/SWITCH/CASE/DEFAULT/ENDSWITCH).
push(pc) pc = target
pc = pop()
Unconditionally moves the point of execution to the instruction after the last bgnloop. The instruction must appear within a bgnloop/endloop.
Note
Support for CONT is determined by a special capability bit, TGSI_CONT_SUPPORTED. See Screen for more information.
Start a loop. Must have a matching endloop.
Starts definition of a subroutine. Must have a matching endsub.
End a loop started with bgnloop.
Ends definition of a subroutine.
Do nothing.
Unconditionally moves the point of execution to the instruction after the next endloop or endswitch. The instruction must appear within a loop/endloop or switch/endswitch.
Conditionally moves the point of execution to the instruction after the next endloop or endswitch. The instruction must appear within a loop/endloop or switch/endswitch. Condition evaluates to true if src0.x != 0 where src0.x is interpreted as an integer register.
Note
Considered for removal as it’s quite inconsistent wrt other opcodes (could emulate with UIF/BRK/ENDIF).
Start an IF ... ELSE .. ENDIF block. Condition evaluates to true if
src0.x != 0.0
where src0.x is interpreted as a floating point register.
Start an UIF ... ELSE .. ENDIF block. Condition evaluates to true if
src0.x != 0
where src0.x is interpreted as an integer register.
Starts an else block, after an IF or UIF statement.
Ends an IF or UIF block.
Starts a C-style switch expression. The switch consists of one or multiple CASE statements, and at most one DEFAULT statement. Execution of a statement ends when a BRK is hit, but just like in C falling through to other cases without a break is allowed. Similarly, DEFAULT label is allowed anywhere not just as last statement, and fallthrough is allowed into/from it. CASE src arguments are evaluated at bit level against the SWITCH src argument.
Example:
SWITCH src[0].x
CASE src[0].x
(some instructions here)
(optional BRK here)
DEFAULT
(some instructions here)
(optional BRK here)
CASE src[0].x
(some instructions here)
(optional BRK here)
ENDSWITCH
This represents a switch case label. The src arg must be an integer immediate.
This represents the default case in the switch, which is taken if no other case matches.
Ends a switch expression.
The interpolation instructions allow an input to be interpolated in a different way than its declaration. This corresponds to the GLSL 4.00 interpolateAt* functions. The first argument of each of these must come from TGSI_FILE_INPUT.
Interpolates the varying specified by src0 at the centroid
Interpolates the varying specified by src0 at the sample id specified by src1.x (interpreted as an integer)
Interpolates the varying specified by src0 at the offset src1.xy from the pixel center (interpreted as floats)
The double-precision opcodes reinterpret four-component vectors into two-component vectors with doubled precision in each component.
Like the frexp() routine in many math libraries, this opcode stores the exponent of its source to dst0, and the significand to dst1, such that .
This opcode is the inverse of DFRACEXP. The second source is an integer.
Perform a * b + c with no intermediate rounding step.
Those opcodes follow very closely semantics of the respective Direct3D instructions. If in doubt double check Direct3D documentation. Note that the swizzle on SVIEW (src1) determines texel swizzling after lookup.
Using provided address, sample data from the specified texture using the filtering mode identified by the gven sampler. The source data may come from any resource type other than buffers.
Syntax: SAMPLE dst, address, sampler_view, sampler
Example: SAMPLE TEMP[0], TEMP[1], SVIEW[0], SAMP[0]
Simplified alternative to the SAMPLE instruction. Using the provided integer address, SAMPLE_I fetches data from the specified sampler view without any filtering. The source data may come from any resource type other than CUBE.
Syntax: SAMPLE_I dst, address, sampler_view
Example: SAMPLE_I TEMP[0], TEMP[1], SVIEW[0]
The ‘address’ is specified as unsigned integers. If the ‘address’ is out of range [0...(# texels - 1)] the result of the fetch is always 0 in all components. As such the instruction doesn’t honor address wrap modes, in cases where that behavior is desirable ‘SAMPLE’ instruction should be used. address.w always provides an unsigned integer mipmap level. If the value is out of the range then the instruction always returns 0 in all components. address.yz are ignored for buffers and 1d textures. address.z is ignored for 1d texture arrays and 2d textures.
For 1D texture arrays address.y provides the array index (also as unsigned integer). If the value is out of the range of available array indices [0... (array size - 1)] then the opcode always returns 0 in all components. For 2D texture arrays address.z provides the array index, otherwise it exhibits the same behavior as in the case for 1D texture arrays. The exact semantics of the source address are presented in the table below:
resource type | X | Y | Z | W |
---|---|---|---|---|
PIPE_BUFFER | x | ignored | ||
PIPE_TEXTURE_1D | x | mpl | ||
PIPE_TEXTURE_2D | x | y | mpl | |
PIPE_TEXTURE_3D | x | y | z | mpl |
PIPE_TEXTURE_RECT | x | y | mpl | |
PIPE_TEXTURE_CUBE | not allowed as source | |||
PIPE_TEXTURE_1D_ARRAY | x | idx | mpl | |
PIPE_TEXTURE_2D_ARRAY | x | y | idx | mpl |
Where ‘mpl’ is a mipmap level and ‘idx’ is the array index.
Just like SAMPLE_I but allows fetch data from multi-sampled surfaces.
Syntax: SAMPLE_I_MS dst, address, sampler_view, sample
Just like the SAMPLE instruction with the exception that an additional bias is applied to the level of detail computed as part of the instruction execution.
Syntax: SAMPLE_B dst, address, sampler_view, sampler, lod_bias
Example: SAMPLE_B TEMP[0], TEMP[1], SVIEW[0], SAMP[0], TEMP[2].x
Similar to the SAMPLE instruction but it performs a comparison filter. The operands to SAMPLE_C are identical to SAMPLE, except that there is an additional float32 operand, reference value, which must be a register with single-component, or a scalar literal. SAMPLE_C makes the hardware use the current samplers compare_func (in pipe_sampler_state) to compare reference value against the red component value for the surce resource at each texel that the currently configured texture filter covers based on the provided coordinates.
Syntax: SAMPLE_C dst, address, sampler_view.r, sampler, ref_value
Example: SAMPLE_C TEMP[0], TEMP[1], SVIEW[0].r, SAMP[0], TEMP[2].x
Same as SAMPLE_C, but LOD is 0 and derivatives are ignored. The LZ stands for level-zero.
Syntax: SAMPLE_C_LZ dst, address, sampler_view.r, sampler, ref_value
Example: SAMPLE_C_LZ TEMP[0], TEMP[1], SVIEW[0].r, SAMP[0], TEMP[2].x
SAMPLE_D is identical to the SAMPLE opcode except that the derivatives for the source address in the x direction and the y direction are provided by extra parameters.
Syntax: SAMPLE_D dst, address, sampler_view, sampler, der_x, der_y
Example: SAMPLE_D TEMP[0], TEMP[1], SVIEW[0], SAMP[0], TEMP[2], TEMP[3]
SAMPLE_L is identical to the SAMPLE opcode except that the LOD is provided directly as a scalar value, representing no anisotropy.
Syntax: SAMPLE_L dst, address, sampler_view, sampler, explicit_lod
Example: SAMPLE_L TEMP[0], TEMP[1], SVIEW[0], SAMP[0], TEMP[2].x
Gathers the four texels to be used in a bi-linear filtering operation and packs them into a single register. Only works with 2D, 2D array, cubemaps, and cubemaps arrays. For 2D textures, only the addressing modes of the sampler and the top level of any mip pyramid are used. Set W to zero. It behaves like the SAMPLE instruction, but a filtered sample is not generated. The four samples that contribute to filtering are placed into xyzw in counter-clockwise order, starting with the (u,v) texture coordinate delta at the following locations (-, +), (+, +), (+, -), (-, -), where the magnitude of the deltas are half a texel.
Query the dimensions of a given sampler view. dst receives width, height, depth or array size and number of mipmap levels as int4. The dst can have a writemask which will specify what info is the caller interested in.
Syntax: SVIEWINFO dst, src_mip_level, sampler_view
Example: SVIEWINFO TEMP[0], TEMP[1].x, SVIEW[0]
src_mip_level is an unsigned integer scalar. If it’s out of range then returns 0 for width, height and depth/array size but the total number of mipmap is still returned correctly for the given sampler view. The returned width, height and depth values are for the mipmap level selected by the src_mip_level and are in the number of texels. For 1d texture array width is in dst.x, array size is in dst.y and dst.z is 0. The number of mipmaps is still in dst.w. In contrast to d3d10 resinfo, there’s no way in the tgsi instruction encoding to specify the return type (float/rcpfloat/uint), hence always using uint. Also, unlike the SAMPLE instructions, the swizzle on src1 resinfo allowing swizzling dst values is ignored (due to the interaction with rcpfloat modifier which requires some swizzle handling in the state tracker anyway).
Query the position of a given sample. dst receives float4 (x, y, 0, 0) indicated where the sample is located. If the resource is not a multi-sample resource and not a render target, the result is 0.
dst receives number of samples in x. If the resource is not a multi-sample resource and not a render target, the result is 0.
Syntax: LOAD dst, resource, address
Example: LOAD TEMP[0], RES[0], TEMP[1]
Using the provided integer address, LOAD fetches data from the specified buffer or texture without any filtering.
The ‘address’ is specified as a vector of unsigned integers. If the ‘address’ is out of range the result is unspecified.
Only the first mipmap level of a resource can be read from using this instruction.
For 1D or 2D texture arrays, the array index is provided as an unsigned integer in address.y or address.z, respectively. address.yz are ignored for buffers and 1D textures. address.z is ignored for 1D texture arrays and 2D textures. address.w is always ignored.
Syntax: STORE resource, address, src
Example: STORE RES[0], TEMP[0], TEMP[1]
Using the provided integer address, STORE writes data to the specified buffer or texture.
The ‘address’ is specified as a vector of unsigned integers. If the ‘address’ is out of range the result is unspecified.
Only the first mipmap level of a resource can be written to using this instruction.
For 1D or 2D texture arrays, the array index is provided as an unsigned integer in address.y or address.z, respectively. address.yz are ignored for buffers and 1D textures. address.z is ignored for 1D texture arrays and 2D textures. address.w is always ignored.
These opcodes are intended for communication between threads running within the same compute grid. For now they’re only valid in compute programs.
Syntax: MFENCE resource
Example: MFENCE RES[0]
This opcode forces strong ordering between any memory access operations that affect the specified resource. This means that previous loads and stores (and only those) will be performed and visible to other threads before the program execution continues.
Syntax: LFENCE resource
Example: LFENCE RES[0]
Similar to MFENCE, but it only affects the ordering of memory loads.
Syntax: SFENCE resource
Example: SFENCE RES[0]
Similar to MFENCE, but it only affects the ordering of memory stores.
BARRIER
This opcode suspends the execution of the current thread until all the remaining threads in the working group reach the same point of the program. Results are unspecified if any of the remaining threads terminates or never reaches an executed BARRIER instruction.
These opcodes provide atomic variants of some common arithmetic and logical operations. In this context atomicity means that another concurrent memory access operation that affects the same memory location is guaranteed to be performed strictly before or after the entire execution of the atomic operation.
For the moment they’re only valid in compute programs.
Syntax: ATOMUADD dst, resource, offset, src
Example: ATOMUADD TEMP[0], RES[0], TEMP[1], TEMP[2]
The following operation is performed atomically on each component:
Syntax: ATOMXCHG dst, resource, offset, src
Example: ATOMXCHG TEMP[0], RES[0], TEMP[1], TEMP[2]
The following operation is performed atomically on each component:
Syntax: ATOMCAS dst, resource, offset, cmp, src
Example: ATOMCAS TEMP[0], RES[0], TEMP[1], TEMP[2], TEMP[3]
The following operation is performed atomically on each component:
Syntax: ATOMAND dst, resource, offset, src
Example: ATOMAND TEMP[0], RES[0], TEMP[1], TEMP[2]
The following operation is performed atomically on each component:
Syntax: ATOMOR dst, resource, offset, src
Example: ATOMOR TEMP[0], RES[0], TEMP[1], TEMP[2]
The following operation is performed atomically on each component:
Syntax: ATOMXOR dst, resource, offset, src
Example: ATOMXOR TEMP[0], RES[0], TEMP[1], TEMP[2]
The following operation is performed atomically on each component:
Syntax: ATOMUMIN dst, resource, offset, src
Example: ATOMUMIN TEMP[0], RES[0], TEMP[1], TEMP[2]
The following operation is performed atomically on each component:
Syntax: ATOMUMAX dst, resource, offset, src
Example: ATOMUMAX TEMP[0], RES[0], TEMP[1], TEMP[2]
The following operation is performed atomically on each component:
Syntax: ATOMIMIN dst, resource, offset, src
Example: ATOMIMIN TEMP[0], RES[0], TEMP[1], TEMP[2]
The following operation is performed atomically on each component:
Syntax: ATOMIMAX dst, resource, offset, src
Example: ATOMIMAX TEMP[0], RES[0], TEMP[1], TEMP[2]
The following operation is performed atomically on each component:
Absolute value of x.
Ceiling of x.
- clamp(x,y,z) Clamp x between y and z.
- (x < y) ? y : (x > z) ? z : x
Floor of x.
Logarithm of x, base 2.
- max(x,y) Maximum of x and y.
- (x > y) ? x : y
- min(x,y) Minimum of x and y.
- (x < y) ? x : y
partialx(x) Derivative of x relative to fragment’s X.
partialy(x) Derivative of x relative to fragment’s Y.
pop() Pop from stack.
x to the power y.
push(x) Push x on stack.
round(x) Round x.
trunc(x) Truncate x, i.e. drop the fraction bits.
discard Discard fragment.
pc Program counter.
target Label of target instruction.
Declares a register that is will be referenced as an operand in Instruction tokens.
File field contains register file that is being declared and is one of TGSI_FILE.
UsageMask field specifies which of the register components can be accessed and is one of TGSI_WRITEMASK.
The Local flag specifies that a given value isn’t intended for subroutine parameter passing and, as a result, the implementation isn’t required to give any guarantees of it being preserved across subroutine boundaries. As it’s merely a compiler hint, the implementation is free to ignore it.
If Dimension flag is set to 1, a Declaration Dimension token follows.
If Semantic flag is set to 1, a Declaration Semantic token follows.
If Interpolate flag is set to 1, a Declaration Interpolate token follows.
If file is TGSI_FILE_RESOURCE, a Declaration Resource token follows.
If Array flag is set to 1, a Declaration Array token follows.
Declarations can optional have an ArrayID attribute which can be referred by indirect addressing operands. An ArrayID of zero is reserved and treaded as if no ArrayID is specified.
If an indirect addressing operand refers to a specific declaration by using an ArrayID only the registers in this declaration are guaranteed to be accessed, accessing any register outside this declaration results in undefined behavior. Note that for compatibility the effective index is zero-based and not relative to the specified declaration
If no ArrayID is specified with an indirect addressing operand the whole register file might be accessed by this operand. This is strongly discouraged and will prevent packing of scalar/vec2 arrays and effective alias analysis.
Vertex and fragment shader input and output registers may be labeled with semantic information consisting of a name and index.
Follows Declaration token if Semantic bit is set.
Since its purpose is to link a shader with other stages of the pipeline, it is valid to follow only those Declaration tokens that declare a register either in INPUT or OUTPUT file.
SemanticName field contains the semantic name of the register being declared. There is no default value.
SemanticIndex is an optional subscript that can be used to distinguish different register declarations with the same semantic name. The default value is 0.
The meanings of the individual semantic names are explained in the following sections.
For vertex shaders, TGSI_SEMANTIC_POSITION indicates the vertex shader output register which contains the homogeneous vertex position in the clip space coordinate system. After clipping, the X, Y and Z components of the vertex will be divided by the W value to get normalized device coordinates.
For fragment shaders, TGSI_SEMANTIC_POSITION is used to indicate that fragment shader input contains the fragment’s window position. The X component starts at zero and always increases from left to right. The Y component starts at zero and always increases but Y=0 may either indicate the top of the window or the bottom depending on the fragment coordinate origin convention (see TGSI_PROPERTY_FS_COORD_ORIGIN). The Z coordinate ranges from 0 to 1 to represent depth from the front to the back of the Z buffer. The W component contains the interpolated reciprocal of the vertex position W component (corresponding to gl_Fragcoord, but unlike d3d10 which interpolates the same 1/w but then gives back the reciprocal of the interpolated value).
Fragment shaders may also declare an output register with TGSI_SEMANTIC_POSITION. Only the Z component is writable. This allows the fragment shader to change the fragment’s Z position.
For vertex shader outputs or fragment shader inputs/outputs, this label indicates that the resister contains an R,G,B,A color.
Several shader inputs/outputs may contain colors so the semantic index is used to distinguish them. For example, color[0] may be the diffuse color while color[1] may be the specular color.
This label is needed so that the flat/smooth shading can be applied to the right interpolants during rasterization.
Back-facing colors are only used for back-facing polygons, and are only valid in vertex shader outputs. After rasterization, all polygons are front-facing and COLOR and BCOLOR end up occupying the same slots in the fragment shader, so all BCOLORs effectively become regular COLORs in the fragment shader.
Vertex shader inputs and outputs and fragment shader inputs may be labeled with TGSI_SEMANTIC_FOG to indicate that the register contains a fog coordinate. Typically, the fragment shader will use the fog coordinate to compute a fog blend factor which is used to blend the normal fragment color with a constant fog color. But fog coord really is just an ordinary vec4 register like regular semantics.
Vertex shader input and output registers may be labeled with TGIS_SEMANTIC_PSIZE to indicate that the register contains a point size in the form (S, 0, 0, 1). The point size controls the width or diameter of points for rasterization. This label cannot be used in fragment shaders.
When using this semantic, be sure to set the appropriate state in the Rasterizer first.
Only available if PIPE_CAP_TGSI_TEXCOORD is exposed !
Vertex shader outputs and fragment shader inputs may be labeled with this semantic to make them replaceable by sprite coordinates via the sprite_coord_enable state in the Rasterizer. The semantic index permitted with this semantic is limited to <= 7.
If the driver does not support TEXCOORD, sprite coordinate replacement applies to inputs with the GENERIC semantic instead.
The intended use case for this semantic is gl_TexCoord.
Only available if PIPE_CAP_TGSI_TEXCOORD is exposed !
Fragment shader inputs may be labeled with TGSI_SEMANTIC_PCOORD to indicate that the register contains sprite coordinates in the form (x, y, 0, 1), if the current primitive is a point and point sprites are enabled. Otherwise, the contents of the register are undefined.
The intended use case for this semantic is gl_PointCoord.
All vertex/fragment shader inputs/outputs not labeled with any other semantic label can be considered to be generic attributes. Typical uses of generic inputs/outputs are texcoords and user-defined values.
Indicates that a vertex shader input is a normal vector. This is typically only used for legacy graphics APIs.
This label applies to fragment shader inputs only and indicates that the register contains front/back-face information of the form (F, 0, 0, 1). The first component will be positive when the fragment belongs to a front-facing polygon, and negative when the fragment belongs to a back-facing polygon.
For vertex shaders, this sematic label indicates that an input or output is a boolean edge flag. The register layout is [F, x, x, x] where F is 0.0 or 1.0 and x = don’t care. Normally, the vertex shader simply copies the edge flag input to the edgeflag output.
Edge flags are used to control which lines or points are actually drawn when the polygon mode converts triangles/quads/polygons into points or lines.
For fragment shaders, this semantic label indicates that an output is a writable stencil reference value. Only the Y component is writable. This allows the fragment shader to change the fragments stencilref value.
For geometry shaders, this semantic label indicates that an output contains the index of the viewport (and scissor) to use. This is an integer value, and only the X component is used.
For geometry shaders, this semantic label indicates that an output contains the layer value to use for the color and depth/stencil surfaces. This is an integer value, and only the X component is used. (Also known as rendertarget array index.)
Used as distance to plane for performing application-defined culling of individual primitives against a plane. When components of vertex elements are given this label, these values are assumed to be a float32 signed distance to a plane. Primitives will be completely discarded if the plane distance for all of the vertices in the primitive are < 0. If a vertex has a cull distance of NaN, that vertex counts as “out” (as if its < 0); The limits on both clip and cull distances are bound by the PIPE_MAX_CLIP_OR_CULL_DISTANCE_COUNT define which defines the maximum number of components that can be used to hold the distances and by the PIPE_MAX_CLIP_OR_CULL_DISTANCE_ELEMENT_COUNT which specifies the maximum number of registers which can be annotated with those semantics.
When components of vertex elements are identified this way, these values are each assumed to be a float32 signed distance to a plane. Primitive setup only invokes rasterization on pixels for which the interpolated plane distances are >= 0. Multiple clip planes can be implemented simultaneously, by annotating multiple components of one or more vertex elements with the above specified semantic. The limits on both clip and cull distances are bound by the PIPE_MAX_CLIP_OR_CULL_DISTANCE_COUNT define which defines the maximum number of components that can be used to hold the distances and by the PIPE_MAX_CLIP_OR_CULL_DISTANCE_ELEMENT_COUNT which specifies the maximum number of registers which can be annotated with those semantics.
For fragment shaders, this semantic label indicates that a system value contains the current sample id (i.e. gl_SampleID). This is an integer value, and only the X component is used.
For fragment shaders, this semantic label indicates that a system value contains the current sample’s position (i.e. gl_SamplePosition). Only the X and Y values are used.
For fragment shaders, this semantic label indicates that an output contains the sample mask used to disable further sample processing (i.e. gl_SampleMask). Only the X value is used, up to 32x MS.
For geometry shaders, this semantic label indicates that a system value contains the current invocation id (i.e. gl_InvocationID). This is an integer value, and only the X component is used.
For vertex shaders, this semantic label indicates that a system value contains the current instance id (i.e. gl_InstanceID). It does not include the base instance. This is an integer value, and only the X component is used.
For vertex shaders, this semantic label indicates that a system value contains the current vertex id (i.e. gl_VertexID). It does (unlike in d3d10) include the base vertex. This is an integer value, and only the X component is used.
For vertex shaders, this semantic label indicates that a system value contains the current vertex id without including the base vertex (this corresponds to d3d10 vertex id, so TGSI_SEMANTIC_VERTEXID_NOBASE + TGSI_SEMANTIC_BASEVERTEX == TGSI_SEMANTIC_VERTEXID). This is an integer value, and only the X component is used.
For vertex shaders, this semantic label indicates that a system value contains the base vertex (i.e. gl_BaseVertex). Note that for non-indexed draw calls, this contains the first (or start) value instead. This is an integer value, and only the X component is used.
For geometry and fragment shaders, this semantic label indicates the value contains the primitive id (i.e. gl_PrimitiveID). This is an integer value, and only the X component is used. FIXME: This right now can be either a ordinary input or a system value...
This token is only valid for fragment shader INPUT declarations.
The Interpolate field specifes the way input is being interpolated by the rasteriser and is one of TGSI_INTERPOLATE_*.
The Location field specifies the location inside the pixel that the interpolation should be done at, one of TGSI_INTERPOLATE_LOC_*. Note that when per-sample shading is enabled, the implementation may choose to interpolate at the sample irrespective of the Location field.
The CylindricalWrap bitfield specifies which register components should be subject to cylindrical wrapping when interpolating by the rasteriser. If TGSI_CYLINDRICAL_WRAP_X is set to 1, the X component should be interpolated according to cylindrical wrapping rules.
Follows Declaration token if file is TGSI_FILE_SAMPLER_VIEW.
DCL SVIEW[#], resource, type(s)
Declares a shader input sampler view and assigns it to a SVIEW[#] register.
resource can be one of BUFFER, 1D, 2D, 3D, 1DArray and 2DArray.
type must be 1 or 4 entries (if specifying on a per-component level) out of UNORM, SNORM, SINT, UINT and FLOAT.
Follows Declaration token if file is TGSI_FILE_RESOURCE.
DCL RES[#], resource [, WR] [, RAW]
Declares a shader input resource and assigns it to a RES[#] register.
resource can be one of BUFFER, 1D, 2D, 3D, CUBE, 1DArray and 2DArray.
If the RAW keyword is not specified, the texture data will be subject to conversion, swizzling and scaling as required to yield the specified data type from the physical data format of the bound resource.
If the RAW keyword is specified, no channel conversion will be performed: the values read for each of the channels (X,Y,Z,W) will correspond to consecutive words in the same order and format they’re found in memory. No element-to-address conversion will be performed either: the value of the provided X coordinate will be interpreted in byte units instead of texel units. The result of accessing a misaligned address is undefined.
Usage of the STORE opcode is only allowed if the WR (writable) flag is set.
Properties are general directives that apply to the whole TGSI program.
Specifies the fragment shader TGSI_SEMANTIC_POSITION coordinate origin. The default value is UPPER_LEFT.
If UPPER_LEFT, the position will be (0,0) at the upper left corner and increase downward and rightward. If LOWER_LEFT, the position will be (0,0) at the lower left corner and increase upward and rightward.
OpenGL defaults to LOWER_LEFT, and is configurable with the GL_ARB_fragment_coord_conventions extension.
DirectX 9/10 use UPPER_LEFT.
Specifies the fragment shader TGSI_SEMANTIC_POSITION pixel center convention. The default value is HALF_INTEGER.
If HALF_INTEGER, the fractionary part of the position will be 0.5 If INTEGER, the fractionary part of the position will be 0.0
Note that this does not affect the set of fragments generated by rasterization, which is instead controlled by half_pixel_center in the rasterizer.
OpenGL defaults to HALF_INTEGER, and is configurable with the GL_ARB_fragment_coord_conventions extension.
DirectX 9 uses INTEGER. DirectX 10 uses HALF_INTEGER.
Specifies that writes to the fragment shader color 0 are replicated to all bound cbufs. This facilitates OpenGL’s fragColor output vs fragData[0] where fragData is directed to a single color buffer, but fragColor is broadcast.
If this property is set on the program bound to the shader stage before the fragment shader, user clip planes should have no effect (be disabled) even if that shader does not write to any clip distance outputs and the rasterizer’s clip_plane_enable is non-zero. This property is only supported by drivers that also support shader clip distance outputs. This is useful for APIs that don’t have UCPs and where clip distances written by a shader cannot be disabled.
Specifies the number of times a geometry shader should be executed for each input primitive. Each invocation will have a different TGSI_SEMANTIC_INVOCATIONID system value set. If not specified, assumed to be 1.
If this property is set on the vertex shader, the TGSI_SEMANTIC_POSITION output is assumed to contain window space coordinates. Division of X,Y,Z by W and the viewport transformation are disabled, and 1/W is directly taken from the 4-th component of the shader output. Naturally, clipping is not performed on window coordinates either. The effect of this property is undefined if a geometry or tessellation shader are in use.
This table shows how texture image components are returned as (x,y,z,w) tuples by TGSI texture instructions, such as TEX, TXD, and TXP. For reference, OpenGL and Direct3D conventions are shown as well.
Texture Components | Gallium | OpenGL | Direct3D 9 |
---|---|---|---|
R | (r, 0, 0, 1) | (r, 0, 0, 1) | (r, 1, 1, 1) |
RG | (r, g, 0, 1) | (r, g, 0, 1) | (r, g, 1, 1) |
RGB | (r, g, b, 1) | (r, g, b, 1) | (r, g, b, 1) |
RGBA | (r, g, b, a) | (r, g, b, a) | (r, g, b, a) |
A | (0, 0, 0, a) | (0, 0, 0, a) | (0, 0, 0, a) |
L | (l, l, l, 1) | (l, l, l, 1) | (l, l, l, 1) |
LA | (l, l, l, a) | (l, l, l, a) | (l, l, l, a) |
I | (i, i, i, i) | (i, i, i, i) | N/A |
UV | XXX TBD | (0, 0, 0, 1) [1] | (u, v, 1, 1) |
Z | XXX TBD | (z, z, z, 1) [2] | (0, z, 0, 1) |
S | (s, s, s, s) | unknown | unknown |
[1] | http://www.opengl.org/registry/specs/ATI/envmap_bumpmap.txt |
[2] | the default is (z, z, z, 1) but may also be (0, 0, 0, z) or (z, z, z, z) depending on the value of GL_DEPTH_TEXTURE_MODE. |
A screen is an object representing the context-independent part of a device.
XXX some of these don’t belong in this section.
Capability queries return information about the features and limits of the driver/GPU. For floating-point values, use get_paramf, and for boolean or integer values, use get_param.
The integer capabilities:
The floating-point capabilities are:
These are per-shader-stage capabitity queries. Different shader stages may support different features.
If a value greater than 0 is returned, the driver can have multiple constant buffers bound to shader stages. The CONST register file can be accessed with two-dimensional indices, like in the example below.
DCL CONST[0][0..7] # declare first 8 vectors of constbuf 0 DCL CONST[3][0] # declare first vector of constbuf 3 MOV OUT[0], CONST[0][3] # copy vector 3 of constbuf 0
For backwards compatibility, one-dimensional access to CONST register file is still supported. In that case, the constbuf index is assumed to be 0.
Compute-specific capabilities. They can be queried using pipe_screen::get_compute_param.
These flags indicate how a resource will be used and are specified at resource creation time. Resources may be used in different roles during their lifecycle. Bind flags are cumulative and may be combined to create a resource which can be used for multiple things. Depending on the pipe driver’s memory management and these bind flags, resources might be created and handled quite differently.
The PIPE_USAGE enums are hints about the expected usage pattern of a resource. Note that drivers must always support read and write CPU access at any time no matter which hint they got.
XXX to-do
Returns an identifying name for the screen.
Returns the screen vendor.
Returns the actual vendor of the device driving the screen (as opposed to the driver vendor).
Create a pipe_context.
priv is private data of the caller, which may be put to various unspecified uses, typically to do with implementing swapbuffers and/or front-buffer rendering.
Determine if a resource in the given format can be used in a specific manner.
format the resource format
target one of the PIPE_TEXTURE_x flags
sample_count the number of samples. 0 and 1 mean no multisampling, the maximum allowed legal value is 32.
bindings is a bitmask of PIPE_BIND_* flags.
geom_flags is a bitmask of PIPE_TEXTURE_GEOM_x flags.
Returns TRUE if all usages can be satisfied.
Check if a resource can actually be created (but don’t actually allocate any memory). This is used to implement OpenGL’s proxy textures. Typically, a driver will simply check if the total size of the given resource is less than some limit.
For PIPE_TEXTURE_CUBE, the pipe_resource::array_size field should be 6.
Create a new resource from a template. The following fields of the pipe_resource must be specified in the template:
target one of the pipe_texture_target enums. Note that PIPE_BUFFER and PIPE_TEXTURE_X are not really fundamentally different. Modern APIs allow using buffers as shader resources.
format one of the pipe_format enums.
width0 the width of the base mip level of the texture or size of the buffer.
height0 the height of the base mip level of the texture (1 for 1D or 1D array textures).
depth0 the depth of the base mip level of the texture (1 for everything else).
array_size the array size for 1D and 2D array textures. For cube maps this must be 6, for other textures 1.
last_level the last mip map level present.
nr_samples the nr of msaa samples. 0 (or 1) specifies a resource which isn’t multisampled.
usage one of the PIPE_USAGE flags.
bind bitmask of the PIPE_BIND flags.
flags bitmask of PIPE_RESOURCE_FLAG flags.
Destroy a resource. A resource is destroyed if it has no more references.
Query a timestamp in nanoseconds. The returned value should match PIPE_QUERY_TIMESTAMP. This function returns immediately and doesn’t wait for rendering to complete (which cannot be achieved with queries).
Return a driver-specific query. If the info parameter is NULL, the number of available queries is returned. Otherwise, the driver query at the specified index is returned in info. The function returns non-zero on success. The driver-specific query is described with the pipe_driver_query_info structure.
Resources represent objects that hold data: textures and buffers.
They are mostly modelled after the resources in Direct3D 10/11, but with a different transfer/update mechanism, and more features for OpenGL support.
Resources can be used in several ways, and it is required to specify all planned uses through an appropriate set of bind flags.
TODO: write much more on resources
Transfers are the mechanism used to access resources with the CPU.
OpenGL: OpenGL supports mapping buffers and has inline transfer functions for both buffers and textures
D3D11: D3D11 lacks transfers, but has special resource types that are mappable to the CPU address space
TODO: write much more on transfers
Resource targets determine the type of a resource.
Note that drivers may not actually have the restrictions listed regarding coordinate normalization and wrap modes, and in fact efficient OpenCL support will probably require drivers that don’t have any of them, which will probably be advertised with an appropriate cap.
TODO: document all targets. Note that both 3D and cube have restrictions that depend on the hardware generation.
Buffer resource: can be used as a vertex, index, constant buffer (appropriate bind flags must be requested).
Buffers do not really have a format, it’s just bytes, but they are required to have their type set to a R8 format (without a specific “just byte” format, R8_UINT would probably make the most sense, but for historic reasons R8_UNORM is ok too). (This is just to make some shared buffer/texture code easier so format size can be queried.) width0 serves as size, most other resource properties don’t apply but must be set appropriately (depth0/height0/array_size must be 1, last_level 0).
They can be bound to stream output if supported. TODO: what about the restrictions lifted by the several later GL transform feedback extensions? How does one advertise that in Gallium?
They can be also be bound to a shader stage (for sampling) as usual by creating an appropriate sampler view, if the driver supports PIPE_CAP_TEXTURE_BUFFER_OBJECTS. This supports larger width than a 1d texture would (TODO limit currently unspecified, minimum must be at least 65536). Only the “direct fetch” sample opcodes are supported (TGSI_OPCODE_TXF, TGSI_OPCODE_SAMPLE_I) so the sampler state (coord wrapping etc.) is mostly ignored (with SAMPLE_I there’s no sampler state at all).
They can be also be bound to the framebuffer (only as color render target, not depth buffer, also there cannot be a depth buffer bound at the same time) as usual by creating an appropriate view (this is not usable in OpenGL). TODO there’s no CAP bit currently for this, there’s also unspecified size etc. limits TODO: is there any chance of supporting GL pixel buffer object acceleration with this?
OpenGL: vertex buffers in GL 1.5 or GL_ARB_vertex_buffer_object
D3D11: buffer resources - Binding to a render target requires D3D_FEATURE_LEVEL_10_0
1D surface accessed with normalized coordinates. 1D array textures are supported depending on PIPE_CAP_MAX_TEXTURE_ARRAY_LAYERS.
width must be a power of two
height0 must be 1
depth0 must be 1
array_size must be 1 for PIPE_TEXTURE_1D
Mipmaps can be used
Must use normalized coordinates
OpenGL: GL_TEXTURE_1D in GL 1.0
D3D11: 1D textures in D3D_FEATURE_LEVEL_10_0
2D surface with OpenGL GL_TEXTURE_RECTANGLE semantics.
OpenGL: GL_TEXTURE_RECTANGLE in GL 3.1 or GL_ARB_texture_rectangle or GL_NV_texture_rectangle
OpenCL: can create OpenCL images based on this, that can then be sampled arbitrarily
D3D11: not supported (only PIPE_TEXTURE_2D with normalized coordinates is supported)
2D surface accessed with normalized coordinates. 2D array textures are supported depending on PIPE_CAP_MAX_TEXTURE_ARRAY_LAYERS.
width and height must be powers of two
depth0 must be 1
array_size must be 1 for PIPE_TEXTURE_2D
Mipmaps can be used
Must use normalized coordinates
No special restrictions on wrap modes
OpenGL: GL_TEXTURE_2D in GL 1.0
OpenCL: can create OpenCL images based on this, that can then be sampled arbitrarily
D3D11: 2D textures
3-dimensional array of texels. Mipmap dimensions are reduced in all 3 coordinates.
width, height and depth must be powers of two
array_size must be 1
Must use normalized coordinates
OpenGL: GL_TEXTURE_3D in GL 1.2 or GL_EXT_texture3D
D3D11: 3D textures
Cube maps consist of 6 2D faces. The 6 surfaces form an imaginary cube, and sampling happens by mapping an input 3-vector to the point of the cube surface in that direction. Cube map arrays are supported depending on PIPE_CAP_CUBE_MAP_ARRAY.
Sampling may be optionally seamless if a driver supports it (PIPE_CAP_SEAMLESS_CUBE_MAP), resulting in filtering taking samples from multiple surfaces near to the edge.
Width and height must be equal
depth0 must be 1
array_size must be a multiple of 6
width and height must be powers of two
Must use normalized coordinates
OpenGL: GL_TEXTURE_CUBE_MAP in GL 1.3 or EXT_texture_cube_map
D3D11: 2D array textures with the D3D11_RESOURCE_MISC_TEXTURECUBE flag
Surfaces are views of a resource that can be bound as a framebuffer to serve as the render target or depth buffer.
TODO: write much more on surfaces
OpenGL: FBOs are collections of surfaces in GL 3.0 or GL_ARB_framebuffer_object
D3D11: render target views and depth/stencil views
Sampler views are views of a resource that can be bound to a pipeline stage to be sampled from shaders.
TODO: write much more on sampler views
OpenGL: texture objects are actually sampler view and resource in a single unit
D3D11: shader resource views
Gallium format names mostly follow D3D10 conventions, with some extensions.
Format names like XnYnZnWn have the X component in the lowest-address n bits and the W component in the highest-address n bits; for B8G8R8A8, byte 0 is blue and byte 3 is alpha. Note that platform endianness is not considered in this definition. In C:
struct x8y8z8w8 { uint8_t x, y, z, w; };
Format aliases like XYZWstrq are (s+t+r+q)-bit integers in host endianness, with the X component in the s least-significant bits of the integer. In C:
uint32_t xyzw8888 = (x << 0) | (y << 8) | (z << 16) | (w << 24);
Format suffixes affect the interpretation of the channel:
The difference between SINT and SSCALED is that the former are pure integers in shaders, while the latter are floats; likewise for UINT versus USCALED.
There are two exceptions for FLOAT. R9G9B9E5_FLOAT is nine bits each of red green and blue mantissa, with a shared five bit exponent. R11G11B10_FLOAT is five bits of exponent and five or six bits of mantissa for each color channel.
For the NORM suffix, the signedness of each channel is indicated with an S or U after the number of channel bits, as in R5SG5SB6U_NORM.
The SRGB suffix is like UNORM in range, but in the sRGB colorspace.
Compressed formats are named first by the compression format string (DXT1, ETC1, etc), followed by a format-specific subtype. Refer to the appropriate compression spec for details.
Formats used in video playback are named by their FOURCC code.
Format names with an embedded underscore are subsampled. R8G8_B8G8 is a single 32-bit block of two pixels, where the R and B values are repeated in both pixels.
DirectX Graphics Infrastructure documentation on DXGI_FORMAT enum: http://msdn.microsoft.com/en-us/library/windows/desktop/bb173059%28v=vs.85%29.aspx
FOURCC codes for YUV formats: http://www.fourcc.org/yuv.php
A Gallium rendering context encapsulates the state which effects 3D rendering such as blend state, depth/stencil state, texture samplers, etc.
Note that resource/texture allocation is not per-context but per-screen.
All Constant State Object (CSO) state is created, bound, and destroyed, with triplets of methods that all follow a specific naming scheme. For example, create_blend_state, bind_blend_state, and destroy_blend_state.
CSO objects handled by the context object:
This state describes how resources in various flavours (textures, buffers, surfaces) are bound to the driver.
These pieces of state are too small, variable, and/or trivial to have CSO objects. They all follow simple, one-method binding calls, e.g. set_blend_color.
These are the means to bind textures to shader stages. To create one, specify its format, swizzle and LOD range in sampler view template.
If texture format is different than template format, it is said the texture is being cast to another format. Casting can be done only between compatible formats, that is formats that have matching component order and sizes.
Swizzle fields specify they way in which fetched texel components are placed in the result register. For example, swizzle_r specifies what is going to be placed in first component of result register.
The first_level and last_level fields of sampler view template specify the LOD range the texture is going to be constrained to. Note that these values are in addition to the respective min_lod, max_lod values in the pipe_sampler_state (that is if min_lod is 2.0, and first_level 3, the first mip level used for sampling from the resource is effectively the fifth).
The first_layer and last_layer fields specify the layer range the texture is going to be constrained to. Similar to the LOD range, this is added to the array index which is used for sampling.
Shader resources are textures or buffers that may be read or written from a shader without an associated sampler. This means that they have no support for floating point coordinates, address wrap modes or filtering.
Shader resources are specified for all the shader stages at once using the set_shader_resources method. When binding texture resources, the level, first_layer and last_layer pipe_surface fields specify the mipmap level and the range of layers the texture will be constrained to. In the case of buffers, first_element and last_element specify the range within the buffer that will be used by the shader resource. Writes to a shader resource are only allowed when the writable flag is set.
These are the means to use resources as color render targets or depthstencil attachments. To create one, specify the mip level, the range of layers, and the bind flags (either PIPE_BIND_DEPTH_STENCIL or PIPE_BIND_RENDER_TARGET). Note that layer values are in addition to what is indicated by the geometry shader output variable XXX_FIXME (that is if first_layer is 3 and geometry shader indicates index 2, the 5th layer of the resource will be used). These first_layer and last_layer parameters will only be used for 1d array, 2d array, cube, and 3d textures otherwise they are 0.
Stream output, also known as transform feedback, allows writing the primitives produced by the vertex pipeline to buffers. This is done after the geometry shader or vertex shader if no geometry shader is present.
The stream output targets are views into buffer resources which can be bound as stream outputs and specify a memory range where it’s valid to write primitives. The pipe driver must implement memory protection such that any primitives written outside of the specified memory range are discarded.
Two stream output targets can use the same resource at the same time, but with a disjoint memory range.
Additionally, the stream output target internally maintains the offset into the buffer which is incremented everytime something is written to it. The internal offset is equal to how much data has already been written. It can be stored in device memory and the CPU actually doesn’t have to query it.
The stream output target can be used in a draw command to provide the vertex count. The vertex count is derived from the internal offset discussed above.
NOTE: The currently-bound vertex or geometry shader must be compiled with the properly-filled-in structure pipe_stream_output_info describing which outputs should be written to buffers and how. The structure is part of pipe_shader_state.
Clear is one of the most difficult concepts to nail down to a single interface (due to both different requirements from APIs and also driver/hw specific differences).
clear initializes some or all of the surfaces currently bound to the framebuffer to particular RGBA, depth, or stencil values. Currently, this does not take into account color or stencil write masks (as used by GL), and always clears the whole surfaces (no scissoring as used by GL clear or explicit rectangles like d3d9 uses). It can, however, also clear only depth or stencil in a combined depth/stencil surface. If a surface includes several layers then all layers will be cleared.
clear_render_target clears a single color rendertarget with the specified color value. While it is only possible to clear one surface at a time (which can include several layers), this surface need not be bound to the framebuffer.
clear_depth_stencil clears a single depth, stencil or depth/stencil surface with the specified depth and stencil values (for combined depth/stencil buffers, is is also possible to only clear one or the other part). While it is only possible to clear one surface at a time (which can include several layers), this surface need not be bound to the framebuffer.
clear_buffer clears a PIPE_BUFFER resource with the specified clear value (which may be multiple bytes in length). Logically this is a memset with a multi-byte element value starting at offset bytes from resource start, going for size bytes. It is guaranteed that size % clear_value_size == 0.
draw_vbo draws a specified primitive. The primitive mode and other properties are described by pipe_draw_info.
The mode, start, and count fields of pipe_draw_info specify the the mode of the primitive and the vertices to be fetched, in the range between start to start``+``count-1, inclusive.
Every instance with instanceID in the range between start_instance and start_instance``+``instance_count-1, inclusive, will be drawn.
If there is an index buffer bound, and indexed field is true, all vertex indices will be looked up in the index buffer.
In indexed draw, min_index and max_index respectively provide a lower and upper bound of the indices contained in the index buffer inside the range between start to start``+``count-1. This allows the driver to determine which subset of vertices will be referenced during te draw call without having to scan the index buffer. Providing a over-estimation of the the true bounds, for example, a min_index and max_index of 0 and 0xffffffff respectively, must give exactly the same rendering, albeit with less performance due to unreferenced vertex buffers being unnecessarily DMA’ed or processed. Providing a underestimation of the true bounds will result in undefined behavior, but should not result in program or system failure.
In case of non-indexed draw, min_index should be set to start and max_index should be set to start``+``count-1.
index_bias is a value added to every vertex index after lookup and before fetching vertex attributes.
When drawing indexed primitives, the primitive restart index can be used to draw disjoint primitive strips. For example, several separate line strips can be drawn by designating a special index value as the restart index. The primitive_restart flag enables/disables this feature. The restart_index field specifies the restart index value.
When primitive restart is in use, array indexes are compared to the restart index before adding the index_bias offset.
If a given vertex element has instance_divisor set to 0, it is said it contains per-vertex data and effective vertex attribute address needs to be recalculated for every index.
attribAddr = stride * index + src_offset
If a given vertex element has instance_divisor set to non-zero, it is said it contains per-instance data and effective vertex attribute address needs to recalculated for every instance_divisor-th instance.
attribAddr = stride * instanceID / instance_divisor + src_offset
In the above formulas, src_offset is taken from the given vertex element and stride is taken from a vertex buffer associated with the given vertex element.
The calculated attribAddr is used as an offset into the vertex buffer to fetch the attribute data.
The value of instanceID can be read in a vertex shader through a system value register declared with INSTANCEID semantic name.
Queries gather some statistic from the 3D pipeline over one or more draws. Queries may be nested, though not all state trackers exercise this.
Queries can be created with create_query and deleted with destroy_query. To start a query, use begin_query, and when finished, use end_query to end the query.
create_query takes a query type (PIPE_QUERY_*), as well as an index, which is the vertex stream for PIPE_QUERY_PRIMITIVES_GENERATED and PIPE_QUERY_PRIMITIVES_EMITTED, and allocates a query structure.
begin_query will clear/reset previous query results.
get_query_result is used to retrieve the results of a query. If the wait parameter is TRUE, then the get_query_result call will block until the results of the query are ready (and TRUE will be returned). Otherwise, if the wait parameter is FALSE, the call will not block and the return value will be TRUE if the query has completed or FALSE otherwise.
The interface currently includes the following types of queries:
PIPE_QUERY_OCCLUSION_COUNTER counts the number of fragments which are written to the framebuffer without being culled by Depth, Stencil, & Alpha testing or shader KILL instructions. The result is an unsigned 64-bit integer. This query can be used with render_condition.
In cases where a boolean result of an occlusion query is enough, PIPE_QUERY_OCCLUSION_PREDICATE should be used. It is just like PIPE_QUERY_OCCLUSION_COUNTER except that the result is a boolean value of FALSE for cases where COUNTER would result in 0 and TRUE for all other cases. This query can be used with render_condition.
PIPE_QUERY_TIME_ELAPSED returns the amount of time, in nanoseconds, the context takes to perform operations. The result is an unsigned 64-bit integer.
PIPE_QUERY_TIMESTAMP returns a device/driver internal timestamp, scaled to nanoseconds, recorded after all commands issued prior to end_query have been processed. This query does not require a call to begin_query. The result is an unsigned 64-bit integer.
PIPE_QUERY_TIMESTAMP_DISJOINT can be used to check the internal timer resolution and whether the timestamp counter has become unreliable due to things like throttling etc. - only if this is FALSE a timestamp query (within the timestamp_disjoint query) should be trusted. The result is a 64-bit integer specifying the timer resolution in Hz, followed by a boolean value indicating whether the timestamp counter is discontinuous or disjoint.
PIPE_QUERY_PRIMITIVES_GENERATED returns a 64-bit integer indicating the number of primitives processed by the pipeline (regardless of whether stream output is active or not).
PIPE_QUERY_PRIMITIVES_EMITTED returns a 64-bit integer indicating the number of primitives written to stream output buffers.
PIPE_QUERY_SO_STATISTICS returns 2 64-bit integers corresponding to the result of PIPE_QUERY_PRIMITIVES_EMITTED and the number of primitives that would have been written to stream output buffers if they had infinite space available (primitives_storage_needed), in this order. XXX the 2nd value is equivalent to PIPE_QUERY_PRIMITIVES_GENERATED but it is unclear if it should be increased if stream output is not active.
PIPE_QUERY_SO_OVERFLOW_PREDICATE returns a boolean value indicating whether the stream output targets have overflowed as a result of the commands issued between begin_query and end_query. This query can be used with render_condition.
PIPE_QUERY_GPU_FINISHED returns a boolean value indicating whether all commands issued before end_query have completed. However, this does not imply serialization. This query does not require a call to begin_query.
PIPE_QUERY_PIPELINE_STATISTICS returns an array of the following 64-bit integers: Number of vertices read from vertex buffers. Number of primitives read from vertex buffers. Number of vertex shader threads launched. Number of geometry shader threads launched. Number of primitives generated by geometry shaders. Number of primitives forwarded to the rasterizer. Number of primitives rasterized. Number of fragment shader threads launched. Number of tessellation control shader threads launched. Number of tessellation evaluation shader threads launched. If a shader type is not supported by the device/driver, the corresponding values should be set to 0.
Gallium does not guarantee the availability of any query types; one must always check the capabilities of the Screen first.
A drawing command can be skipped depending on the outcome of a query (typically an occlusion query, or streamout overflow predicate). The render_condition function specifies the query which should be checked prior to rendering anything. Functions always honoring render_condition include (and are limited to) draw_vbo, clear, clear_render_target, clear_depth_stencil. The blit function (but not resource_copy_region, which seems inconsistent) can also optionally honor the current render condition.
If render_condition is called with query = NULL, conditional rendering is disabled and drawing takes place normally.
If render_condition is called with a non-null query subsequent drawing commands will be predicated on the outcome of the query. Commands will be skipped if condition is equal to the predicate result (for non-boolean queries such as OCCLUSION_QUERY, zero counts as FALSE, non-zero as TRUE).
If mode is PIPE_RENDER_COND_WAIT the driver will wait for the query to complete before deciding whether to render.
If mode is PIPE_RENDER_COND_NO_WAIT and the query has not yet completed, the drawing command will be executed normally. If the query has completed, drawing will be predicated on the outcome of the query.
If mode is PIPE_RENDER_COND_BY_REGION_WAIT or PIPE_RENDER_COND_BY_REGION_NO_WAIT rendering will be predicated as above for the non-REGION modes but in the case that an occlusion query returns a non-zero result, regions which were occluded may be ommitted by subsequent drawing commands. This can result in better performance with some GPUs. Normally, if the occlusion query returned a non-zero result subsequent drawing happens normally so fragments may be generated, shaded and processed even where they’re known to be obscured.
flush
flush_resource
Flush the resource cache, so that the resource can be used by an external client. Possible usage: - flushing a resource before presenting it on the screen - flushing a resource if some other process or device wants to use it This shouldn’t be used to flush caches if the resource is only managed by a single pipe_screen and is not shared with another process. (i.e. you shouldn’t use it to flush caches explicitly if you want to e.g. use the resource for texturing)
is_resource_referenced
These methods emulate classic blitter controls.
These methods operate directly on pipe_resource objects, and stand apart from any 3D state in the context. Blitting functionality may be moved to a separate abstraction at some point in the future.
resource_copy_region blits a region of a resource to a region of another resource, provided that both resources have the same format, or compatible formats, i.e., formats for which copying the bytes from the source resource unmodified to the destination resource will achieve the same effect of a textured quad blitter.. The source and destination may be the same resource, but overlapping blits are not permitted. This can be considered the equivalent of a CPU memcpy.
blit blits a region of a resource to a region of another resource, including scaling, format conversion, and up-/downsampling, as well as a destination clip rectangle (scissors). It can also optionally honor the current render condition (but either way the blit itself never contributes anything to queries currently gathering data). As opposed to manually drawing a textured quad, this lets the pipe driver choose the optimal method for blitting (like using a special 2D engine), and usually offers, for example, accelerated stencil-only copies even where PIPE_CAP_SHADER_STENCIL_EXPORT is not available.
These methods are used to get data to/from a resource.
transfer_map creates a memory mapping and the transfer object associated with it. The returned pointer points to the start of the mapped range according to the box region, not the beginning of the resource. If transfer_map fails, the returned pointer to the buffer memory is NULL, and the pointer to the transfer object remains unchanged (i.e. it can be non-NULL).
transfer_unmap remove the memory mapping for and destroy the transfer object. The pointer into the resource should be considered invalid and discarded.
transfer_inline_write performs a simplified transfer for simple writes. Basically transfer_map, data write, and transfer_unmap all in one.
The box parameter to some of these functions defines a 1D, 2D or 3D region of pixels. This is self-explanatory for 1D, 2D and 3D texture targets.
For PIPE_TEXTURE_1D_ARRAY and PIPE_TEXTURE_2D_ARRAY, the box::z and box::depth fields refer to the array dimension of the texture.
For PIPE_TEXTURE_CUBE, the box:z and box::depth fields refer to the faces of the cube map (z + depth <= 6).
For PIPE_TEXTURE_CUBE_ARRAY, the box:z and box::depth fields refer to both the face and array dimension of the texture (face = z % 6, array = z / 6).
If a transfer was created with FLUSH_EXPLICIT, it will not automatically be flushed on write or unmap. Flushes must be requested with transfer_flush_region. Flush ranges are relative to the mapped range, not the beginning of the resource.
This function flushes all pending writes to the currently-set surfaces and invalidates all read caches of the currently-set samplers.
This function flushes caches according to which of the PIPE_BARRIER_* flags are set.
These flags control the behavior of a transfer object.
A compute program can be defined, bound or destroyed using create_compute_state, bind_compute_state or destroy_compute_state respectively.
Any of the subroutines contained within the compute program can be executed on the device using the launch_grid method. This method will execute as many instances of the program as elements in the specified N-dimensional grid, hopefully in parallel.
The compute program has access to four special resources:
These resources use a byte-based addressing scheme, and they can be accessed from the compute program by means of the LOAD/STORE TGSI opcodes. Additional resources to be accessed using the same opcodes may be specified by the user with the set_compute_resources method.
In addition, normal texture sampling is allowed from the compute program: bind_sampler_states may be used to set up texture samplers for the compute stage and set_sampler_views may be used to bind a number of sampler views to it.
CSO, Constant State Objects, are a core part of Gallium’s API.
CSO work on the principle of reusable state; they are created by filling out a state object with the desired properties, then passing that object to a context. The context returns an opaque context-specific handle which can be bound at any time for the desired effect.
This state controls blending of the final fragments into the target rendering buffers.
The blend factors largely follow the same pattern as their counterparts in other modern and legacy drawing APIs.
Dual source blend factors are supported for up to 1 MRT, although you can advertise > 1 MRT, the stack cannot handle them for a few reasons. There is no definition on how the 1D array of shader outputs should be mapped to something that would be a 2D array (location, index). No current hardware exposes > 1 MRT, and we should revisit this issue if anyone ever does.
Logical operations, also known as logicops, lops, or rops, are supported. Only two-operand logicops are available. When logicops are enabled, all other blend state is ignored, including per-render-target state, so logicops are performed on all render targets.
Warning
The blend_enable flag is ignored for all render targets when logical operations are enabled.
For a source component s and destination component d, the logical operations are defined as taking the bits of each channel of each component, and performing one of the following operations per-channel:
Note
The logical operation names and definitions match those of the OpenGL API, and are similar to the ROP2 and ROP3 definitions of GDI. This is intentional, to ease transitions to Gallium.
These members affect all render targets.
Whether dithering is enabled.
Note
Dithering is completely implementation-dependent. It may be ignored by drivers for any reason, and some render targets may always or never be dithered depending on their format or usage flags.
Whether the blender should perform a logicop instead of blending.
The logicop to use. One of PIPE_LOGICOP.
These three states control the depth, stencil, and alpha tests, used to discard fragments that have passed through the fragment shader.
Traditionally, these three tests have been clumped together in hardware, so they are all stored in one structure.
During actual execution, the order of operations done on fragments is always:
The rasterizer state controls the rendering of points, lines and triangles. Attributes include polygon culling state, line width, line stipple, multisample state, scissoring and flat/smooth shading.
Linkage
If set, TGSI_SEMANTIC_COLOR registers are clamped to the [0, 1] range after the execution of the vertex shader, before being passed to the geometry shader or fragment shader.
OpenGL: glClampColor(GL_CLAMP_VERTEX_COLOR) in GL 3.0 or GL_ARB_color_buffer_float
D3D11: seems always disabled
Note the PIPE_CAP_VERTEX_COLOR_CLAMPED query indicates whether or not the driver supports this control. If it’s not supported, the state tracker may have to insert extra clamping code.
Controls whether TGSI_SEMANTIC_COLOR outputs of the fragment shader are clamped to [0, 1].
OpenGL: glClampColor(GL_CLAMP_FRAGMENT_COLOR) in GL 3.0 or ARB_color_buffer_float
D3D11: seems always disabled
Note the PIPE_CAP_FRAGMENT_COLOR_CLAMPED query indicates whether or not the driver supports this control. If it’s not supported, the state tracker may have to insert extra clamping code.
If set, the provoking vertex of each polygon is used to determine the color of the entire polygon. If not set, fragment colors will be interpolated between the vertex colors.
The actual interpolated shading algorithm is obviously implementation-dependent, but will usually be Gourard for most hardware.
Note
This is separate from the fragment shader input attributes CONSTANT, LINEAR and PERSPECTIVE. The flatshade state is needed at clipping time to determine how to set the color of new vertices.
Draw can implement flat shading by copying the provoking vertex color to all the other vertices in the primitive.
Whether the first vertex should be the provoking vertex, for most primitives. If not set, the last vertex is the provoking vertex.
There are a few important exceptions to the specification of this rule.
If set, there are per-vertex back-facing colors. The hardware (perhaps assisted by Draw) should be set up to use this state along with the front/back information to set the final vertex colors prior to rasterization.
The frontface vertex shader color output is marked with TGSI semantic COLOR[0], and backface COLOR[1].
The effect of this state depends on PIPE_CAP_TGSI_TEXCOORD !
Controls automatic texture coordinate generation for rendering sprite points.
If PIPE_CAP_TGSI_TEXCOORD is false: When bit k in the sprite_coord_enable bitfield is set, then generic input k to the fragment shader will get an automatically computed texture coordinate.
If PIPE_CAP_TGSI_TEXCOORD is true: The bitfield refers to inputs with TEXCOORD semantic instead of generic inputs.
The texture coordinate will be of the form (s, t, 0, 1) where s varies from 0 to 1 from left to right while t varies from 0 to 1 according to the state of ‘sprite_coord_mode’ (see below).
If any bit is set, then point_smooth MUST be disabled (there are no round sprites) and point_quad_rasterization MUST be true (sprites are always rasterized as quads). Any mismatch between these states should be considered a bug in the state-tracker.
This feature is implemented in the Draw module but may also be implemented natively by GPUs or implemented with a geometry shader.
Specifies how the value for each shader output should be computed when drawing point sprites. For PIPE_SPRITE_COORD_LOWER_LEFT, the lower-left vertex will have coordinates (0,0,0,1). For PIPE_SPRITE_COORD_UPPER_LEFT, the upper-left vertex will have coordinates (0,0,0,1). This state is used by Draw to generate texcoords.
Determines if points should be rasterized according to quad or point rasterization rules.
(Legacy-only) OpenGL actually has quite different rasterization rules for points and point sprites - hence this indicates if points should be rasterized as points or according to point sprite (which decomposes them into quads, basically) rules. Newer GL versions no longer support the old point rules at all.
Additionally Direct3D will always use quad rasterization rules for points, regardless of whether point sprites are enabled or not.
If this state is enabled, point smoothing and antialiasing are disabled. If it is disabled, point sprite coordinates are not generated.
Note
Some renderers always internally translate points into quads; this state still affects those renderers by overriding other rasterization state.
When true, the rasterizer should use (0.5, 0.5) pixel centers for determining pixel ownership (e.g, OpenGL, D3D10 and higher):
0 0.5 1
0 +-----+
| |
0.5 | X |
| |
1 +-----+
When false, the rasterizer should use (0, 0) pixel centers for determining pixel ownership (e.g., D3D9 or ealier):
-0.5 0 0.5
-0.5 +-----+
| |
0 | X |
| |
0.5 +-----+
Determines what happens when a pixel sample lies precisely on a triangle edge.
When true, a pixel sample is considered to lie inside of a triangle if it lies on the bottom edge or left edge (e.g., OpenGL drawables):
0 x
0 +--------------------->
|
| +-------------+
| | |
| | |
| | |
| +=============+
|
y V
When false, a pixel sample is considered to lie inside of a triangle if it lies on the top edge or left edge (e.g., OpenGL FBOs, D3D):
0 x
0 +--------------------->
|
| +=============+
| | |
| | |
| | |
| +-------------+
|
y V
Note
Actually all graphics APIs use a top-left rasterization rule for pixel ownership, but their notion of top varies with the axis origin (which can be either at y = 0 or at y = height). Gallium instead always assumes that top is always at y=0.
Texture units have many options for selecting texels from loaded textures; this state controls an individual texture unit’s texel-sampling settings.
Texture coordinates are always treated as four-dimensional, and referred to with the traditional (S, T, R, Q) notation.
The wrap modes are:
The texture image filter modes are:
The texture mip filter modes are:
One of the two types of shaders supported by Gallium.
This state controls the format of the input attributes contained in pipe_vertex_buffers. There is one pipe_vertex_element array member for each input attribute.
Gallium supports a diverse range of formats for vertex data. Drivers are guaranteed to support 32-bit floating-point vectors of one to four components. Additionally, they may support the following formats:
At this time, support for varied vertex data formats is limited by driver deficiencies. It is planned to support a single uniform set of formats for all Gallium drivers at some point.
Rather than attempt to specify every small nuance of behavior, Gallium uses a very simple set of rules for padding out unspecified components. If an input uses less than four components, it will be padded out with the constant vector (0, 0, 0, 1).
Fog, point size, the facing bit, and edgeflags, all are in the standard format of (x, 0, 0, 1), and so only the first component of those inputs is used.
Vertex position may be specified with two to four components. Using less than two components is not allowed.
Colors, both front- and back-facing, may omit the alpha component, only using three components. Using less than three components is not allowed.
Along with the interface definitions, the following drivers, state trackers, and auxiliary modules are shipped in the standard Gallium distribution.
Driver for Intel i915 and i945 chipsets.
A version of Softpipe that uses the Low-Level Virtual Machine to dynamically generate optimized rasterizing pipelines.
Driver for the nVidia nv30 and nv40 families of GPUs.
Driver for the nVidia nv50 family of GPUs.
Driver for the nVidia nvc0 / fermi family of GPUs.
Driver for VMware virtualized guest operating system graphics processing.
Driver for the ATI/AMD r300, r400, and r500 families of GPUs.
Driver for the ATI/AMD r600, r700, Evergreen and Northern Islands families of GPUs.
Driver for the AMD Southern Islands family of GPUs.
Driver for Qualcomm Adreno a2xx, a3xx, and a4xx series of GPUs.
Reference software rasterizer. Slow but accurate.
Wrapper driver. Trace dumps an XML record of the calls made to the Context and Screen objects that it wraps.
Wrapper driver. Remote Debugger driver used with stand alone rbug-gui.
Tracker that implements the Khronos OpenCL standard.
Tracker that implements the client-side DRI protocol, for providing direct acceleration services to X11 servers with the DRI extension. Supports DRI1 and DRI2. Only GL is supported.
Tracker implementing a GL state machine. Not usable as a standalone tracker; Mesa should be built with another state tracker, such as Direct Rendering Infrastructure or EGL.
Tracker for Video Decode and Presentation API for Unix.
Tracker for Xorg X11 servers. Provides device-dependent modesetting and acceleration as a DDX driver.
Tracker for X-Video Motion Compensation.
The OS module contains the abstractions for basic operating system services:
This is the bare minimum required to port Gallium to a new platform.
The OS module already provides the implementations of these abstractions for the most common platforms. When targeting an embedded platform no implementation will be provided – these must be provided separately.
The CSO cache is used to accelerate preparation of state by saving driver-specific state structures for later use.
Draw is a software TCL pipeline for hardware that lacks vertex shaders or other essential parts of pre-rasterization vertex preparation.
Indices provides tools for translating or generating element indices for use with element-based rendering.
Each of these managers provides various services to drivers that are not fully utilizing a memory manager.
The TGSI auxiliary module provides basic utilities for manipulating TGSI streams.
Driver specific documentation.
Freedreno driver specific docs.
Some notes about ir3, the compiler and machine-specific IR for the shader ISA introduced with adreno a3xx. The same shader ISA is present, with some small differences, in adreno a4xx.
Compared to the previous generation a2xx ISA (ir2), the a3xx ISA is a “simple” scalar instruction set. However, the compiler is responsible, in most cases, to schedule the instructions. The hardware does not try to hide the shader core pipeline stages. For a common example, a common (cat2) ALU instruction takes four cycles, so a subsequent cat2 instruction which uses the result must have three intervening instructions (or nops). When operating on vec4’s, typically the corresponding scalar instructions for operating on the remaining three components could typically fit. Although that results in a lot of edge cases where things fall over, like:
ADD TEMP[0], TEMP[1], TEMP[2]
MUL TEMP[0], TEMP[1], TEMP[0].wzyx
Here, the second instruction needs the output of the first group of scalar instructions in the wrong order, resulting in not enough instruction spots between the add r0.w, r1.w, r2.w and mul r0.x, r1.x, r0.w. Which is why the original (old) compiler which merely translated nearly literally from TGSI to ir3, had a strong tendency to fall over.
So the current compiler instead, in the frontend, generates a directed-acyclic-graph of instructions and basic blocks, which go through various additional passes to eventually schedule and do register assignment.
For additional documentation about the hardware, see wiki: a3xx ISA.
The ir3 IR maps quite directly to the hardware, in that instruction opcodes map directly to hardware opcodes, and that dst/src register(s) map directly to the hardware dst/src register(s). But there are a few extensions, in the form of meta instructions. And additionally, for normal (non-const, etc) src registers, the IR3_REG_SSA flag is set and reg->instr points to the source instruction which produced that value. So, for example, the following TGSI shader:
VERT
DCL IN[0]
DCL IN[1]
DCL OUT[0], POSITION
DCL TEMP[0], LOCAL
1: DP3 TEMP[0].x, IN[0].xyzz, IN[1].xyzz
2: MOV OUT[0], TEMP[0].xxxx
3: END
eventually generates:
(after scheduling, etc, but before register assignment).
Represents a basic block.
TODO: currently blocks are nested, but I think I need to change that to a more conventional arrangement before implementing proper flow control. Currently the only flow control handles is if/else which gets flattened out and results chosen with sel instructions.
In addition there are various util macros/functions to simplify manipulation/traversal of the graph:
For example:
foreach_ssa_src_n(src, i, instr) {
unsigned d = delay_calc_srcn(ctx, src, instr, i);
delay = MAX2(delay, d);
}
TODO probably other helper/util stuff worth mentioning here
TODO
Certain instructions, such as texture sample instructions, consume multiple consecutive scalar registers via a single src register encoded in the instruction, and/or write multiple consecutive scalar registers. In the simplest example:
sam (f32)(xyz)r2.x, r0.z, s#0, t#0
for a 2d texture, would read r0.zw to get the coordinate, and write r2.xyz.
Before register assignment, to group the two components of the texture src together:
The frontend sets up the SSA ptrs from sam source register to the fanin meta instruction, which in turn points to the instructions producing the coord.x and coord.y values. And the grouping pass sets up the left and right neighbor pointers to the fanin‘s sources, used later by the register assignment pass to assign blocks of scalar registers.
And likewise, for the consecutive scalar registers for the destination:
Most instructions support addressing indirectly (relative to address register) into const or gpr register file in some or all of their src/dst registers. In this case the register accessed is taken from r<a0.x + n> or c<a0.x + n>, ie. address register (a0.x) value plus n, where n is encoded in the instruction (rather than the absolute register number).
Note that cat5 (texture sample) instructions are the notable exception, not supporting relative addressing of src or dst.
Relative addressing of the const file (for example, a uniform array) is relatively simple. We don’t do register assignment of the const file, so all that is required is to schedule things properly. Ie. the instruction that writes the address register must be scheduled first, and we cannot have two different address register values live at one time.
But relative addressing of gpr file (which can be as src or dst) has additional restrictions on register assignment (ie. the array elements must be assigned to consecutive scalar registers). And in the case of relative dst, subsequent instructions now depend on both the relative write, as well as the previous instruction which wrote that register, since we do not know at compile time which actual register was written.
Each instruction has an optional address pointer, to capture the dependency on the address register value when relative addressing is used for any of the src/dst register(s). This behaves as an additional virtual src register, ie. foreach_ssa_src() will also iterate the address register (last).
Note that nop‘s for timing constraints, type specifiers (ie. add.f vs add.u), etc, omitted for brevity in examples
mova a0.x, hr1.y
sub r1.y, r2.x, r3.x
add r0.x, r1.y, c<a0.x + 2>
results in:
The scheduling pass has some smarts to schedule things such that only a single a0.x value is used at any one time.
To implement variable arrays, values are stored in consecutive scalar registers. This has some overlap with register groups, in that fanin and fanout are used to help group things for the register assignment pass.
To use a variable array as a src register, a slight variation of what is done for const array src. The instruction src is a fanin instruction that groups all the array members:
mova a0.x, hr1.y
sub r1.y, r2.x, r3.x
add r0.x, r1.y, r<a0.x + 2>
results in:
TODO better describe how actual deref offset is derived, ie. based on array base register.
To do an indirect write to a variable array, a fanout is used. Say the array was assigned to registers r0.z through r1.y (hence the constant offset of 2):
Note that only cat1 (mov) can do indirect write.
mova a0.x, hr1.y
min r2.x, r2.x, c0.x
mov r<a0.x + 2>, r2.x
mul r0.x, r0.z, c0.z
In this case, the mov instruction does not write all elements of the array (compared to usage of fanout for sam instructions in grouping). But the mov instruction does need an additional dependency (via fanin) on instructions that last wrote the array element members, to ensure that they get scheduled before the mov in scheduling stage (which also serves to group the array elements for the register assignment stage).
Note that there would in fact be fanout nodes generated for each array element (although only the reachable ones will be scheduled, etc).
After the frontend has generated the use-def graph of instructions, they are run through various passes which include scheduling and register assignment. Because inserting mov instructions after scheduling would also require inserting additional nop instructions (since it is too late to reschedule to try and fill the bubbles), the earlier stages try to ensure that (at least given an infinite supply of registers) that register assignment after scheduling cannot fail.
Note that we essentially have ~256 scalar registers in the architecture (although larger register usage will at some thresholds limit the number of threads which can run in parallel). And at some point we will have to deal with spilling.
In this stage, simple if/else blocks are flattened into a single block with phi nodes converted into sel instructions. The a3xx ISA has very few predicated instructions, and we would prefer not to use branches for simple if/else.
Currently the frontend inserts movs in various cases, because certain categories of instructions have limitations about const regs as sources. And the CP pass simply removes all simple movs (ie. src-type is same as dst-type, no abs/neg flags, etc).
The eventual plan is to invert that, with the front-end inserting no movs and CP legalize things.
In the grouping pass, instructions which need to be grouped (for fanins, etc) have their left / right neighbor pointers setup. In cases where there is a conflict (ie. one instruction cannot have two unique left or right neighbors), an additional mov instruction is inserted. This ensures that there is some possible valid register assignment at the later stages.
In the depth pass, a depth is calculated for each instruction node within it’s basic block. The depth is the sum of the required cycles (delay slots needed between two instructions plus one) of each instruction plus the max depth of any of it’s source instructions. (meta instructions don’t add to the depth). As an instruction’s depth is calculated, it is inserted into a per block list sorted by deepest instruction. Unreachable instructions and inputs are marked.
TODO: we should probably calculate both hard and soft depths (?) to try to coax additional instructions to fit in places where we need to use sync bits, such as after a texture fetch or SFU.
After the grouping pass, there are no more instructions to insert or remove. Start scheduling each basic block from the deepest node in the depth sorted list created by the depth pass, recursively trying to schedule each instruction after it’s source instructions plus delay slots. Insert nops as required.
TODO