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 libresoc_extensions
import VkVersion
, MAX_API_VERSION
, EXTENSIONS
35 # We currently don't use layers in libresoc, but keeping the ability for anv
36 # anyways, so we can use it for device groups.
42 TEMPLATE_H
= Template("""\
43 /* This file generated from ${filename}, don't edit directly. */
45 struct libresoc_instance_dispatch_table {
47 void *entrypoints[${len(instance_entrypoints)}];
49 % for e in instance_entrypoints:
50 % if e.guard is not None:
52 PFN_${e.name} ${e.name};
57 PFN_${e.name} ${e.name};
64 struct libresoc_physical_device_dispatch_table {
66 void *entrypoints[${len(physical_device_entrypoints)}];
68 % for e in physical_device_entrypoints:
69 % if e.guard is not None:
71 PFN_${e.name} ${e.name};
76 PFN_${e.name} ${e.name};
83 struct libresoc_device_dispatch_table {
85 void *entrypoints[${len(device_entrypoints)}];
87 % for e in device_entrypoints:
88 % if e.guard is not None:
90 PFN_${e.name} ${e.name};
95 PFN_${e.name} ${e.name};
102 extern const struct libresoc_instance_dispatch_table libresoc_instance_dispatch_table;
103 %for layer in LAYERS:
104 extern const struct libresoc_physical_device_dispatch_table ${layer}_physical_device_dispatch_table;
106 %for layer in LAYERS:
107 extern const struct libresoc_device_dispatch_table ${layer}_device_dispatch_table;
110 % for e in instance_entrypoints:
114 % if e.guard is not None:
117 ${e.return_type} ${e.prefixed_name('libresoc')}(${e.decl_params()});
118 % if e.guard is not None:
123 % for e in physical_device_entrypoints:
127 % if e.guard is not None:
130 % for layer in LAYERS:
131 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()});
133 % if e.guard is not None:
138 % for e in device_entrypoints:
142 % if e.guard is not None:
145 % for layer in LAYERS:
146 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()});
148 % if e.guard is not None:
152 """, output_encoding
='utf-8')
154 TEMPLATE_C
= Template(u
"""\
156 * Copyright © 2015 Intel Corporation
158 * Permission is hereby granted, free of charge, to any person obtaining a
159 * copy of this software and associated documentation files (the "Software"),
160 * to deal in the Software without restriction, including without limitation
161 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
162 * and/or sell copies of the Software, and to permit persons to whom the
163 * Software is furnished to do so, subject to the following conditions:
165 * The above copyright notice and this permission notice (including the next
166 * paragraph) shall be included in all copies or substantial portions of the
169 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
170 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
171 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
172 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
173 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
174 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
178 /* This file generated from ${filename}, don't edit directly. */
180 #include "libresoc_private.h"
182 #include "util/macros.h"
184 struct string_map_entry {
190 /* We use a big string constant to avoid lots of reloctions from the entry
191 * point table to lots of little strings. The entries in the entry point table
192 * store the index into this big string.
195 <%def name="strmap(strmap, prefix)">
196 static const char ${prefix}_strings[] =
197 % for s in strmap.sorted_strings:
202 static const struct string_map_entry ${prefix}_string_map_entries[] = {
203 % for s in strmap.sorted_strings:
204 { ${s.offset}, ${'{:0=#8x}'.format(s.hash)}, ${s.num} }, /* ${s.string} */
209 * size ${len(strmap.sorted_strings)} entries
210 * collisions entries:
211 % for i in range(10):
212 * ${i}${'+' if i == 9 else ' '} ${strmap.collisions[i]}
217 static const uint16_t ${prefix}_string_map[${strmap.hash_size}] = {
218 % for e in strmap.mapping:
219 ${ '{:0=#6x}'.format(e) if e >= 0 else 'none' },
224 ${prefix}_string_map_lookup(const char *str)
226 static const uint32_t prime_factor = ${strmap.prime_factor};
227 static const uint32_t prime_step = ${strmap.prime_step};
228 const struct string_map_entry *e;
234 for (p = str; *p; p++)
235 hash = hash * prime_factor + *p;
239 i = ${prefix}_string_map[h & ${strmap.hash_mask}];
242 e = &${prefix}_string_map_entries[i];
243 if (e->hash == hash && strcmp(str, ${prefix}_strings + e->name) == 0)
252 ${prefix}_entry_name(int num)
254 for (int i = 0; i < ARRAY_SIZE(${prefix}_string_map_entries); i++) {
255 if (${prefix}_string_map_entries[i].num == num)
256 return &${prefix}_strings[${prefix}_string_map_entries[i].name];
262 ${strmap(instance_strmap, 'instance')}
263 ${strmap(physical_device_strmap, 'physical_device')}
264 ${strmap(device_strmap, 'device')}
266 /* Weak aliases for all potential implementations. These will resolve to
267 * NULL if they're not defined, which lets the resolve_entrypoint() function
268 * either pick the correct entry point.
271 % for e in instance_entrypoints:
275 % if e.guard is not None:
278 ${e.return_type} ${e.prefixed_name('libresoc')}(${e.decl_params()}) __attribute__ ((weak));
279 % if e.guard is not None:
284 const struct libresoc_instance_dispatch_table libresoc_instance_dispatch_table = {
285 % for e in instance_entrypoints:
286 % if e.guard is not None:
289 .${e.name} = ${e.prefixed_name('libresoc')},
290 % if e.guard is not None:
296 % for layer in LAYERS:
297 % for e in physical_device_entrypoints:
301 % if e.guard is not None:
304 % if layer == 'libresoc':
305 ${e.return_type} __attribute__ ((weak))
306 ${e.prefixed_name('libresoc')}(${e.decl_params()})
308 % if e.params[0].type == 'VkPhysicalDevice':
309 LIBRESOC_FROM_HANDLE(libresoc_physical_device, libresoc_physical_device, ${e.params[0].name});
310 return libresoc_physical_device->dispatch.${e.name}(${e.call_params()});
312 assert(!"Unhandled device child trampoline case: ${e.params[0].type}");
316 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()}) __attribute__ ((weak));
318 % if e.guard is not None:
323 const struct libresoc_physical_device_dispatch_table ${layer}_physical_device_dispatch_table = {
324 % for e in physical_device_entrypoints:
325 % if e.guard is not None:
328 .${e.name} = ${e.prefixed_name(layer)},
329 % if e.guard is not None:
337 % for layer in LAYERS:
338 % for e in device_entrypoints:
342 % if e.guard is not None:
345 % if layer == 'libresoc':
346 ${e.return_type} __attribute__ ((weak))
347 ${e.prefixed_name('libresoc')}(${e.decl_params()})
349 % if e.params[0].type == 'VkDevice':
350 LIBRESOC_FROM_HANDLE(libresoc_device, libresoc_device, ${e.params[0].name});
351 return libresoc_device->dispatch.${e.name}(${e.call_params()});
352 % elif e.params[0].type == 'VkCommandBuffer':
353 LIBRESOC_FROM_HANDLE(libresoc_cmd_buffer, libresoc_cmd_buffer, ${e.params[0].name});
354 return libresoc_cmd_buffer->device->dispatch.${e.name}(${e.call_params()});
355 % elif e.params[0].type == 'VkQueue':
356 LIBRESOC_FROM_HANDLE(libresoc_queue, libresoc_queue, ${e.params[0].name});
357 return libresoc_queue->device->dispatch.${e.name}(${e.call_params()});
359 assert(!"Unhandled device child trampoline case: ${e.params[0].type}");
363 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()}) __attribute__ ((weak));
365 % if e.guard is not None:
370 const struct libresoc_device_dispatch_table ${layer}_device_dispatch_table = {
371 % for e in device_entrypoints:
372 % if e.guard is not None:
375 .${e.name} = ${e.prefixed_name(layer)},
376 % if e.guard is not None:
384 /** Return true if the core version or extension in which the given entrypoint
385 * is defined is enabled.
387 * If device is NULL, all device extensions are considered enabled.
390 libresoc_instance_entrypoint_is_enabled(int index, uint32_t core_version,
391 const struct libresoc_instance_extension_table *instance)
394 % for e in instance_entrypoints:
398 return ${e.core_version.c_vk_version()} <= core_version;
400 % for ext in e.extensions:
401 % if ext.type == 'instance':
402 if (instance->${ext.name[3:]}) return true;
404 /* All device extensions are considered enabled at the instance level */
418 /** Return true if the core version or extension in which the given entrypoint
419 * is defined is enabled.
421 * If device is NULL, all device extensions are considered enabled.
424 libresoc_physical_device_entrypoint_is_enabled(int index, uint32_t core_version,
425 const struct libresoc_instance_extension_table *instance)
428 % for e in physical_device_entrypoints:
432 return ${e.core_version.c_vk_version()} <= core_version;
434 % for ext in e.extensions:
435 % if ext.type == 'instance':
436 if (instance->${ext.name[3:]}) return true;
438 /* All device extensions are considered enabled at the instance level */
452 /** Return true if the core version or extension in which the given entrypoint
453 * is defined is enabled.
455 * If device is NULL, all device extensions are considered enabled.
458 libresoc_device_entrypoint_is_enabled(int index, uint32_t core_version,
459 const struct libresoc_instance_extension_table *instance,
460 const struct libresoc_device_extension_table *device)
463 % for e in device_entrypoints:
467 return ${e.core_version.c_vk_version()} <= core_version;
469 % for ext in e.extensions:
470 % if ext.type == 'instance':
473 if (!device || device->${ext.name[3:]}) return true;
487 libresoc_get_instance_entrypoint_index(const char *name)
489 return instance_string_map_lookup(name);
493 libresoc_get_physical_device_entrypoint_index(const char *name)
495 return physical_device_string_map_lookup(name);
499 libresoc_get_device_entrypoint_index(const char *name)
501 return device_string_map_lookup(name);
505 libresoc_get_instance_entry_name(int index)
507 return instance_entry_name(index);
511 libresoc_get_physical_device_entry_name(int index)
513 return physical_device_entry_name(index);
517 libresoc_get_device_entry_name(int index)
519 return device_entry_name(index);
523 libresoc_lookup_entrypoint(const char *name)
525 int idx = libresoc_get_instance_entrypoint_index(name);
527 return libresoc_instance_dispatch_table.entrypoints[idx];
529 idx = libresoc_get_physical_device_entrypoint_index(name);
531 return libresoc_physical_device_dispatch_table.entrypoints[idx];
533 idx = libresoc_get_device_entrypoint_index(name);
535 return libresoc_device_dispatch_table.entrypoints[idx];
538 }""", output_encoding
='utf-8')
542 PRIME_FACTOR
= 5024183
545 class StringIntMapEntry(object):
546 def __init__(self
, string
, num
):
550 # Calculate the same hash value that we will calculate in C.
553 h
= ((h
* PRIME_FACTOR
) + ord(c
)) & U32_MASK
558 def round_to_pow2(x
):
559 return 2**int(math
.ceil(math
.log(x
, 2)))
561 class StringIntMap(object):
564 self
.strings
= dict()
566 def add_string(self
, string
, num
):
567 assert not self
.baked
568 assert string
not in self
.strings
569 assert 0 <= num
< 2**31
570 self
.strings
[string
] = StringIntMapEntry(string
, num
)
573 self
.sorted_strings
= \
574 sorted(self
.strings
.values(), key
=lambda x
: x
.string
)
576 for entry
in self
.sorted_strings
:
577 entry
.offset
= offset
578 offset
+= len(entry
.string
) + 1
580 # Save off some values that we'll need in C
581 self
.hash_size
= round_to_pow2(len(self
.strings
) * 1.25)
582 self
.hash_mask
= self
.hash_size
- 1
583 self
.prime_factor
= PRIME_FACTOR
584 self
.prime_step
= PRIME_STEP
586 self
.mapping
= [-1] * self
.hash_size
587 self
.collisions
= [0] * 10
588 for idx
, s
in enumerate(self
.sorted_strings
):
591 while self
.mapping
[h
& self
.hash_mask
] >= 0:
594 self
.collisions
[min(level
, 9)] += 1
595 self
.mapping
[h
& self
.hash_mask
] = idx
597 EntrypointParam
= namedtuple('EntrypointParam', 'type name decl')
599 class EntrypointBase(object):
600 def __init__(self
, name
):
606 # Extensions which require this entrypoint
607 self
.core_version
= None
610 class Entrypoint(EntrypointBase
):
611 def __init__(self
, name
, return_type
, params
, guard
=None):
612 super(Entrypoint
, self
).__init
__(name
)
613 self
.return_type
= return_type
617 def is_physical_device_entrypoint(self
):
618 return self
.params
[0].type in ('VkPhysicalDevice', )
620 def is_device_entrypoint(self
):
621 return self
.params
[0].type in ('VkDevice', 'VkCommandBuffer', 'VkQueue')
623 def prefixed_name(self
, prefix
):
624 assert self
.name
.startswith('vk')
625 return prefix
+ '_' + self
.name
[2:]
627 def decl_params(self
):
628 return ', '.join(p
.decl
for p
in self
.params
)
630 def call_params(self
):
631 return ', '.join(p
.name
for p
in self
.params
)
633 class EntrypointAlias(EntrypointBase
):
634 def __init__(self
, name
, entrypoint
):
635 super(EntrypointAlias
, self
).__init
__(name
)
636 self
.alias
= entrypoint
638 def is_physical_device_entrypoint(self
):
639 return self
.alias
.is_physical_device_entrypoint()
641 def is_device_entrypoint(self
):
642 return self
.alias
.is_device_entrypoint()
644 def prefixed_name(self
, prefix
):
645 return self
.alias
.prefixed_name(prefix
)
647 def get_entrypoints(doc
, entrypoints_to_defines
):
648 """Extract the entry points from the registry."""
649 entrypoints
= OrderedDict()
651 for command
in doc
.findall('./commands/command'):
652 if 'alias' in command
.attrib
:
653 alias
= command
.attrib
['name']
654 target
= command
.attrib
['alias']
655 entrypoints
[alias
] = EntrypointAlias(alias
, entrypoints
[target
])
657 name
= command
.find('./proto/name').text
658 ret_type
= command
.find('./proto/type').text
659 params
= [EntrypointParam(
660 type=p
.find('./type').text
,
661 name
=p
.find('./name').text
,
662 decl
=''.join(p
.itertext())
663 ) for p
in command
.findall('./param')]
664 guard
= entrypoints_to_defines
.get(name
)
665 # They really need to be unique
666 assert name
not in entrypoints
667 entrypoints
[name
] = Entrypoint(name
, ret_type
, params
, guard
)
669 for feature
in doc
.findall('./feature'):
670 assert feature
.attrib
['api'] == 'vulkan'
671 version
= VkVersion(feature
.attrib
['number'])
672 if version
> MAX_API_VERSION
:
675 for command
in feature
.findall('./require/command'):
676 e
= entrypoints
[command
.attrib
['name']]
678 assert e
.core_version
is None
679 e
.core_version
= version
681 supported_exts
= dict((ext
.name
, ext
) for ext
in EXTENSIONS
)
682 for extension
in doc
.findall('.extensions/extension'):
683 ext_name
= extension
.attrib
['name']
684 if ext_name
not in supported_exts
:
687 ext
= supported_exts
[ext_name
]
688 ext
.type = extension
.attrib
['type']
690 for command
in extension
.findall('./require/command'):
691 e
= entrypoints
[command
.attrib
['name']]
693 assert e
.core_version
is None
694 e
.extensions
.append(ext
)
696 return [e
for e
in entrypoints
.values() if e
.enabled
]
699 def get_entrypoints_defines(doc
):
700 """Maps entry points to extension defines."""
701 entrypoints_to_defines
= {}
704 for platform
in doc
.findall('./platforms/platform'):
705 name
= platform
.attrib
['name']
706 define
= platform
.attrib
['protect']
707 platform_define
[name
] = define
709 for extension
in doc
.findall('./extensions/extension[@platform]'):
710 platform
= extension
.attrib
['platform']
711 define
= platform_define
[platform
]
713 for entrypoint
in extension
.findall('./require/command'):
714 fullname
= entrypoint
.attrib
['name']
715 entrypoints_to_defines
[fullname
] = define
717 return entrypoints_to_defines
721 parser
= argparse
.ArgumentParser()
722 parser
.add_argument('--outdir', help='Where to write the files.',
724 parser
.add_argument('--xml',
725 help='Vulkan API XML file.',
729 args
= parser
.parse_args()
733 for filename
in args
.xml_files
:
734 doc
= et
.parse(filename
)
735 entrypoints
+= get_entrypoints(doc
, get_entrypoints_defines(doc
))
737 device_entrypoints
= []
738 physical_device_entrypoints
= []
739 instance_entrypoints
= []
740 for e
in entrypoints
:
741 if e
.is_device_entrypoint():
742 device_entrypoints
.append(e
)
743 elif e
.is_physical_device_entrypoint():
744 physical_device_entrypoints
.append(e
)
746 instance_entrypoints
.append(e
)
748 device_strmap
= StringIntMap()
749 for num
, e
in enumerate(device_entrypoints
):
750 device_strmap
.add_string(e
.name
, num
)
754 physical_device_strmap
= StringIntMap()
755 for num
, e
in enumerate(physical_device_entrypoints
):
756 physical_device_strmap
.add_string(e
.name
, num
)
758 physical_device_strmap
.bake()
760 instance_strmap
= StringIntMap()
761 for num
, e
in enumerate(instance_entrypoints
):
762 instance_strmap
.add_string(e
.name
, num
)
764 instance_strmap
.bake()
766 # For outputting entrypoints.h we generate a libresoc_EntryPoint() prototype
769 with
open(os
.path
.join(args
.outdir
, 'libresoc_entrypoints.h'), 'wb') as f
:
770 f
.write(TEMPLATE_H
.render(instance_entrypoints
=instance_entrypoints
,
771 physical_device_entrypoints
=physical_device_entrypoints
,
772 device_entrypoints
=device_entrypoints
,
774 filename
=os
.path
.basename(__file__
)))
775 with
open(os
.path
.join(args
.outdir
, 'libresoc_entrypoints.c'), 'wb') as f
:
776 f
.write(TEMPLATE_C
.render(instance_entrypoints
=instance_entrypoints
,
777 physical_device_entrypoints
=physical_device_entrypoints
,
778 device_entrypoints
=device_entrypoints
,
780 instance_strmap
=instance_strmap
,
781 physical_device_strmap
=physical_device_strmap
,
782 device_strmap
=device_strmap
,
783 filename
=os
.path
.basename(__file__
)))
785 # In the event there's an error, this imports some helpers from mako
786 # to print a useful stack trace and prints it, then exits with
787 # status 1, if python is run with debug; otherwise it just raises
791 from mako
import exceptions
792 sys
.stderr
.write(exceptions
.text_error_template().render() + '\n')
797 if __name__
== '__main__':