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 collections
import OrderedDict
, namedtuple
32 from mako
.template
import Template
34 from anv_extensions
import *
36 # We generate a static hash table for entry point lookup
37 # (vkGetProcAddress). We use a linear congruential generator for our hash
38 # function and a power-of-two size table. The prime numbers are determined
51 TEMPLATE_H
= Template("""\
52 /* This file generated from ${filename}, don't edit directly. */
54 struct anv_dispatch_table {
56 void *entrypoints[${len(entrypoints)}];
58 % for e in entrypoints:
59 % if e.guard is not None:
61 PFN_${e.name} ${e.name};
66 PFN_${e.name} ${e.name};
74 extern const struct anv_dispatch_table ${layer}_dispatch_table;
76 extern const struct anv_dispatch_table anv_tramp_dispatch_table;
78 % for e in entrypoints:
82 % if e.guard is not None:
85 % for layer in LAYERS:
86 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()});
88 % if e.guard is not None:
92 """, output_encoding
='utf-8')
94 TEMPLATE_C
= Template(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 string_map_entry {
128 /* We use a big string constant to avoid lots of reloctions from the entry
129 * point table to lots of little strings. The entries in the entry point table
130 * store the index into this big string.
133 static const char strings[] =
134 % for s in strmap.sorted_strings:
139 static const struct string_map_entry string_map_entries[] = {
140 % for s in strmap.sorted_strings:
141 { ${s.offset}, ${'{:0=#8x}'.format(s.hash)}, ${s.num} }, /* ${s.string} */
146 * size ${len(strmap.sorted_strings)} entries
147 * collisions entries:
148 % for i in xrange(10):
149 * ${i}${'+' if i == 9 else ' '} ${strmap.collisions[i]}
154 static const uint16_t string_map[${strmap.hash_size}] = {
155 % for e in strmap.mapping:
156 ${ '{:0=#6x}'.format(e) if e >= 0 else 'none' },
161 string_map_lookup(const char *str)
163 static const uint32_t prime_factor = ${strmap.prime_factor};
164 static const uint32_t prime_step = ${strmap.prime_step};
165 const struct string_map_entry *e;
171 for (p = str; *p; p++)
172 hash = hash * prime_factor + *p;
176 i = string_map[h & ${strmap.hash_mask}];
179 e = &string_map_entries[i];
180 if (e->hash == hash && strcmp(str, strings + e->name) == 0)
188 /* Weak aliases for all potential implementations. These will resolve to
189 * NULL if they're not defined, which lets the resolve_entrypoint() function
190 * either pick the correct entry point.
193 % for layer in LAYERS:
194 % for e in entrypoints:
198 % if e.guard is not None:
201 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()}) __attribute__ ((weak));
202 % if e.guard is not None:
207 const struct anv_dispatch_table ${layer}_dispatch_table = {
208 % for e in entrypoints:
209 % if e.guard is not None:
212 .${e.name} = ${e.prefixed_name(layer)},
213 % if e.guard is not None:
221 /** Trampoline entrypoints for all device functions */
223 % for e in entrypoints:
224 % if e.alias or not e.is_device_entrypoint():
227 % if e.guard is not None:
230 static ${e.return_type}
231 ${e.prefixed_name('anv_tramp')}(${e.decl_params()})
233 % if e.params[0].type == 'VkDevice':
234 ANV_FROM_HANDLE(anv_device, anv_device, ${e.params[0].name});
235 return anv_device->dispatch.${e.name}(${e.call_params()});
237 ANV_FROM_HANDLE(anv_cmd_buffer, anv_cmd_buffer, ${e.params[0].name});
238 return anv_cmd_buffer->device->dispatch.${e.name}(${e.call_params()});
241 % if e.guard is not None:
246 const struct anv_dispatch_table anv_tramp_dispatch_table = {
247 % for e in entrypoints:
248 % if not e.is_device_entrypoint():
251 % if e.guard is not None:
254 .${e.name} = ${e.prefixed_name('anv_tramp')},
255 % if e.guard is not None:
262 /** Return true if the core version or extension in which the given entrypoint
263 * is defined is enabled.
265 * If device is NULL, all device extensions are considered enabled.
268 anv_entrypoint_is_enabled(int index, uint32_t core_version,
269 const struct anv_instance_extension_table *instance,
270 const struct anv_device_extension_table *device)
273 % for e in entrypoints:
277 return ${e.core_version.c_vk_version()} <= core_version;
279 % for ext in e.extensions:
280 % if ext.type == 'instance':
281 if (!device && instance->${ext.name[3:]}) return true;
283 if (!device || device->${ext.name[3:]}) return true;
296 static void * __attribute__ ((noinline))
297 anv_resolve_entrypoint(const struct gen_device_info *devinfo, uint32_t index)
299 if (devinfo == NULL) {
300 return anv_dispatch_table.entrypoints[index];
303 const struct anv_dispatch_table *genX_table;
304 switch (devinfo->gen) {
306 genX_table = &gen11_dispatch_table;
309 genX_table = &gen10_dispatch_table;
312 genX_table = &gen9_dispatch_table;
315 genX_table = &gen8_dispatch_table;
318 if (devinfo->is_haswell)
319 genX_table = &gen75_dispatch_table;
321 genX_table = &gen7_dispatch_table;
324 unreachable("unsupported gen\\n");
327 if (genX_table->entrypoints[index])
328 return genX_table->entrypoints[index];
330 return anv_dispatch_table.entrypoints[index];
334 anv_get_entrypoint_index(const char *name)
336 return string_map_lookup(name);
340 anv_lookup_entrypoint(const struct gen_device_info *devinfo, const char *name)
342 int idx = anv_get_entrypoint_index(name);
345 return anv_resolve_entrypoint(devinfo, idx);
346 }""", output_encoding
='utf-8')
350 PRIME_FACTOR
= 5024183
353 class StringIntMapEntry(object):
354 def __init__(self
, string
, num
):
358 # Calculate the same hash value that we will calculate in C.
361 h
= ((h
* PRIME_FACTOR
) + ord(c
)) & U32_MASK
366 def round_to_pow2(x
):
367 return 2**int(math
.ceil(math
.log(x
, 2)))
369 class StringIntMap(object):
372 self
.strings
= dict()
374 def add_string(self
, string
, num
):
375 assert not self
.baked
376 assert string
not in self
.strings
377 assert num
>= 0 and num
< 2**31
378 self
.strings
[string
] = StringIntMapEntry(string
, num
)
381 self
.sorted_strings
= \
382 sorted(self
.strings
.values(), key
=lambda x
: x
.string
)
384 for entry
in self
.sorted_strings
:
385 entry
.offset
= offset
386 offset
+= len(entry
.string
) + 1
388 # Save off some values that we'll need in C
389 self
.hash_size
= round_to_pow2(len(self
.strings
) * 1.25)
390 self
.hash_mask
= self
.hash_size
- 1
391 self
.prime_factor
= PRIME_FACTOR
392 self
.prime_step
= PRIME_STEP
394 self
.mapping
= [-1] * self
.hash_size
395 self
.collisions
= [0] * 10
396 for idx
, s
in enumerate(self
.sorted_strings
):
399 while self
.mapping
[h
& self
.hash_mask
] >= 0:
402 self
.collisions
[min(level
, 9)] += 1
403 self
.mapping
[h
& self
.hash_mask
] = idx
405 EntrypointParam
= namedtuple('EntrypointParam', 'type name decl')
407 class EntrypointBase(object):
408 def __init__(self
, name
):
414 # Extensions which require this entrypoint
415 self
.core_version
= None
418 class Entrypoint(EntrypointBase
):
419 def __init__(self
, name
, return_type
, params
, guard
= None):
420 super(Entrypoint
, self
).__init
__(name
)
421 self
.return_type
= return_type
425 def is_device_entrypoint(self
):
426 return self
.params
[0].type in ('VkDevice', 'VkCommandBuffer')
428 def prefixed_name(self
, prefix
):
429 assert self
.name
.startswith('vk')
430 return prefix
+ '_' + self
.name
[2:]
432 def decl_params(self
):
433 return ', '.join(p
.decl
for p
in self
.params
)
435 def call_params(self
):
436 return ', '.join(p
.name
for p
in self
.params
)
438 class EntrypointAlias(EntrypointBase
):
439 def __init__(self
, name
, entrypoint
):
440 super(EntrypointAlias
, self
).__init
__(name
)
441 self
.alias
= entrypoint
443 def is_device_entrypoint(self
):
444 return self
.alias
.is_device_entrypoint()
446 def prefixed_name(self
, prefix
):
447 return self
.alias
.prefixed_name(prefix
)
449 def get_entrypoints(doc
, entrypoints_to_defines
, start_index
):
450 """Extract the entry points from the registry."""
451 entrypoints
= OrderedDict()
453 for command
in doc
.findall('./commands/command'):
454 if 'alias' in command
.attrib
:
455 alias
= command
.attrib
['name']
456 target
= command
.attrib
['alias']
457 entrypoints
[alias
] = EntrypointAlias(alias
, entrypoints
[target
])
459 name
= command
.find('./proto/name').text
460 ret_type
= command
.find('./proto/type').text
461 params
= [EntrypointParam(
462 type = p
.find('./type').text
,
463 name
= p
.find('./name').text
,
464 decl
= ''.join(p
.itertext())
465 ) for p
in command
.findall('./param')]
466 guard
= entrypoints_to_defines
.get(name
)
467 # They really need to be unique
468 assert name
not in entrypoints
469 entrypoints
[name
] = Entrypoint(name
, ret_type
, params
, guard
)
471 for feature
in doc
.findall('./feature'):
472 assert feature
.attrib
['api'] == 'vulkan'
473 version
= VkVersion(feature
.attrib
['number'])
474 if version
> MAX_API_VERSION
:
477 for command
in feature
.findall('./require/command'):
478 e
= entrypoints
[command
.attrib
['name']]
480 assert e
.core_version
is None
481 e
.core_version
= version
483 supported_exts
= dict((ext
.name
, ext
) for ext
in EXTENSIONS
)
484 for extension
in doc
.findall('.extensions/extension'):
485 ext_name
= extension
.attrib
['name']
486 if ext_name
not in supported_exts
:
489 if extension
.attrib
['supported'] != 'vulkan':
492 ext
= supported_exts
[ext_name
]
493 ext
.type = extension
.attrib
['type']
495 for command
in extension
.findall('./require/command'):
496 e
= entrypoints
[command
.attrib
['name']]
498 assert e
.core_version
is None
499 e
.extensions
.append(ext
)
501 return [e
for e
in entrypoints
.itervalues() if e
.enabled
]
504 def get_entrypoints_defines(doc
):
505 """Maps entry points to extension defines."""
506 entrypoints_to_defines
= {}
508 for extension
in doc
.findall('./extensions/extension[@platform]'):
509 platform
= extension
.attrib
['platform']
510 define
= 'VK_USE_PLATFORM_' + platform
.upper() + '_KHR'
512 for entrypoint
in extension
.findall('./require/command'):
513 fullname
= entrypoint
.attrib
['name']
514 entrypoints_to_defines
[fullname
] = define
516 return entrypoints_to_defines
520 parser
= argparse
.ArgumentParser()
521 parser
.add_argument('--outdir', help='Where to write the files.',
523 parser
.add_argument('--xml',
524 help='Vulkan API XML file.',
528 args
= parser
.parse_args()
532 for filename
in args
.xml_files
:
533 doc
= et
.parse(filename
)
534 entrypoints
+= get_entrypoints(doc
, get_entrypoints_defines(doc
),
535 start_index
=len(entrypoints
))
537 # Manually add CreateDmaBufImageINTEL for which we don't have an extension
539 entrypoints
.append(Entrypoint('vkCreateDmaBufImageINTEL', 'VkResult', [
540 EntrypointParam('VkDevice', 'device', 'VkDevice device'),
541 EntrypointParam('VkDmaBufImageCreateInfo', 'pCreateInfo',
542 'const VkDmaBufImageCreateInfo* pCreateInfo'),
543 EntrypointParam('VkAllocationCallbacks', 'pAllocator',
544 'const VkAllocationCallbacks* pAllocator'),
545 EntrypointParam('VkDeviceMemory', 'pMem', 'VkDeviceMemory* pMem'),
546 EntrypointParam('VkImage', 'pImage', 'VkImage* pImage')
549 strmap
= StringIntMap()
550 for num
, e
in enumerate(entrypoints
):
551 strmap
.add_string(e
.name
, num
)
555 # For outputting entrypoints.h we generate a anv_EntryPoint() prototype
558 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.h'), 'wb') as f
:
559 f
.write(TEMPLATE_H
.render(entrypoints
=entrypoints
,
561 filename
=os
.path
.basename(__file__
)))
562 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.c'), 'wb') as f
:
563 f
.write(TEMPLATE_C
.render(entrypoints
=entrypoints
,
566 filename
=os
.path
.basename(__file__
)))
568 # In the even there's an error this imports some helpers from mako
569 # to print a useful stack trace and prints it, then exits with
570 # status 1, if python is run with debug; otherwise it just raises
574 from mako
import exceptions
575 sys
.stderr
.write(exceptions
.text_error_template().render() + '\n')
580 if __name__
== '__main__':