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 radv_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
41 # We currently don't use layers in radv, but keeping the ability for anv
42 # anyways, so we can use it for device groups.
47 TEMPLATE_H
= Template("""\
48 /* This file generated from ${filename}, don't edit directly. */
50 struct radv_instance_dispatch_table {
52 void *entrypoints[${len(instance_entrypoints)}];
54 % for e in instance_entrypoints:
55 % if e.guard is not None:
57 PFN_${e.name} ${e.name};
62 PFN_${e.name} ${e.name};
69 struct radv_physical_device_dispatch_table {
71 void *entrypoints[${len(physical_device_entrypoints)}];
73 % for e in physical_device_entrypoints:
74 % if e.guard is not None:
76 PFN_${e.name} ${e.name};
81 PFN_${e.name} ${e.name};
88 struct radv_device_dispatch_table {
90 void *entrypoints[${len(device_entrypoints)}];
92 % for e in device_entrypoints:
93 % if e.guard is not None:
95 PFN_${e.name} ${e.name};
100 PFN_${e.name} ${e.name};
107 extern const struct radv_instance_dispatch_table radv_instance_dispatch_table;
108 %for layer in LAYERS:
109 extern const struct radv_physical_device_dispatch_table ${layer}_physical_device_dispatch_table;
111 %for layer in LAYERS:
112 extern const struct radv_device_dispatch_table ${layer}_device_dispatch_table;
115 % for e in instance_entrypoints:
116 % if e.alias and e.alias.enabled:
119 % if e.guard is not None:
122 ${e.return_type} ${e.prefixed_name('radv')}(${e.decl_params()});
123 % if e.guard is not None:
128 % for e in physical_device_entrypoints:
132 % if e.guard is not None:
135 % for layer in LAYERS:
136 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()});
138 % if e.guard is not None:
143 % for e in device_entrypoints:
144 % if e.alias and e.alias.enabled:
147 % if e.guard is not None:
150 % for layer in LAYERS:
151 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()});
153 % if e.guard is not None:
157 """, output_encoding
='utf-8')
159 TEMPLATE_C
= Template(u
"""\
161 * Copyright © 2015 Intel Corporation
163 * Permission is hereby granted, free of charge, to any person obtaining a
164 * copy of this software and associated documentation files (the "Software"),
165 * to deal in the Software without restriction, including without limitation
166 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
167 * and/or sell copies of the Software, and to permit persons to whom the
168 * Software is furnished to do so, subject to the following conditions:
170 * The above copyright notice and this permission notice (including the next
171 * paragraph) shall be included in all copies or substantial portions of the
174 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
175 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
176 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
177 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
178 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
179 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
183 /* This file generated from ${filename}, don't edit directly. */
185 #include "radv_private.h"
187 #include "util/macros.h"
189 struct string_map_entry {
195 /* We use a big string constant to avoid lots of reloctions from the entry
196 * point table to lots of little strings. The entries in the entry point table
197 * store the index into this big string.
200 <%def name="strmap(strmap, prefix)">
201 static const char ${prefix}_strings[] =
202 % for s in strmap.sorted_strings:
207 static const struct string_map_entry ${prefix}_string_map_entries[] = {
208 % for s in strmap.sorted_strings:
209 { ${s.offset}, ${'{:0=#8x}'.format(s.hash)}, ${s.num} }, /* ${s.string} */
214 * size ${len(strmap.sorted_strings)} entries
215 * collisions entries:
216 % for i in range(10):
217 * ${i}${'+' if i == 9 else ' '} ${strmap.collisions[i]}
222 static const uint16_t ${prefix}_string_map[${strmap.hash_size}] = {
223 % for e in strmap.mapping:
224 ${ '{:0=#6x}'.format(e) if e >= 0 else 'none' },
229 ${prefix}_string_map_lookup(const char *str)
231 static const uint32_t prime_factor = ${strmap.prime_factor};
232 static const uint32_t prime_step = ${strmap.prime_step};
233 const struct string_map_entry *e;
239 for (p = str; *p; p++)
240 hash = hash * prime_factor + *p;
244 i = ${prefix}_string_map[h & ${strmap.hash_mask}];
247 e = &${prefix}_string_map_entries[i];
248 if (e->hash == hash && strcmp(str, ${prefix}_strings + e->name) == 0)
257 ${prefix}_entry_name(int num)
259 for (int i = 0; i < ARRAY_SIZE(${prefix}_string_map_entries); i++) {
260 if (${prefix}_string_map_entries[i].num == num)
261 return &${prefix}_strings[${prefix}_string_map_entries[i].name];
267 ${strmap(instance_strmap, 'instance')}
268 ${strmap(physical_device_strmap, 'physical_device')}
269 ${strmap(device_strmap, 'device')}
271 /* Weak aliases for all potential implementations. These will resolve to
272 * NULL if they're not defined, which lets the resolve_entrypoint() function
273 * either pick the correct entry point.
276 % for e in instance_entrypoints:
277 % if e.alias and e.alias.enabled:
280 % if e.guard is not None:
283 ${e.return_type} ${e.prefixed_name('radv')}(${e.decl_params()}) __attribute__ ((weak));
284 % if e.guard is not None:
289 const struct radv_instance_dispatch_table radv_instance_dispatch_table = {
290 % for e in instance_entrypoints:
291 % if e.guard is not None:
294 .${e.name} = ${e.prefixed_name('radv')},
295 % if e.guard is not None:
301 % for e in physical_device_entrypoints:
302 % if e.alias and e.alias.enabled:
305 % if e.guard is not None:
308 ${e.return_type} ${e.prefixed_name('radv')}(${e.decl_params()}) __attribute__ ((weak));
309 % if e.guard is not None:
314 const struct radv_physical_device_dispatch_table radv_physical_device_dispatch_table = {
315 % for e in physical_device_entrypoints:
316 % if e.guard is not None:
319 .${e.name} = ${e.prefixed_name('radv')},
320 % if e.guard is not None:
327 % for layer in LAYERS:
328 % for e in device_entrypoints:
329 % if e.alias and e.alias.enabled:
332 % if e.guard is not None:
335 % if layer == 'radv':
336 ${e.return_type} __attribute__ ((weak))
337 ${e.prefixed_name('radv')}(${e.decl_params()})
339 % if e.params[0].type == 'VkDevice':
340 RADV_FROM_HANDLE(radv_device, radv_device, ${e.params[0].name});
341 return radv_device->dispatch.${e.name}(${e.call_params()});
342 % elif e.params[0].type == 'VkCommandBuffer':
343 RADV_FROM_HANDLE(radv_cmd_buffer, radv_cmd_buffer, ${e.params[0].name});
344 return radv_cmd_buffer->device->dispatch.${e.name}(${e.call_params()});
345 % elif e.params[0].type == 'VkQueue':
346 RADV_FROM_HANDLE(radv_queue, radv_queue, ${e.params[0].name});
347 return radv_queue->device->dispatch.${e.name}(${e.call_params()});
349 assert(!"Unhandled device child trampoline case: ${e.params[0].type}");
353 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()}) __attribute__ ((weak));
355 % if e.guard is not None:
360 const struct radv_device_dispatch_table ${layer}_device_dispatch_table = {
361 % for e in device_entrypoints:
362 % if e.guard is not None:
365 .${e.name} = ${e.prefixed_name(layer)},
366 % if e.guard is not None:
374 /** Return true if the core version or extension in which the given entrypoint
375 * is defined is enabled.
377 * If device is NULL, all device extensions are considered enabled.
380 radv_instance_entrypoint_is_enabled(int index, uint32_t core_version,
381 const struct radv_instance_extension_table *instance)
384 % for e in instance_entrypoints:
388 return ${e.core_version.c_vk_version()} <= core_version;
390 % for ext in e.extensions:
391 % if ext.type == 'instance':
392 if (instance->${ext.name[3:]}) return true;
394 /* All device extensions are considered enabled at the instance level */
408 /** Return true if the core version or extension in which the given entrypoint
409 * is defined is enabled.
411 * If device is NULL, all device extensions are considered enabled.
414 radv_physical_device_entrypoint_is_enabled(int index, uint32_t core_version,
415 const struct radv_instance_extension_table *instance)
418 % for e in physical_device_entrypoints:
422 return ${e.core_version.c_vk_version()} <= core_version;
424 % for ext in e.extensions:
425 % if ext.type == 'instance':
426 if (instance->${ext.name[3:]}) return true;
428 /* All device extensions are considered enabled at the instance level */
442 /** Return true if the core version or extension in which the given entrypoint
443 * is defined is enabled.
445 * If device is NULL, all device extensions are considered enabled.
448 radv_device_entrypoint_is_enabled(int index, uint32_t core_version,
449 const struct radv_instance_extension_table *instance,
450 const struct radv_device_extension_table *device)
453 % for e in device_entrypoints:
457 return ${e.core_version.c_vk_version()} <= core_version;
459 % for ext in e.extensions:
460 % if ext.type == 'instance':
463 if (!device || device->${ext.name[3:]}) return true;
477 radv_get_instance_entrypoint_index(const char *name)
479 return instance_string_map_lookup(name);
483 radv_get_physical_device_entrypoint_index(const char *name)
485 return physical_device_string_map_lookup(name);
489 radv_get_device_entrypoint_index(const char *name)
491 return device_string_map_lookup(name);
495 radv_get_instance_entry_name(int index)
497 return instance_entry_name(index);
501 radv_get_physical_device_entry_name(int index)
503 return physical_device_entry_name(index);
507 radv_get_device_entry_name(int index)
509 return device_entry_name(index);
512 static void * __attribute__ ((noinline))
513 radv_resolve_device_entrypoint(uint32_t index)
515 return radv_device_dispatch_table.entrypoints[index];
519 radv_lookup_entrypoint(const char *name)
521 int idx = radv_get_instance_entrypoint_index(name);
523 return radv_instance_dispatch_table.entrypoints[idx];
525 idx = radv_get_physical_device_entrypoint_index(name);
527 return radv_physical_device_dispatch_table.entrypoints[idx];
529 idx = radv_get_device_entrypoint_index(name);
531 return radv_resolve_device_entrypoint(idx);
534 }""", output_encoding
='utf-8')
538 PRIME_FACTOR
= 5024183
541 def round_to_pow2(x
):
542 return 2**int(math
.ceil(math
.log(x
, 2)))
544 class StringIntMapEntry(object):
545 def __init__(self
, string
, num
):
549 # Calculate the same hash value that we will calculate in C.
552 h
= ((h
* PRIME_FACTOR
) + ord(c
)) & U32_MASK
557 class StringIntMap(object):
560 self
.strings
= dict()
562 def add_string(self
, string
, num
):
563 assert not self
.baked
564 assert string
not in self
.strings
565 assert num
>= 0 and num
< 2**31
566 self
.strings
[string
] = StringIntMapEntry(string
, num
)
569 self
.sorted_strings
= \
570 sorted(self
.strings
.values(), key
=lambda x
: x
.string
)
572 for entry
in self
.sorted_strings
:
573 entry
.offset
= offset
574 offset
+= len(entry
.string
) + 1
576 # Save off some values that we'll need in C
577 self
.hash_size
= round_to_pow2(len(self
.strings
) * 1.25)
578 self
.hash_mask
= self
.hash_size
- 1
579 self
.prime_factor
= PRIME_FACTOR
580 self
.prime_step
= PRIME_STEP
582 self
.mapping
= [-1] * self
.hash_size
583 self
.collisions
= [0] * 10
584 for idx
, s
in enumerate(self
.sorted_strings
):
587 while self
.mapping
[h
& self
.hash_mask
] >= 0:
590 self
.collisions
[min(level
, 9)] += 1
591 self
.mapping
[h
& self
.hash_mask
] = idx
593 EntrypointParam
= namedtuple('EntrypointParam', 'type name decl')
595 class EntrypointBase(object):
596 def __init__(self
, name
):
602 # Extensions which require this entrypoint
603 self
.core_version
= None
606 def prefixed_name(self
, prefix
):
607 assert self
.name
.startswith('vk')
608 return prefix
+ '_' + self
.name
[2:]
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 decl_params(self
):
624 return ', '.join(p
.decl
for p
in self
.params
)
626 def call_params(self
):
627 return ', '.join(p
.name
for p
in self
.params
)
629 class EntrypointAlias(EntrypointBase
):
630 def __init__(self
, name
, entrypoint
):
631 super(EntrypointAlias
, self
).__init
__(name
)
632 self
.alias
= entrypoint
634 def is_physical_device_entrypoint(self
):
635 return self
.alias
.is_physical_device_entrypoint()
637 def is_device_entrypoint(self
):
638 return self
.alias
.is_device_entrypoint()
640 def prefixed_name(self
, prefix
):
641 if self
.alias
.enabled
:
642 return self
.alias
.prefixed_name(prefix
)
643 return super(EntrypointAlias
, self
).prefixed_name(prefix
)
647 return self
.alias
.params
650 def return_type(self
):
651 return self
.alias
.return_type
653 def decl_params(self
):
654 return self
.alias
.decl_params()
656 def call_params(self
):
657 return self
.alias
.call_params()
659 def get_entrypoints(doc
, entrypoints_to_defines
):
660 """Extract the entry points from the registry."""
661 entrypoints
= OrderedDict()
663 for command
in doc
.findall('./commands/command'):
664 if 'alias' in command
.attrib
:
665 alias
= command
.attrib
['name']
666 target
= command
.attrib
['alias']
667 entrypoints
[alias
] = EntrypointAlias(alias
, entrypoints
[target
])
669 name
= command
.find('./proto/name').text
670 ret_type
= command
.find('./proto/type').text
671 params
= [EntrypointParam(
672 type = p
.find('./type').text
,
673 name
= p
.find('./name').text
,
674 decl
= ''.join(p
.itertext())
675 ) for p
in command
.findall('./param')]
676 guard
= entrypoints_to_defines
.get(name
)
677 # They really need to be unique
678 assert name
not in entrypoints
679 entrypoints
[name
] = Entrypoint(name
, ret_type
, params
, guard
)
681 for feature
in doc
.findall('./feature'):
682 assert feature
.attrib
['api'] == 'vulkan'
683 version
= VkVersion(feature
.attrib
['number'])
684 if version
> MAX_API_VERSION
:
687 for command
in feature
.findall('./require/command'):
688 e
= entrypoints
[command
.attrib
['name']]
690 assert e
.core_version
is None
691 e
.core_version
= version
693 supported_exts
= dict((ext
.name
, ext
) for ext
in EXTENSIONS
)
694 for extension
in doc
.findall('.extensions/extension'):
695 ext_name
= extension
.attrib
['name']
696 if ext_name
not in supported_exts
:
699 ext
= supported_exts
[ext_name
]
700 ext
.type = extension
.attrib
['type']
702 for command
in extension
.findall('./require/command'):
703 e
= entrypoints
[command
.attrib
['name']]
705 assert e
.core_version
is None
706 e
.extensions
.append(ext
)
708 # if the base command is not supported by the driver yet, don't alias aliases
709 for e
in entrypoints
.values():
710 if e
.alias
and not e
.alias
.enabled
:
711 e_clone
= copy
.deepcopy(e
.alias
)
712 e_clone
.enabled
= True
713 e_clone
.name
= e
.name
714 entrypoints
[e
.name
] = e_clone
716 return [e
for e
in entrypoints
.values() if e
.enabled
]
719 def get_entrypoints_defines(doc
):
720 """Maps entry points to extension defines."""
721 entrypoints_to_defines
= {}
724 for platform
in doc
.findall('./platforms/platform'):
725 name
= platform
.attrib
['name']
726 define
= platform
.attrib
['protect']
727 platform_define
[name
] = define
729 for extension
in doc
.findall('./extensions/extension[@platform]'):
730 platform
= extension
.attrib
['platform']
731 define
= platform_define
[platform
]
733 for entrypoint
in extension
.findall('./require/command'):
734 fullname
= entrypoint
.attrib
['name']
735 entrypoints_to_defines
[fullname
] = define
737 return entrypoints_to_defines
740 parser
= argparse
.ArgumentParser()
741 parser
.add_argument('--outdir', help='Where to write the files.',
743 parser
.add_argument('--xml',
744 help='Vulkan API XML file.',
748 args
= parser
.parse_args()
752 for filename
in args
.xml_files
:
753 doc
= et
.parse(filename
)
754 entrypoints
+= get_entrypoints(doc
, get_entrypoints_defines(doc
))
756 device_entrypoints
= []
757 physical_device_entrypoints
= []
758 instance_entrypoints
= []
759 for e
in entrypoints
:
760 if e
.is_device_entrypoint():
761 device_entrypoints
.append(e
)
762 elif e
.is_physical_device_entrypoint():
763 physical_device_entrypoints
.append(e
)
765 instance_entrypoints
.append(e
)
767 device_strmap
= StringIntMap()
768 for num
, e
in enumerate(device_entrypoints
):
769 device_strmap
.add_string(e
.name
, num
)
773 physical_device_strmap
= StringIntMap()
774 for num
, e
in enumerate(physical_device_entrypoints
):
775 physical_device_strmap
.add_string(e
.name
, num
)
777 physical_device_strmap
.bake()
779 instance_strmap
= StringIntMap()
780 for num
, e
in enumerate(instance_entrypoints
):
781 instance_strmap
.add_string(e
.name
, num
)
783 instance_strmap
.bake()
785 # For outputting entrypoints.h we generate a radv_EntryPoint() prototype
788 with
open(os
.path
.join(args
.outdir
, 'radv_entrypoints.h'), 'wb') as f
:
789 f
.write(TEMPLATE_H
.render(instance_entrypoints
=instance_entrypoints
,
790 physical_device_entrypoints
=physical_device_entrypoints
,
791 device_entrypoints
=device_entrypoints
,
793 filename
=os
.path
.basename(__file__
)))
794 with
open(os
.path
.join(args
.outdir
, 'radv_entrypoints.c'), 'wb') as f
:
795 f
.write(TEMPLATE_C
.render(instance_entrypoints
=instance_entrypoints
,
796 physical_device_entrypoints
=physical_device_entrypoints
,
797 device_entrypoints
=device_entrypoints
,
799 instance_strmap
=instance_strmap
,
800 physical_device_strmap
=physical_device_strmap
,
801 device_strmap
=device_strmap
,
802 filename
=os
.path
.basename(__file__
)))
804 # In the event there's an error, this imports some helpers from mako
805 # to print a useful stack trace and prints it, then exits with
806 # status 1, if python is run with debug; otherwise it just raises
810 from mako
import exceptions
811 sys
.stderr
.write(exceptions
.text_error_template().render() + '\n')
816 if __name__
== '__main__':