3 # Copyright © 2015, 2017 Intel Corporation
5 # Permission is hereby granted, free of charge, to any person obtaining a
6 # copy of this software and associated documentation files (the "Software"),
7 # to deal in the Software without restriction, including without limitation
8 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 # and/or sell copies of the Software, and to permit persons to whom the
10 # Software is furnished to do so, subject to the following conditions:
12 # The above copyright notice and this permission notice (including the next
13 # paragraph) shall be included in all copies or substantial portions of the
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
29 import xml
.etree
.cElementTree
as et
31 from mako
.template
import Template
35 SUPPORTED_EXTENSIONS
= [
36 'VK_KHR_descriptor_update_template',
37 'VK_KHR_get_physical_device_properties2',
38 'VK_KHR_incremental_present',
39 'VK_KHR_maintenance1',
40 'VK_KHR_push_descriptor',
41 'VK_KHR_sampler_mirror_clamp_to_edge',
42 'VK_KHR_shader_draw_parameters',
45 'VK_KHR_wayland_surface',
47 'VK_KHR_xlib_surface',
48 'VK_KHX_external_memory',
49 'VK_KHX_external_memory_capabilities',
52 # We generate a static hash table for entry point lookup
53 # (vkGetProcAddress). We use a linear congruential generator for our hash
54 # function and a power-of-two size table. The prime numbers are determined
57 TEMPLATE_H
= Template(textwrap
.dedent("""\
58 /* This file generated from ${filename}, don't edit directly. */
60 struct anv_dispatch_table {
62 void *entrypoints[${len(entrypoints)}];
64 % for _, name, _, _, _, guard in entrypoints:
65 % if guard is not None:
67 PFN_vk${name} ${name};
72 PFN_vk${name} ${name};
79 % for type_, name, args, num, h, guard in entrypoints:
80 % if guard is not None:
83 ${type_} anv_${name}(${args});
84 ${type_} gen7_${name}(${args});
85 ${type_} gen75_${name}(${args});
86 ${type_} gen8_${name}(${args});
87 ${type_} gen9_${name}(${args});
88 % if guard is not None:
92 """), output_encoding
='utf-8')
94 TEMPLATE_C
= Template(textwrap
.dedent(u
"""\
96 * Copyright © 2015 Intel Corporation
98 * Permission is hereby granted, free of charge, to any person obtaining a
99 * copy of this software and associated documentation files (the "Software"),
100 * to deal in the Software without restriction, including without limitation
101 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
102 * and/or sell copies of the Software, and to permit persons to whom the
103 * Software is furnished to do so, subject to the following conditions:
105 * The above copyright notice and this permission notice (including the next
106 * paragraph) shall be included in all copies or substantial portions of the
109 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
110 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
111 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
112 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
113 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
114 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
118 /* This file generated from ${filename}, don't edit directly. */
120 #include "anv_private.h"
122 struct anv_entrypoint {
127 /* We use a big string constant to avoid lots of reloctions from the entry
128 * point table to lots of little strings. The entries in the entry point table
129 * store the index into this big string.
132 static const char strings[] =
133 % for _, name, _, _, _, _ in entrypoints:
138 static const struct anv_entrypoint entrypoints[] = {
139 % for _, _, _, num, h, _ in entrypoints:
140 { ${offsets[num]}, ${'{:0=#8x}'.format(h)} },
144 /* Weak aliases for all potential implementations. These will resolve to
145 * NULL if they're not defined, which lets the resolve_entrypoint() function
146 * either pick the correct entry point.
149 % for layer in ['anv', 'gen7', 'gen75', 'gen8', 'gen9']:
150 % for type_, name, args, _, _, guard in entrypoints:
151 % if guard is not None:
154 ${type_} ${layer}_${name}(${args}) __attribute__ ((weak));
155 % if guard is not None:
160 const struct anv_dispatch_table ${layer}_layer = {
161 % for _, name, args, _, _, guard in entrypoints:
162 % if guard is not None:
165 .${name} = ${layer}_${name},
166 % if guard is not None:
173 static void * __attribute__ ((noinline))
174 anv_resolve_entrypoint(const struct gen_device_info *devinfo, uint32_t index)
176 if (devinfo == NULL) {
177 return anv_layer.entrypoints[index];
180 switch (devinfo->gen) {
182 if (gen9_layer.entrypoints[index])
183 return gen9_layer.entrypoints[index];
186 if (gen8_layer.entrypoints[index])
187 return gen8_layer.entrypoints[index];
190 if (devinfo->is_haswell && gen75_layer.entrypoints[index])
191 return gen75_layer.entrypoints[index];
193 if (gen7_layer.entrypoints[index])
194 return gen7_layer.entrypoints[index];
197 return anv_layer.entrypoints[index];
199 unreachable("unsupported gen\\n");
204 * size ${hash_size} entries
205 * collisions entries:
206 % for i in xrange(10):
207 * ${i}${'+' if i == 9 else ''} ${collisions[i]}
211 #define none ${'{:#x}'.format(none)}
212 static const uint16_t map[] = {
213 % for i in xrange(0, hash_size, 8):
214 % for j in xrange(i, i + 8):
215 ## This is 6 because the 0x is counted in the length
216 % if mapping[j] & 0xffff == 0xffff:
219 ${'{:0=#6x}'.format(mapping[j] & 0xffff)},
226 anv_lookup_entrypoint(const struct gen_device_info *devinfo, const char *name)
228 static const uint32_t prime_factor = ${prime_factor};
229 static const uint32_t prime_step = ${prime_step};
230 const struct anv_entrypoint *e;
235 for (p = name; *p; p++)
236 hash = hash * prime_factor + *p;
240 i = map[h & ${hash_mask}];
245 } while (e->hash != hash);
247 if (strcmp(name, strings + e->name) != 0)
250 return anv_resolve_entrypoint(devinfo, i);
251 }"""), output_encoding
='utf-8')
256 HASH_MASK
= HASH_SIZE
- 1
258 PRIME_FACTOR
= 5024183
263 """Calculate the same hash value that Mesa will calculate in C."""
264 return functools
.reduce(
265 lambda h
, c
: (h
* PRIME_FACTOR
+ ord(c
)) & U32_MASK
, name
, 0)
268 def get_entrypoints(doc
, entrypoints_to_defines
):
269 """Extract the entry points from the registry."""
272 enabled_commands
= set()
273 for feature
in doc
.findall('./feature'):
274 assert feature
.attrib
['api'] == 'vulkan'
275 if float(feature
.attrib
['number']) > MAX_API_VERSION
:
278 for command
in feature
.findall('./require/command'):
279 enabled_commands
.add(command
.attrib
['name'])
281 for extension
in doc
.findall('.extensions/extension'):
282 if extension
.attrib
['name'] not in SUPPORTED_EXTENSIONS
:
285 assert extension
.attrib
['supported'] == 'vulkan'
286 for command
in extension
.findall('./require/command'):
287 enabled_commands
.add(command
.attrib
['name'])
290 for command
in doc
.findall('./commands/command'):
291 type = command
.find('./proto/type').text
292 fullname
= command
.find('./proto/name').text
294 if fullname
not in enabled_commands
:
297 shortname
= fullname
[2:]
298 params
= (''.join(p
.itertext()) for p
in command
.findall('./param'))
299 params
= ', '.join(params
)
300 guard
= entrypoints_to_defines
.get(fullname
)
301 entrypoints
.append((type, shortname
, params
, index
, cal_hash(fullname
), guard
))
307 def get_entrypoints_defines(doc
):
308 """Maps entry points to extension defines."""
309 entrypoints_to_defines
= {}
311 for extension
in doc
.findall('./extensions/extension[@protect]'):
312 define
= extension
.attrib
['protect']
314 for entrypoint
in extension
.findall('./require/command'):
315 fullname
= entrypoint
.attrib
['name']
316 entrypoints_to_defines
[fullname
] = define
318 return entrypoints_to_defines
321 def gen_code(entrypoints
):
322 """Generate the C code."""
325 for _
, name
, _
, _
, _
, _
in entrypoints
:
327 i
+= 2 + len(name
) + 1
329 mapping
= [NONE
] * HASH_SIZE
330 collisions
= [0] * 10
331 for _
, name
, _
, num
, h
, _
in entrypoints
:
333 while mapping
[h
& HASH_MASK
] != NONE
:
339 collisions
[level
] += 1
340 mapping
[h
& HASH_MASK
] = num
342 return TEMPLATE_C
.render(entrypoints
=entrypoints
,
344 collisions
=collisions
,
347 prime_step
=PRIME_STEP
,
348 prime_factor
=PRIME_FACTOR
,
351 filename
=os
.path
.basename(__file__
))
355 parser
= argparse
.ArgumentParser()
356 parser
.add_argument('--outdir', help='Where to write the files.',
358 parser
.add_argument('--xml', help='Vulkan API XML file.', required
=True)
359 args
= parser
.parse_args()
361 doc
= et
.parse(args
.xml
)
362 entrypoints
= get_entrypoints(doc
, get_entrypoints_defines(doc
))
364 # Manually add CreateDmaBufImageINTEL for which we don't have an extension
366 entrypoints
.append(('VkResult', 'CreateDmaBufImageINTEL',
367 'VkDevice device, ' +
368 'const VkDmaBufImageCreateInfo* pCreateInfo, ' +
369 'const VkAllocationCallbacks* pAllocator,' +
370 'VkDeviceMemory* pMem,' +
371 'VkImage* pImage', len(entrypoints
),
372 cal_hash('vkCreateDmaBufImageINTEL'), None))
374 # For outputting entrypoints.h we generate a anv_EntryPoint() prototype
376 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.h'), 'wb') as f
:
377 f
.write(TEMPLATE_H
.render(entrypoints
=entrypoints
,
378 filename
=os
.path
.basename(__file__
)))
379 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.c'), 'wb') as f
:
380 f
.write(gen_code(entrypoints
))
383 if __name__
== '__main__':