vk

59 definitions in 20 files, 0 with an encoding diagram. src/isa/vk

Files

FileDefinitionsOtherWhat
package.lisp00the ISA.VK package: host target Vulkan, described as an ISA.
registry.lisp017the Vulkan registry as compile-time tables.
gen/enums.lisp00Vulkan API constants, enums and bitmasks (generated, do not edit).
gen/types.lisp00Vulkan base types, handles, flags and function pointers (generated, do not edit).
gen/structs.lisp00Vulkan structs and unions (generated, do not edit).
gen/cmds.lisp00Vulkan commands (generated, do not edit).
gen/dynstate.lisp00Vulkan dynamic states and the commands that set them (generated, do not edit).
limits.lisp09Vulkan limits, features and extensions as build-time constants.
gen/limits.lisp00the Vulkan spec's required limits and features (generated, do not edit).
gen/formats.lisp00Vulkan format descriptions (generated, do not edit).
format.lisp08Vulkan's formats as core texel formats, and every guest format lowered to them.
layout.lisp02host ABI sizes, alignments and member offsets of Vulkan types.
arena.lisp011Vulkan structs in a byte buffer, by their host layout.
defvk.lisp011Vulkan as an ISA: DEFVK, the reference model, canonical enumerations.
sem.lisp570Vulkan command semantics: effects on the abstract graphics state.
pipe.lisp24graphics pipelines: the state a pipeline bakes in, and binding it.
cost.lisp010what Vulkan commands cost, and the cheapest way to make a state change.
host.lisp010Vulkan commands as host interfaces (resolute vulkan).
emit.lisp019the run-time emitter: abstract state -> Vulkan structs and calls.
sampler.lisp011samplers, image views and pushed texture descriptors from the abstract state.

README

src/isa/vk: Vulkan, described as an ISA

The RSX is translated the way the guest CPUs are: as a match problem (docs/isel.md). Here the host side is Vulkan, treated as an instruction set. Each Vulkan command (vkCmdSetViewport, vkCmdBindPipeline, vkCreateGraphicsPipelines, ...) is an instruction, and its operands are its parameters and the structs they point to. Vulkan is never emulated. Its description is there so that ctil can match an RSX state change (an NV4097 method) against the cheapest Vulkan commands with the same effect, and so that the emitter can issue those commands at run time.

Both sides describe their effects on one abstract graphics state (src/core/gfx.lisp). The RSX description will state each NV4097 method's effect on the same state.

FileRole
gen/enums.lisp, gen/types.lisp, gen/structs.lisp, gen/cmds.lisp, gen/dynstate.lispGenerated from registry/vk.xml by tools/vkgen. They hold the API constants, enums and bitmasks, the types and handles, the structs and unions, the commands, and the registry's dynamic states
registry.lispThe compile-time tables behind the generated forms, plus vk-value
gen/limits.lisp, limits.lispThe spec's required limits and features (generated from Vulkan-Profiles by tools/vkgen/limits.cmake), and the build's values: vk-limit, vk-feature, vk-extension (see "Limits")
layout.lispHost (LP64) sizes, alignments and offsets: vk-sizeof, vk-offsetof, vk-layout
../../core/gfx.lispThe abstract graphics state: defgfxstate, defgfxenum, gs, events (in the core, shared with the RSX)
arena.lispVulkan structs in a byte buffer: vk-alloc, vk-set, vk-read, vk-elt
defvk.lispdefvk, the reference model, the canonical and Vulkan enumeration maps, dynamic-state bits
sem.lispCommand semantics: dynamic state, binds, rendering, draws, clears
pipe.lispThe state a pipeline bakes in (vkCreateGraphicsPipelines), and binding it
cost.lispCost classes, the cost hook, and vk-state-change-plan
host.lispCommands as defhosts for the vulkan resolute, and the reference trace
emit.lispThe run-time emitter (static subset): canonical state to structs and calls
gen/formats.lisp, format.lispThe registry's format descriptions as core texel formats; every guest format lowered per use by derivation (docs/texfmt.md)
sampler.lispSamplers, image views and pushed texture descriptors from the abstract state

Registry (generated)

(vk-enum "VkCompareOp" ("VK_COMPARE_OP_NEVER" 0) ("VK_COMPARE_OP_LESS" 1) ...)
(vk-bitmask "VkCullModeFlagBits" 32 ("VK_CULL_MODE_NONE" 0) ("VK_CULL_MODE_FRONT_BIT" #x1) ...)
(vk-handle "VkBuffer" :non-dispatchable "VkDevice")
(vk-struct "VkPipelineRasterizationStateCreateInfo"
    (:stype "VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO" :in "VK_GRAPHICS_VERSION_1_0")
  ("sType" "VkStructureType")
  ("pNext" "void" :const :ptr 1 :optional) ...)
(vk-command "vkCmdSetViewport" "void" (:in "VK_GRAPHICS_VERSION_1_0" :queues "VK_QUEUE_GRAPHICS_BIT"
                                       :pass "both" :levels "primary,secondary" :tasks "state")
  ("commandBuffer" "VkCommandBuffer" :sync) ("firstViewport" "uint32_t") ("viewportCount" "uint32_t")
  ("pViewports" "VkViewport" :const :ptr 1 :len "viewportCount"))
(vk-dynamic-state "viewport" (:substate "Pre-Rasterization Shader")
  ("vkCmdSetViewport" "VK_DYNAMIC_STATE_VIEWPORT" :pipeline-only)
  ("vkCmdSetViewportWithCount" "VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT"))

The selection is Vulkan 1.0 to 1.3 core, from the registry's VK_{BASE_,COMPUTE_,GRAPHICS_,}VERSION_1_x features. It also takes the extensions listed in vkgen.c: surface, swapchain, dynamic rendering, synchronization2, push descriptors, maintenance5, line rasterization, uint8 indices, extended dynamic state 1, 2 and 3, vertex input dynamic state, colour write enable, depth clip enable, provoking vertex, custom border colour, primitive restart index, descriptor buffer, and debug utils. The selection is closed over the types that members and parameters name. :in records the feature or extension that brought an entry in. A value that an extension aliases but that only a later core version defines is written under both names. The selection has 339 structs, 3 unions, 128 enums, 277 commands and 41 dynamic states.

Names are the registry's. They are looked up ignoring case and hyphens, so VkViewport, 'vkCmdDraw and :min-depth all work. (vk-value VK_COMPARE_OP_LESS) gives 1, and several names are ORed together. Do not edit gen/. Configure with -DXSPE_REGEN=ON and build vk_gen instead. vk_gen_fresh checks the committed files against a fresh run. The registry is cached offline with CPM_SOURCE_CACHE=$HOME/ScarletNX/.cache/cpm.

Layout rule (layout.lisp)

The host ABI is LP64. C scalars are their natural size, which is also their alignment. Pointers, function pointers and every handle take 8 bytes. On 64-bit targets, a non-dispatchable handle is a pointer too. Enums take 4 bytes. Flags take their width, 4 or 8 bytes. Struct members are naturally aligned, and a struct is padded to its alignment. A union is as large as its largest member. Bit-fields share their declared type's unit while they fit. vk_layout checks every struct and union against cc and the real vulkan.h, with 2508 checks on sizeof, _Alignof and offsetof.

The abstract graphics state (src/core/gfx.lisp)

(setf (gs depth test) 1)                ; field of a group
(setf (gs viewport 0 min-depth) 0.0)    ; field of element i of an indexed group
(setf (gs viewport count) 1)            ; how many elements are in use
(gfx-ref other-state depth compare)     ; the same on an explicit state
(gfx-code compare-op less-or-equal)     ; a canonical enumerant: 3

gs reads the variable gfx. The state is one struct of arrays (gfx), generated from the table below.

GroupFields
primitivetopology restart restart-index patch-points
programvertex fragment (shader identities)
vertex-binding[16] + countstride input-rate divisor
vertex-attribute[16] (by location)enable binding format offset
viewport[16] + countx y width height min-depth max-depth
scissor[16] + countx y width height
rasterdiscard depth-clamp depth-clip cull-mode front-face polygon-mode-front polygon-mode-back line-width provoking-vertex line-stipple line-stipple-factor line-stipple-pattern
depth-biasenable constant clamp slope
depthtest write compare bounds-test bounds-min bounds-max
stenciltest
stencil-face[2] (0 front, 1 back)fail-op pass-op depth-fail-op compare compare-mask write-mask reference
multisamplesamples sample-mask alpha-to-coverage alpha-to-one
blend[8] + count (by colour attachment)enable src-color dst-color color-op src-alpha dst-alpha alpha-op write-mask (bits R G B A) write-enable
blend-constantr g b a
logic-openable op
color-target[8] + count, depth-targetformat; format stencil-format
bindings: attachment[8], depth-attachment, pass, pipeline, vertex-buffer[16], index, descriptor-set[8]views; active and the area and layers; handle; buffer offset size (type)
events: draw, clearserial plus the last event's parameters

Group options mark which fields are bindings, which are events, and which pipeline part holds a field. The parts follow Vulkan's pipeline-library split. Enumerations are canonical and are numbered from 0 by defgfxenum. Where Vulkan has a concept, the names are its own, in its order, so the map from Vulkan is the identity. Concepts that only the RSX has, such as quad-list and polygon, come after. index-type (uint16, uint32, uint8) shows a non-identity map. vk->gfx and gfx->vk are derived from the registry by name (define-vk-enum). Formats are canonical codes: a VkFormat value, or a guest format's code that format.lisp lowers (docs/texfmt.md).

The RSX side writes the same fields. Some of them are deliberately finer than Vulkan: separate front and back polygon modes, and a programmable restart index. A field that Vulkan cannot express on its own then needs another route, such as a pipeline, an extension, or a fallback.

The description form: defvk

(defvk vkCmdSetViewport (first count viewports)
  (dotimes (i count)
    (let ((v (+ first i)))
      (setf (gs viewport v x) (vk-in viewports i :x)
            ...
            (gs viewport v max-depth) (vk-in viewports i :max-depth)))))

(defvk vkCmdSetStencilOp (faces fail pass depth-fail compare)
  (dotimes (f 2)
    (when (logbitp f faces)
      (setf (gs stencil-face f fail-op) (vk->gfx stencil-op fail) ...))))

(defvk vkCmdDraw (vertex-count instance-count first-vertex first-instance)
  (gfx-draw gfx (gfx-code draw-kind direct) vertex-count instance-count first-vertex 0 first-instance))

Pipelines (pipe.lisp): vkCreateGraphicsPipelines bakes a full snapshot from the create info and its pNext chains. Those chains are depth clip, provoking vertex, line state, colour write, and the formats of dynamic rendering. The snapshot also records the enabled dynamic states as bits. vkCmdBindPipeline copies every non-binding field that no enabled dynamic state covers. Which fields a dynamic state covers is derived: they are the fields that the defvk of its command assigns, with the command taken from the registry's <dynamicstates>. No table of them is written by hand.

Costs (cost.lisp)

ClassCostCommands
:dynamic1commands of a dynamic state (vkCmdSet*)
:bind2vkCmdBind* (vertex, index, descriptor sets)
:draw4actions: draws, clears
:pipeline25vkCmdBindPipeline
:pass60begin and end rendering or render pass
:create100000vkCreate*Pipelines

The class comes from (:cost ...) or from the registry. *vk-cost-hook* (command class default) overrides the cost per driver. (vk-state-change-plan fields :dynamic states :pipeline-cached t) is the decision the RSX translation makes. Given the fields that change and the dynamic states of the bound pipeline, it returns the cheapest commands that make the change. If a baked field is not covered, it returns a pipeline :switch instead, or a :create when no cached pipeline has the new state.

(vk-state-change-plan '((depth test) (raster cull-mode))
                      :dynamic '("VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE"))
;; => (:COST 26 :COMMANDS ("vkCmdSetDepthTestEnable") :PIPELINE :SWITCH
;;     :PASS NIL :SHADER-KEY NIL :DATA NIL)

Where a changed field goes:

OutcomeFields
:commandsa dynamic-state command the bound pipeline enables; a binding command; a state command outside every dynamic state (vkCmdSetPrimitiveRestartIndexEXT) when it is in :commands (the device's extensions)
:pass :restartfields only vkCmdBeginRendering sets (attachments, render area): end the rendering and begin it again (two :pass costs)
:pipelinefields pipeline creation sets (*vk-pipeline-writes*, recorded from vk-pipeline-bake by gfx-collect-writes, as defvk records a command's writes)
:shader-keyfields no Vulkan object holds, outside the vertex input: the alpha test, the shade model, the point size. They select the shaders, so they need a pipeline too
:datasuch fields of the vertex input: a programmable restart index becomes all ones when the index data is uploaded

Emitter and resolute

(let ((vp (vk-alloc a VkViewport)))                     ; zeroed, sType set if it has one
  (vk-set a VkViewport vp :x x :width w :max-depth 1.0)
  (host-vk-cmd-set-viewport cb index 1 vp))
(vk-emit-graphics-pipeline a device layout gfx dynamic-bits)   ; a whole pipeline from a state

The arena is a fixed byte buffer. Its base address comes from the platform (host-vk-arena-base), and every pointer is a host address, where 0 is NULL. The reference uses base 0. (define-vk-host vkCmdDraw ...) declares host-vk-cmd-draw (C: kit_host_vk_cmd_draw). Handles and pointers are u64, and a VkResult is s32. With *vk-trace* the reference body prints the call and the structs it reaches. With *vk-reference-model* it applies the defvk semantics, which makes the reference Vulkan the description of Vulkan. tools/ctil/resolute/vulkan/ holds vulkan.h, the declarations that ctil includes, and vulkan.c, which calls the loader.

The emitter also has vk-emit-clear (the last clear of a state as vkCmdClearAttachments), vk-emit-shader-module (SPIR-V in the arena), and vk-emit-begin-rendering puts a depth format with stencil in DEPTH_STENCIL_ATTACHMENT_OPTIMAL and sets it as the stencil attachment too. Its user is the presenter (src/present), which also uses host-vk-destroy-pipeline and host-vk-destroy-shader-module.

vulkan.c calls core commands through the loader and extension commands (vkCmdSetColorBlendEquationEXT) through vkGetDeviceProcAddr on kit_vk_device, which the device layer (present.c, see src/present/README.md) sets when it creates the device.

Limits (limits.lisp, gen/limits.lisp)

A build is made for one system, so Vulkan's limits, features and extensions are facts of the build, resolved at configure time and folded by ctil. Nothing queries them at run time.

(vk-limit max-push-constants-size)        ; 256 on a GT 1030, 128 by the Vulkan 1.3 spec
(vk-limit min-uniform-buffer-offset-alignment)
(vk-limit max-compute-work-group-size 2)  ; an element of an array limit
(vk-feature sampler-anisotropy)           ; t or nil
(vk-extension "VK_KHR_push_descriptor")   ; t or nil

The names are the registry's members in Lisp spelling (maxImageDimension2D is max-image-dimension2d). Each is a macro that expands to the value, and an unknown name is an error at expansion.

gen/limits.lisp is generated by tools/vkgen/limits.cmake from Khronos's Vulkan-Profiles profile VP_LUNARG_minimum_requirements (pinned in cpmfile.json, fetched with -DXSPE_REGEN=ON, target vk_limits_gen) and vk.xml. It covers the members of VkPhysicalDeviceLimits, VkPhysicalDeviceVulkan1{1,2,3,4}Properties and ...Features, VkPhysicalDeviceFeatures, and the custom border colour, depth clip, colour write and provoking vertex structs: 221 limits and 156 features, each with the spec's requirement at every core version (1.0 to 1.4). The kind comes from vk.xml's limittype:

KindThe spec's value isExamples
:mina minimum: a device has at least itmaxPushConstantsSize, maxImageDimension2D, maxPushDescriptors
:maxa maximum, the safe value of an alignmentminUniformBufferOffsetAlignment, optimalBufferCopyOffsetAlignment
:range(lo hi) that a device's range containspointSizeRange, viewportBoundsRange
:subseta bitmask (an integer) whose bits a device hassubgroupSupportedStages

The build's values come from <build>/gen/vklimits.lisp, written by cmake/vkdevice.cmake (cmake/vklimits.cmake runs it at configure time and, as the target vk_limits, at every build; files change only when the values do, so a new driver is picked up):

-DXSPE_VK_LIMITS=Values
device (the default when vulkaninfo runs)vulkaninfo --json=<XSPE_VK_GPU> (default 0). Configure fails if the device falls short of any requirement of the spec at XSPE_VK_API (default 1.3), or of that version. A value the device does not report (an extension it lacks) is 0 for a :min/:subset limit, nil otherwise.
specThe spec's requirement at XSPE_VK_API: the worst case of any conforming device. A limit the spec first requires at a later version (maxPushDescriptors, 1.4) has that value, the guarantee wherever it exists. With no requirement, a :min limit is 0 (nil for a boolean) and any other nil (optimalBufferCopyOffsetAlignment). Features are nil unless the version requires them; no extension is present.

The C side gets the same values from <build>/gen/vklimits.h (on the include path of XSPE_CC): KIT_VK_MAX_PUSH_CONSTANTS_SIZE (an array's elements ..._0, ..._1), KIT_VK_FEATURE_SAMPLER_ANISOTROPY (0 or 1), KIT_VK_EXTENSION_KHR_PUSH_DESCRIPTOR (1, defined for a device's extensions only), KIT_VK_LIMITS_DEVICE, KIT_VK_GPU, KIT_VK_API_MAJOR/_MINOR (the prefix is XSPE_PREFIX). A device build also writes <build>/gen/vkformats.lisp (XSPE_VK_FORMATS_LISP), the device's format features as (vk-format-support "device" ("VK_FORMAT_..." :sampled :filter ...)); vulkaninfo's JSON has only VkFormatProperties, so :compare is set for a sampled depth format, as Vulkan 1.0 allows depth comparison there.

Tests (tests/isa/vk)

TestWhat
vk_registryvalues, aliases, types, commands, layouts, dynamic states
vk_layoutevery struct and union against cc and vulkan.h
vk_semrecorded trees and writes, commands applied to the model, pipeline bake and bind
vk_costclasses, costs, plans, the hook
vk_emit_semstate to pipeline to bound state is the identity on baked fields; dynamic states survive a bind
vk_tracethe emitter through ctil --emit and cc, against a trace resolute that tracec.lisp writes from the registry and the real vulkan.h, compared with tests/golden/vk_trace.out (ECL's reference trace under XSPE_ECL_ORACLE)
vk_resolutevulkan.c compiles against vulkan.h
vk_limitsgen/limits.lisp and the build's vklimits.lisp load in ctil --eval; every name has a value of its kind
vk_limits_foldvk-limit & co. lowered to C leave no table or lookup; the program, ctil --eval and vklimits.h give the same values
vk_limits_speca spec-mode vklimits.lisp gives the Vulkan 1.3 minimums (tests/golden/vk_limits_spec.out)
vk_limits_device(device builds) every device value meets the spec's requirement, checked again in Lisp
vk_gen_freshgen/ against a fresh vkgen run (-DXSPE_REGEN=ON)

The others compare ctil --eval with tests/golden/ (and with ECL under XSPE_ECL_ORACLE). The vk_limits* tests check themselves (ctil only); vk_gen_fresh regenerates gen/limits.lisp too.

TODO


Made from xspe at b2fac33349db by tools/gen-xspe.py. xspe is GPL-3.0-or-later.