File: vulkan_dispatch_table_generator.py

package info (click to toggle)
gfxreconstruct 0.9.18%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 24,636 kB
  • sloc: cpp: 328,961; ansic: 25,454; python: 18,156; xml: 255; sh: 128; makefile: 6
file content (332 lines) | stat: -rw-r--r-- 13,196 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#!/usr/bin/python3 -i
#
# Copyright (c) 2019 Valve Corporation
# Copyright (c) 2019 LunarG, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

import sys
from base_generator import BaseGenerator, BaseGeneratorOptions, write


class VulkanDispatchTableGeneratorOptions(BaseGeneratorOptions):
    """Options for generating a dispatch table for Vulkan API calls."""

    def __init__(
        self,
        blacklists=None,  # Path to JSON file listing apicalls and structs to ignore.
        platform_types=None,  # Path to JSON file listing platform (WIN32, X11, etc.) defined types.
        filename=None,
        directory='.',
        prefix_text='',
        protect_file=False,
        protect_feature=True,
        extraVulkanHeaders=[]
    ):
        BaseGeneratorOptions.__init__(
            self,
            blacklists,
            platform_types,
            filename,
            directory,
            prefix_text,
            protect_file,
            protect_feature,
            extraVulkanHeaders=extraVulkanHeaders
        )


class VulkanDispatchTableGenerator(BaseGenerator):
    """VulkanDispatchTableGenerator - subclass of BaseGenerator.
    Generates a dispatch table for Vulkan API calls.
    Generate dispatch table for Vulkan API calls.
    """

    def __init__(
        self, err_file=sys.stderr, warn_file=sys.stderr, diag_file=sys.stdout
    ):
        BaseGenerator.__init__(
            self,
            process_cmds=True,
            process_structs=False,
            feature_break=False,
            err_file=err_file,
            warn_file=warn_file,
            diag_file=diag_file
        )
        # Map of return types to default return values for no-op functions
        self.RETURN_DEFAULTS = {
            'VkResult': 'VK_SUCCESS',
            'VkBool32': 'VK_TRUE',
            'PFN_vkVoidFunction': 'nullptr',
            'VkDeviceAddress': '0',
            'VkDeviceSize': '0',
            'uint32_t': '0',
            'uint64_t': '0'
        }

        self.instance_cmd_names = dict(
        )  # Map of API call names to no-op function declarations
        self.device_cmd_names = dict(
        )  # Map of API call names to no-op function declarations

    def beginFile(self, gen_opts):
        """Method override."""
        BaseGenerator.beginFile(self, gen_opts)

        write('#include "format/platform_types.h"', file=self.outFile)
        write('#include "util/defines.h"', file=self.outFile)
        write('#include "util/logging.h"', file=self.outFile)
        self.newline()
        write('#include "vulkan/vk_layer.h"', file=self.outFile)
        self.includeVulkanHeaders(gen_opts)
        self.newline()
        write('#ifdef WIN32', file=self.outFile)
        write('#ifdef CreateEvent', file=self.outFile)
        write('#undef CreateEvent', file=self.outFile)
        write('#endif', file=self.outFile)
        write('#ifdef CreateSemaphore', file=self.outFile)
        write('#undef CreateSemaphore', file=self.outFile)
        write('#endif', file=self.outFile)
        write('#endif', file=self.outFile)
        self.newline()
        write('GFXRECON_BEGIN_NAMESPACE(gfxrecon)', file=self.outFile)
        write('GFXRECON_BEGIN_NAMESPACE(encode)', file=self.outFile)

    def endFile(self):
        """Method override."""
        self.newline()

        write('typedef const void* DispatchKey;', file=self.outFile)
        self.newline()

        write(
            '// Retrieve a dispatch key from a dispatchable handle',
            file=self.outFile
        )
        write(
            'static DispatchKey GetDispatchKey(const void* handle)',
            file=self.outFile
        )
        write('{', file=self.outFile)
        write(
            '    const DispatchKey* dispatch_key = reinterpret_cast<const DispatchKey*>(handle);',
            file=self.outFile
        )
        write('    return (*dispatch_key);', file=self.outFile)
        write('}', file=self.outFile)

        self.newline()
        self.generate_no_op_funcs()
        self.newline()

        write('struct LayerTable', file=self.outFile)
        write('{', file=self.outFile)
        write(
            '    PFN_vkCreateInstance CreateInstance{ nullptr };',
            file=self.outFile
        )
        write(
            '    PFN_vkCreateDevice CreateDevice{ nullptr };',
            file=self.outFile
        )
        write('};', file=self.outFile)

        self.newline()
        self.generate_instance_cmd_table()
        self.newline()
        self.generate_device_cmd_table()
        self.newline()

        write(
            'template <typename GetProcAddr, typename Handle, typename FuncP>',
            file=self.outFile
        )
        write(
            'static void LoadFunction(GetProcAddr gpa, Handle handle, const char* name, FuncP* funcp)',
            file=self.outFile
        )
        write('{', file=self.outFile)
        write(
            '    FuncP result = reinterpret_cast<FuncP>(gpa(handle, name));',
            file=self.outFile
        )
        write('    if (result != nullptr)', file=self.outFile)
        write('    {', file=self.outFile)
        write('        (*funcp) = result;', file=self.outFile)
        write('    }', file=self.outFile)
        write('}', file=self.outFile)

        self.newline()
        self.generate_load_instance_table_func()
        self.newline()
        self.generate_load_device_table_func()
        self.newline()

        write('GFXRECON_END_NAMESPACE(encode)', file=self.outFile)
        write('GFXRECON_END_NAMESPACE(gfxrecon)', file=self.outFile)

        # Finish processing in superclass
        BaseGenerator.endFile(self)

    def need_feature_generation(self):
        """Indicates that the current feature has C++ code to generate."""
        if self.feature_cmd_params:
            return True
        return False

    def generate_feature(self):
        """Performs C++ code generation for the feature."""
        for name in self.feature_cmd_params:
            # Ignore vkCreateInstance and vkCreateDevice, which are provided by the layer due to special handling requirements
            if name not in ['vkCreateInstance', 'vkCreateDevice']:
                info = self.feature_cmd_params[name]
                values = info[2]

                if values and values[0]:
                    first_param = values[0]
                    if self.is_handle(first_param.base_type):
                        return_type = info[0]
                        proto = info[1]

                        # vkSetDebugUtilsObjectNameEXT and vkSetDebugUtilsObjectTagEXT
                        # need to be probed from GetInstanceProcAddress due to a loader issue.
                        # https://github.com/KhronosGroup/Vulkan-Loader/issues/1109
                        # TODO : When loader with fix for issue is widely available, remove this
                        # special case.
                        if name in ['vkSetDebugUtilsObjectNameEXT', 'vkSetDebugUtilsObjectTagEXT']:
                            self.instance_cmd_names[name] = self.make_cmd_decl(return_type, proto, values, name)
                        elif first_param.base_type not in ['VkInstance', 'VkPhysicalDevice']:
                            self.device_cmd_names[name] = self.make_cmd_decl(return_type, proto, values, name)
                        else:
                            self.instance_cmd_names[name] = self.make_cmd_decl(return_type, proto, values, name)

    def generate_instance_cmd_table(self):
        """Generate instance dispatch table structure."""
        write('struct InstanceTable', file=self.outFile)
        write('{', file=self.outFile)

        for name in self.instance_cmd_names:
            decl = '    PFN_{} {}{{ noop::{} }};'.format(
                name, name[2:], name[2:]
            )
            write(decl, file=self.outFile)

        write('};', file=self.outFile)

    def generate_device_cmd_table(self):
        """Generate device dispatch table structure."""
        write('struct DeviceTable', file=self.outFile)
        write('{', file=self.outFile)

        for name in self.device_cmd_names:
            decl = '    PFN_{} {}{{ noop::{} }};'.format(
                name, name[2:], name[2:]
            )
            write(decl, file=self.outFile)

        write('};', file=self.outFile)

    def generate_no_op_funcs(self):
        """Generate no-op function definitions."""
        write('GFXRECON_BEGIN_NAMESPACE(noop)', file=self.outFile)
        write('// clang-format off', file=self.outFile)

        for name in self.instance_cmd_names:
            write(self.instance_cmd_names[name], file=self.outFile)

        for name in self.device_cmd_names:
            write(self.device_cmd_names[name], file=self.outFile)

        write('// clang-format on', file=self.outFile)
        write('GFXRECON_END_NAMESPACE(noop)', file=self.outFile)

    def generate_load_instance_table_func(self):
        """Generate function to set the instance table's functions with a getprocaddress routine."""
        write(
            'static void LoadInstanceTable(PFN_vkGetInstanceProcAddr gpa, VkInstance instance, InstanceTable* table)',
            file=self.outFile
        )
        write('{', file=self.outFile)
        write('    assert(table != nullptr);', file=self.outFile)
        self.newline()

        for name in self.instance_cmd_names:
            if name == 'vkGetInstanceProcAddr':
                write(
                    '    table->GetInstanceProcAddr = gpa;', file=self.outFile
                )
            else:
                expr = '    LoadFunction(gpa, instance, "{}", &table->{});'.format(
                    name, name[2:]
                )
                write(expr, file=self.outFile)

        write('}', file=self.outFile)

    def generate_load_device_table_func(self):
        """Generate function to set the device table's functions with a getprocaddress routine."""
        write(
            'static void LoadDeviceTable(PFN_vkGetDeviceProcAddr gpa, VkDevice device, DeviceTable* table)',
            file=self.outFile
        )
        write('{', file=self.outFile)
        write('    assert(table != nullptr);', file=self.outFile)
        self.newline()

        for name in self.device_cmd_names:
            if name == 'vkGetDeviceProcAddr':
                write('    table->GetDeviceProcAddr = gpa;', file=self.outFile)
            else:
                expr = '    LoadFunction(gpa, device, "{}", &table->{});'.format(
                    name, name[2:]
                )
                write(expr, file=self.outFile)

        write('}', file=self.outFile)

    def make_full_typename(self, value):
        """Generate the full typename for the NoOp function parameters; the array types need the [] moved from the parameter name to the parameter typename."""
        if value.is_array and not value.is_dynamic:
            return '{}[{}]'.format(value.full_type, value.array_capacity)
        else:
            return value.full_type

    def make_cmd_decl(self, return_type, proto, values, name):
        """Generate a function prototype for the NoOp functions, with a parameter list that only includes types."""
        params = ', '.join(
            [self.make_full_typename(value) for value in values]
        )
        if return_type == 'void':
            return 'static {}({}) {{ GFXRECON_LOG_WARNING("Unsupported function {} was called, resulting in no-op behavior."); }}'.format(
                proto, params, name
            )
        else:
            return_value = ''
            if return_type in self.RETURN_DEFAULTS:
                return_value = self.RETURN_DEFAULTS[return_type]
            else:
                print(
                    'Unrecognized return type {} for no-op function generation; returning a zero initialized value'
                    .format(return_type)
                )
                return_value = '{}{{}}'.format(return_type)
            return 'static {}({}) {{ GFXRECON_LOG_WARNING("Unsupported function {} was called, resulting in no-op behavior."); return {}; }}'.format(
                proto, params, name, return_value
            )