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
28 import xml
.etree
.cElementTree
as et
30 from collections
import OrderedDict
, namedtuple
31 from mako
.template
import Template
33 from anv_extensions
import *
35 # We generate a static hash table for entry point lookup
36 # (vkGetProcAddress). We use a linear congruential generator for our hash
37 # function and a power-of-two size table. The prime numbers are determined
50 TEMPLATE_H
= Template("""\
51 /* This file generated from ${filename}, don't edit directly. */
53 struct anv_dispatch_table {
55 void *entrypoints[${len(entrypoints)}];
57 % for e in entrypoints:
58 % if e.guard is not None:
60 PFN_${e.name} ${e.name};
65 PFN_${e.name} ${e.name};
73 extern const struct anv_dispatch_table ${layer}_dispatch_table;
75 extern const struct anv_dispatch_table anv_tramp_dispatch_table;
77 % for e in entrypoints:
78 % if e.guard is not None:
81 % for layer in LAYERS:
82 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()});
84 % if e.guard is not None:
88 """, output_encoding
='utf-8')
90 TEMPLATE_C
= Template(u
"""\
92 * Copyright © 2015 Intel Corporation
94 * Permission is hereby granted, free of charge, to any person obtaining a
95 * copy of this software and associated documentation files (the "Software"),
96 * to deal in the Software without restriction, including without limitation
97 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
98 * and/or sell copies of the Software, and to permit persons to whom the
99 * Software is furnished to do so, subject to the following conditions:
101 * The above copyright notice and this permission notice (including the next
102 * paragraph) shall be included in all copies or substantial portions of the
105 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
106 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
107 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
108 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
109 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
110 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
114 /* This file generated from ${filename}, don't edit directly. */
116 #include "anv_private.h"
118 struct anv_entrypoint {
123 /* We use a big string constant to avoid lots of reloctions from the entry
124 * point table to lots of little strings. The entries in the entry point table
125 * store the index into this big string.
128 static const char strings[] =
129 % for e in entrypoints:
134 static const struct anv_entrypoint entrypoints[] = {
135 % for e in entrypoints:
136 [${e.num}] = { ${offsets[e.num]}, ${'{:0=#8x}'.format(e.get_c_hash())} }, /* ${e.name} */
140 /* Weak aliases for all potential implementations. These will resolve to
141 * NULL if they're not defined, which lets the resolve_entrypoint() function
142 * either pick the correct entry point.
145 % for layer in LAYERS:
146 % for e in entrypoints:
147 % if e.guard is not None:
150 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()}) __attribute__ ((weak));
151 % if e.guard is not None:
156 const struct anv_dispatch_table ${layer}_dispatch_table = {
157 % for e in entrypoints:
158 % if e.guard is not None:
161 .${e.name} = ${e.prefixed_name(layer)},
162 % if e.guard is not None:
170 /** Trampoline entrypoints for all device functions */
172 % for e in entrypoints:
173 % if e.params[0].type not in ('VkDevice', 'VkCommandBuffer'):
176 % if e.guard is not None:
179 static ${e.return_type}
180 ${e.prefixed_name('anv_tramp')}(${e.decl_params()})
182 % if e.params[0].type == 'VkDevice':
183 ANV_FROM_HANDLE(anv_device, anv_device, ${e.params[0].name});
184 return anv_device->dispatch.${e.name}(${e.call_params()});
186 ANV_FROM_HANDLE(anv_cmd_buffer, anv_cmd_buffer, ${e.params[0].name});
187 return anv_cmd_buffer->device->dispatch.${e.name}(${e.call_params()});
190 % if e.guard is not None:
195 const struct anv_dispatch_table anv_tramp_dispatch_table = {
196 % for e in entrypoints:
197 % if e.params[0].type not in ('VkDevice', 'VkCommandBuffer'):
200 % if e.guard is not None:
203 .${e.name} = ${e.prefixed_name('anv_tramp')},
204 % if e.guard is not None:
211 /** Return true if the core version or extension in which the given entrypoint
212 * is defined is enabled.
214 * If device is NULL, all device extensions are considered enabled.
217 anv_entrypoint_is_enabled(int index, uint32_t core_version,
218 const struct anv_instance_extension_table *instance,
219 const struct anv_device_extension_table *device)
222 % for e in entrypoints:
225 return ${e.core_version.c_vk_version()} <= core_version;
227 % if e.extension.type == 'instance':
228 return instance->${e.extension.name[3:]};
230 return !device || device->${e.extension.name[3:]};
241 static void * __attribute__ ((noinline))
242 anv_resolve_entrypoint(const struct gen_device_info *devinfo, uint32_t index)
244 if (devinfo == NULL) {
245 return anv_dispatch_table.entrypoints[index];
248 const struct anv_dispatch_table *genX_table;
249 switch (devinfo->gen) {
251 genX_table = &gen11_dispatch_table;
254 genX_table = &gen10_dispatch_table;
257 genX_table = &gen9_dispatch_table;
260 genX_table = &gen8_dispatch_table;
263 if (devinfo->is_haswell)
264 genX_table = &gen75_dispatch_table;
266 genX_table = &gen7_dispatch_table;
269 unreachable("unsupported gen\\n");
272 if (genX_table->entrypoints[index])
273 return genX_table->entrypoints[index];
275 return anv_dispatch_table.entrypoints[index];
279 * size ${hash_size} entries
280 * collisions entries:
281 % for i in xrange(10):
282 * ${i}${'+' if i == 9 else ''} ${collisions[i]}
286 #define none ${'{:#x}'.format(none)}
287 static const uint16_t map[] = {
288 % for i in xrange(0, hash_size, 8):
289 % for j in xrange(i, i + 8):
290 ## This is 6 because the 0x is counted in the length
291 % if mapping[j] & 0xffff == 0xffff:
294 ${'{:0=#6x}'.format(mapping[j] & 0xffff)},
301 anv_get_entrypoint_index(const char *name)
303 static const uint32_t prime_factor = ${prime_factor};
304 static const uint32_t prime_step = ${prime_step};
305 const struct anv_entrypoint *e;
310 for (p = name; *p; p++)
311 hash = hash * prime_factor + *p;
315 i = map[h & ${hash_mask}];
320 } while (e->hash != hash);
322 if (strcmp(name, strings + e->name) != 0)
329 anv_lookup_entrypoint(const struct gen_device_info *devinfo, const char *name)
331 int idx = anv_get_entrypoint_index(name);
334 return anv_resolve_entrypoint(devinfo, idx);
335 }""", output_encoding
='utf-8')
340 HASH_MASK
= HASH_SIZE
- 1
342 PRIME_FACTOR
= 5024183
347 """Calculate the same hash value that Mesa will calculate in C."""
348 return functools
.reduce(
349 lambda h
, c
: (h
* PRIME_FACTOR
+ ord(c
)) & U32_MASK
, name
, 0)
351 EntrypointParam
= namedtuple('EntrypointParam', 'type name decl')
353 class Entrypoint(object):
354 def __init__(self
, name
, return_type
, params
, guard
= None):
356 self
.return_type
= return_type
361 # Extensions which require this entrypoint
362 self
.core_version
= None
363 self
.extension
= None
365 def prefixed_name(self
, prefix
):
366 assert self
.name
.startswith('vk')
367 return prefix
+ '_' + self
.name
[2:]
369 def decl_params(self
):
370 return ', '.join(p
.decl
for p
in self
.params
)
372 def call_params(self
):
373 return ', '.join(p
.name
for p
in self
.params
)
375 def get_c_hash(self
):
376 return cal_hash(self
.name
)
378 def get_entrypoints(doc
, entrypoints_to_defines
, start_index
):
379 """Extract the entry points from the registry."""
380 entrypoints
= OrderedDict()
382 for command
in doc
.findall('./commands/command'):
383 ret_type
= command
.find('./proto/type').text
384 fullname
= command
.find('./proto/name').text
385 params
= [EntrypointParam(
386 type = p
.find('./type').text
,
387 name
= p
.find('./name').text
,
388 decl
= ''.join(p
.itertext())
389 ) for p
in command
.findall('./param')]
390 guard
= entrypoints_to_defines
.get(fullname
)
391 # They really need to be unique
392 assert fullname
not in entrypoints
393 entrypoints
[fullname
] = Entrypoint(fullname
, ret_type
, params
, guard
)
395 enabled_commands
= set()
396 for feature
in doc
.findall('./feature'):
397 assert feature
.attrib
['api'] == 'vulkan'
398 version
= VkVersion(feature
.attrib
['number'])
399 if version
> MAX_API_VERSION
:
402 for command
in feature
.findall('./require/command'):
403 e
= entrypoints
[command
.attrib
['name']]
405 assert e
.core_version
is None
406 e
.core_version
= version
408 supported_exts
= dict((ext
.name
, ext
) for ext
in EXTENSIONS
)
409 for extension
in doc
.findall('.extensions/extension'):
410 ext_name
= extension
.attrib
['name']
411 if ext_name
not in supported_exts
:
414 if extension
.attrib
['supported'] != 'vulkan':
417 ext
= supported_exts
[ext_name
]
418 ext
.type = extension
.attrib
['type']
420 for command
in extension
.findall('./require/command'):
421 e
= entrypoints
[command
.attrib
['name']]
423 assert e
.core_version
is None
424 assert e
.extension
is None
427 return [e
for e
in entrypoints
.itervalues() if e
.enabled
]
430 def get_entrypoints_defines(doc
):
431 """Maps entry points to extension defines."""
432 entrypoints_to_defines
= {}
434 for extension
in doc
.findall('./extensions/extension[@protect]'):
435 define
= extension
.attrib
['protect']
437 for entrypoint
in extension
.findall('./require/command'):
438 fullname
= entrypoint
.attrib
['name']
439 entrypoints_to_defines
[fullname
] = define
441 return entrypoints_to_defines
444 def gen_code(entrypoints
):
445 """Generate the C code."""
448 for e
in entrypoints
:
452 mapping
= [NONE
] * HASH_SIZE
453 collisions
= [0] * 10
454 for e
in entrypoints
:
457 while mapping
[h
& HASH_MASK
] != NONE
:
463 collisions
[level
] += 1
464 mapping
[h
& HASH_MASK
] = e
.num
466 return TEMPLATE_C
.render(entrypoints
=entrypoints
,
469 collisions
=collisions
,
472 prime_step
=PRIME_STEP
,
473 prime_factor
=PRIME_FACTOR
,
476 filename
=os
.path
.basename(__file__
))
480 parser
= argparse
.ArgumentParser()
481 parser
.add_argument('--outdir', help='Where to write the files.',
483 parser
.add_argument('--xml',
484 help='Vulkan API XML file.',
488 args
= parser
.parse_args()
492 for filename
in args
.xml_files
:
493 doc
= et
.parse(filename
)
494 entrypoints
+= get_entrypoints(doc
, get_entrypoints_defines(doc
),
495 start_index
=len(entrypoints
))
497 # Manually add CreateDmaBufImageINTEL for which we don't have an extension
499 entrypoints
.append(Entrypoint('vkCreateDmaBufImageINTEL', 'VkResult', [
500 EntrypointParam('VkDevice', 'device', 'VkDevice device'),
501 EntrypointParam('VkDmaBufImageCreateInfo', 'pCreateInfo',
502 'const VkDmaBufImageCreateInfo* pCreateInfo'),
503 EntrypointParam('VkAllocationCallbacks', 'pAllocator',
504 'const VkAllocationCallbacks* pAllocator'),
505 EntrypointParam('VkDeviceMemory', 'pMem', 'VkDeviceMemory* pMem'),
506 EntrypointParam('VkImage', 'pImage', 'VkImage* pImage')
509 for num
, e
in enumerate(entrypoints
):
512 # For outputting entrypoints.h we generate a anv_EntryPoint() prototype
515 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.h'), 'wb') as f
:
516 f
.write(TEMPLATE_H
.render(entrypoints
=entrypoints
,
518 filename
=os
.path
.basename(__file__
)))
519 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.c'), 'wb') as f
:
520 f
.write(gen_code(entrypoints
))
522 # In the even there's an error this imports some helpers from mako
523 # to print a useful stack trace and prints it, then exits with
524 # status 1, if python is run with debug; otherwise it just raises
528 from mako
import exceptions
529 sys
.stderr
.write(exceptions
.text_error_template().render() + '\n')
534 if __name__
== '__main__':