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 VkVersion
, MAX_API_VERSION
, EXTENSIONS
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
51 TEMPLATE_H
= Template("""\
52 /* This file generated from ${filename}, don't edit directly. */
54 struct anv_instance_dispatch_table {
56 void *entrypoints[${len(instance_entrypoints)}];
58 % for e in instance_entrypoints:
59 % if e.guard is not None:
61 PFN_${e.name} ${e.name};
66 PFN_${e.name} ${e.name};
73 struct anv_physical_device_dispatch_table {
75 void *entrypoints[${len(physical_device_entrypoints)}];
77 % for e in physical_device_entrypoints:
78 % if e.guard is not None:
80 PFN_${e.name} ${e.name};
85 PFN_${e.name} ${e.name};
92 struct anv_device_dispatch_table {
94 void *entrypoints[${len(device_entrypoints)}];
96 % for e in device_entrypoints:
97 % if e.guard is not None:
99 PFN_${e.name} ${e.name};
104 PFN_${e.name} ${e.name};
111 extern const struct anv_instance_dispatch_table anv_instance_dispatch_table;
112 %for layer in LAYERS:
113 extern const struct anv_physical_device_dispatch_table ${layer}_physical_device_dispatch_table;
115 %for layer in LAYERS:
116 extern const struct anv_device_dispatch_table ${layer}_device_dispatch_table;
119 % for e in instance_entrypoints:
120 % if e.alias and e.alias.enabled:
123 % if e.guard is not None:
126 ${e.return_type} ${e.prefixed_name('anv')}(${e.decl_params()});
127 % if e.guard is not None:
132 % for e in physical_device_entrypoints:
136 % if e.guard is not None:
139 % for layer in LAYERS:
140 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()});
142 % if e.guard is not None:
147 % for e in device_entrypoints:
148 % if e.alias and e.alias.enabled:
151 % if e.guard is not None:
154 % for layer in LAYERS:
155 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()});
157 % if e.guard is not None:
161 """, output_encoding
='utf-8')
163 TEMPLATE_C
= Template(u
"""\
165 * Copyright © 2015 Intel Corporation
167 * Permission is hereby granted, free of charge, to any person obtaining a
168 * copy of this software and associated documentation files (the "Software"),
169 * to deal in the Software without restriction, including without limitation
170 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
171 * and/or sell copies of the Software, and to permit persons to whom the
172 * Software is furnished to do so, subject to the following conditions:
174 * The above copyright notice and this permission notice (including the next
175 * paragraph) shall be included in all copies or substantial portions of the
178 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
179 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
180 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
181 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
182 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
183 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
187 /* This file generated from ${filename}, don't edit directly. */
189 #include "anv_private.h"
191 #include "util/macros.h"
193 struct string_map_entry {
199 /* We use a big string constant to avoid lots of reloctions from the entry
200 * point table to lots of little strings. The entries in the entry point table
201 * store the index into this big string.
204 <%def name="strmap(strmap, prefix)">
205 static const char ${prefix}_strings[] =
206 % for s in strmap.sorted_strings:
211 static const struct string_map_entry ${prefix}_string_map_entries[] = {
212 % for s in strmap.sorted_strings:
213 { ${s.offset}, ${'{:0=#8x}'.format(s.hash)}, ${s.num} }, /* ${s.string} */
218 * size ${len(strmap.sorted_strings)} entries
219 * collisions entries:
220 % for i in range(10):
221 * ${i}${'+' if i == 9 else ' '} ${strmap.collisions[i]}
226 static const uint16_t ${prefix}_string_map[${strmap.hash_size}] = {
227 % for e in strmap.mapping:
228 ${ '{:0=#6x}'.format(e) if e >= 0 else 'none' },
233 ${prefix}_string_map_lookup(const char *str)
235 static const uint32_t prime_factor = ${strmap.prime_factor};
236 static const uint32_t prime_step = ${strmap.prime_step};
237 const struct string_map_entry *e;
243 for (p = str; *p; p++)
244 hash = hash * prime_factor + *p;
248 i = ${prefix}_string_map[h & ${strmap.hash_mask}];
251 e = &${prefix}_string_map_entries[i];
252 if (e->hash == hash && strcmp(str, ${prefix}_strings + e->name) == 0)
261 ${prefix}_entry_name(int num)
263 for (int i = 0; i < ARRAY_SIZE(${prefix}_string_map_entries); i++) {
264 if (${prefix}_string_map_entries[i].num == num)
265 return &${prefix}_strings[${prefix}_string_map_entries[i].name];
271 ${strmap(instance_strmap, 'instance')}
272 ${strmap(physical_device_strmap, 'physical_device')}
273 ${strmap(device_strmap, 'device')}
275 /* Weak aliases for all potential implementations. These will resolve to
276 * NULL if they're not defined, which lets the resolve_entrypoint() function
277 * either pick the correct entry point.
280 % for e in instance_entrypoints:
281 % if e.alias and e.alias.enabled:
284 % if e.guard is not None:
287 ${e.return_type} ${e.prefixed_name('anv')}(${e.decl_params()}) __attribute__ ((weak));
288 % if e.guard is not None:
293 const struct anv_instance_dispatch_table anv_instance_dispatch_table = {
294 % for e in instance_entrypoints:
295 % if e.guard is not None:
298 .${e.name} = ${e.prefixed_name('anv')},
299 % if e.guard is not None:
305 % for layer in LAYERS:
306 % for e in physical_device_entrypoints:
310 % if e.guard is not None:
314 ${e.return_type} __attribute__ ((weak))
315 ${e.prefixed_name('anv')}(${e.decl_params()})
317 % if e.params[0].type == 'VkPhysicalDevice':
318 ANV_FROM_HANDLE(anv_physical_device, anv_physical_device, ${e.params[0].name});
319 return anv_physical_device->dispatch.${e.name}(${e.call_params()});
321 assert(!"Unhandled device child trampoline case: ${e.params[0].type}");
325 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()}) __attribute__ ((weak));
327 % if e.guard is not None:
332 const struct anv_physical_device_dispatch_table ${layer}_physical_device_dispatch_table = {
333 % for e in physical_device_entrypoints:
334 % if e.guard is not None:
337 .${e.name} = ${e.prefixed_name(layer)},
338 % if e.guard is not None:
346 % for layer in LAYERS:
347 % for e in device_entrypoints:
348 % if e.alias and e.alias.enabled:
351 % if e.guard is not None:
355 ${e.return_type} __attribute__ ((weak))
356 ${e.prefixed_name('anv')}(${e.decl_params()})
358 % if e.params[0].type == 'VkDevice':
359 ANV_FROM_HANDLE(anv_device, anv_device, ${e.params[0].name});
360 return anv_device->dispatch.${e.name}(${e.call_params()});
361 % elif e.params[0].type == 'VkCommandBuffer':
362 ANV_FROM_HANDLE(anv_cmd_buffer, anv_cmd_buffer, ${e.params[0].name});
363 return anv_cmd_buffer->device->dispatch.${e.name}(${e.call_params()});
364 % elif e.params[0].type == 'VkQueue':
365 ANV_FROM_HANDLE(anv_queue, anv_queue, ${e.params[0].name});
366 return anv_queue->device->dispatch.${e.name}(${e.call_params()});
368 assert(!"Unhandled device child trampoline case: ${e.params[0].type}");
372 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()}) __attribute__ ((weak));
374 % if e.guard is not None:
379 const struct anv_device_dispatch_table ${layer}_device_dispatch_table = {
380 % for e in device_entrypoints:
381 % if e.guard is not None:
384 .${e.name} = ${e.prefixed_name(layer)},
385 % if e.guard is not None:
393 /** Return true if the core version or extension in which the given entrypoint
394 * is defined is enabled.
396 * If device is NULL, all device extensions are considered enabled.
399 anv_instance_entrypoint_is_enabled(int index, uint32_t core_version,
400 const struct anv_instance_extension_table *instance)
403 % for e in instance_entrypoints:
407 return ${e.core_version.c_vk_version()} <= core_version;
409 % for ext in e.extensions:
410 % if ext.type == 'instance':
411 if (instance->${ext.name[3:]}) return true;
413 /* All device extensions are considered enabled at the instance level */
427 /** Return true if the core version or extension in which the given entrypoint
428 * is defined is enabled.
430 * If device is NULL, all device extensions are considered enabled.
433 anv_physical_device_entrypoint_is_enabled(int index, uint32_t core_version,
434 const struct anv_instance_extension_table *instance)
437 % for e in physical_device_entrypoints:
441 return ${e.core_version.c_vk_version()} <= core_version;
443 % for ext in e.extensions:
444 % if ext.type == 'instance':
445 if (instance->${ext.name[3:]}) return true;
447 /* All device extensions are considered enabled at the instance level */
461 /** Return true if the core version or extension in which the given entrypoint
462 * is defined is enabled.
464 * If device is NULL, all device extensions are considered enabled.
467 anv_device_entrypoint_is_enabled(int index, uint32_t core_version,
468 const struct anv_instance_extension_table *instance,
469 const struct anv_device_extension_table *device)
472 % for e in device_entrypoints:
476 return ${e.core_version.c_vk_version()} <= core_version;
478 % for ext in e.extensions:
479 % if ext.type == 'instance':
482 if (!device || device->${ext.name[3:]}) return true;
496 anv_get_instance_entrypoint_index(const char *name)
498 return instance_string_map_lookup(name);
502 anv_get_physical_device_entrypoint_index(const char *name)
504 return physical_device_string_map_lookup(name);
508 anv_get_device_entrypoint_index(const char *name)
510 return device_string_map_lookup(name);
514 anv_get_instance_entry_name(int index)
516 return instance_entry_name(index);
520 anv_get_physical_device_entry_name(int index)
522 return physical_device_entry_name(index);
526 anv_get_device_entry_name(int index)
528 return device_entry_name(index);
531 static void * __attribute__ ((noinline))
532 anv_resolve_device_entrypoint(const struct gen_device_info *devinfo, uint32_t index)
534 const struct anv_device_dispatch_table *genX_table;
535 switch (devinfo->gen) {
537 genX_table = &gen12_device_dispatch_table;
540 genX_table = &gen11_device_dispatch_table;
543 genX_table = &gen10_device_dispatch_table;
546 genX_table = &gen9_device_dispatch_table;
549 genX_table = &gen8_device_dispatch_table;
552 if (devinfo->is_haswell)
553 genX_table = &gen75_device_dispatch_table;
555 genX_table = &gen7_device_dispatch_table;
558 unreachable("unsupported gen\\n");
561 if (genX_table->entrypoints[index])
562 return genX_table->entrypoints[index];
564 return anv_device_dispatch_table.entrypoints[index];
568 anv_lookup_entrypoint(const struct gen_device_info *devinfo, const char *name)
570 int idx = anv_get_instance_entrypoint_index(name);
572 return anv_instance_dispatch_table.entrypoints[idx];
574 idx = anv_get_physical_device_entrypoint_index(name);
576 return anv_physical_device_dispatch_table.entrypoints[idx];
578 idx = anv_get_device_entrypoint_index(name);
580 return anv_resolve_device_entrypoint(devinfo, idx);
583 }""", output_encoding
='utf-8')
587 PRIME_FACTOR
= 5024183
590 class StringIntMapEntry(object):
591 def __init__(self
, string
, num
):
595 # Calculate the same hash value that we will calculate in C.
598 h
= ((h
* PRIME_FACTOR
) + ord(c
)) & U32_MASK
603 def round_to_pow2(x
):
604 return 2**int(math
.ceil(math
.log(x
, 2)))
606 class StringIntMap(object):
609 self
.strings
= dict()
611 def add_string(self
, string
, num
):
612 assert not self
.baked
613 assert string
not in self
.strings
614 assert 0 <= num
< 2**31
615 self
.strings
[string
] = StringIntMapEntry(string
, num
)
618 self
.sorted_strings
= \
619 sorted(self
.strings
.values(), key
=lambda x
: x
.string
)
621 for entry
in self
.sorted_strings
:
622 entry
.offset
= offset
623 offset
+= len(entry
.string
) + 1
625 # Save off some values that we'll need in C
626 self
.hash_size
= round_to_pow2(len(self
.strings
) * 1.25)
627 self
.hash_mask
= self
.hash_size
- 1
628 self
.prime_factor
= PRIME_FACTOR
629 self
.prime_step
= PRIME_STEP
631 self
.mapping
= [-1] * self
.hash_size
632 self
.collisions
= [0] * 10
633 for idx
, s
in enumerate(self
.sorted_strings
):
636 while self
.mapping
[h
& self
.hash_mask
] >= 0:
639 self
.collisions
[min(level
, 9)] += 1
640 self
.mapping
[h
& self
.hash_mask
] = idx
642 EntrypointParam
= namedtuple('EntrypointParam', 'type name decl')
644 class EntrypointBase(object):
645 def __init__(self
, name
):
651 # Extensions which require this entrypoint
652 self
.core_version
= None
655 def prefixed_name(self
, prefix
):
656 assert self
.name
.startswith('vk')
657 return prefix
+ '_' + self
.name
[2:]
659 class Entrypoint(EntrypointBase
):
660 def __init__(self
, name
, return_type
, params
, guard
=None):
661 super(Entrypoint
, self
).__init
__(name
)
662 self
.return_type
= return_type
666 def is_physical_device_entrypoint(self
):
667 return self
.params
[0].type in ('VkPhysicalDevice', )
669 def is_device_entrypoint(self
):
670 return self
.params
[0].type in ('VkDevice', 'VkCommandBuffer', 'VkQueue')
672 def decl_params(self
):
673 return ', '.join(p
.decl
for p
in self
.params
)
675 def call_params(self
):
676 return ', '.join(p
.name
for p
in self
.params
)
678 class EntrypointAlias(EntrypointBase
):
679 def __init__(self
, name
, entrypoint
):
680 super(EntrypointAlias
, self
).__init
__(name
)
681 self
.alias
= entrypoint
683 def is_physical_device_entrypoint(self
):
684 return self
.alias
.is_physical_device_entrypoint()
686 def is_device_entrypoint(self
):
687 return self
.alias
.is_device_entrypoint()
689 def prefixed_name(self
, prefix
):
690 if self
.alias
.enabled
:
691 return self
.alias
.prefixed_name(prefix
)
692 return super(EntrypointAlias
, self
).prefixed_name(prefix
)
696 return self
.alias
.params
699 def return_type(self
):
700 return self
.alias
.return_type
702 def decl_params(self
):
703 return self
.alias
.decl_params()
705 def call_params(self
):
706 return self
.alias
.call_params()
708 def get_entrypoints(doc
, entrypoints_to_defines
):
709 """Extract the entry points from the registry."""
710 entrypoints
= OrderedDict()
712 for command
in doc
.findall('./commands/command'):
713 if 'alias' in command
.attrib
:
714 alias
= command
.attrib
['name']
715 target
= command
.attrib
['alias']
716 entrypoints
[alias
] = EntrypointAlias(alias
, entrypoints
[target
])
718 name
= command
.find('./proto/name').text
719 ret_type
= command
.find('./proto/type').text
720 params
= [EntrypointParam(
721 type=p
.find('./type').text
,
722 name
=p
.find('./name').text
,
723 decl
=''.join(p
.itertext())
724 ) for p
in command
.findall('./param')]
725 guard
= entrypoints_to_defines
.get(name
)
726 # They really need to be unique
727 assert name
not in entrypoints
728 entrypoints
[name
] = Entrypoint(name
, ret_type
, params
, guard
)
730 for feature
in doc
.findall('./feature'):
731 assert feature
.attrib
['api'] == 'vulkan'
732 version
= VkVersion(feature
.attrib
['number'])
733 if version
> MAX_API_VERSION
:
736 for command
in feature
.findall('./require/command'):
737 e
= entrypoints
[command
.attrib
['name']]
739 assert e
.core_version
is None
740 e
.core_version
= version
742 supported_exts
= dict((ext
.name
, ext
) for ext
in EXTENSIONS
)
743 for extension
in doc
.findall('.extensions/extension'):
744 ext_name
= extension
.attrib
['name']
745 if ext_name
not in supported_exts
:
748 ext
= supported_exts
[ext_name
]
749 ext
.type = extension
.attrib
['type']
751 for command
in extension
.findall('./require/command'):
752 e
= entrypoints
[command
.attrib
['name']]
754 assert e
.core_version
is None
755 e
.extensions
.append(ext
)
757 return [e
for e
in entrypoints
.values() if e
.enabled
]
760 def get_entrypoints_defines(doc
):
761 """Maps entry points to extension defines."""
762 entrypoints_to_defines
= {}
765 for platform
in doc
.findall('./platforms/platform'):
766 name
= platform
.attrib
['name']
767 define
= platform
.attrib
['protect']
768 platform_define
[name
] = define
770 for extension
in doc
.findall('./extensions/extension[@platform]'):
771 platform
= extension
.attrib
['platform']
772 define
= platform_define
[platform
]
774 for entrypoint
in extension
.findall('./require/command'):
775 fullname
= entrypoint
.attrib
['name']
776 entrypoints_to_defines
[fullname
] = define
778 return entrypoints_to_defines
782 parser
= argparse
.ArgumentParser()
783 parser
.add_argument('--outdir', help='Where to write the files.',
785 parser
.add_argument('--xml',
786 help='Vulkan API XML file.',
790 args
= parser
.parse_args()
794 for filename
in args
.xml_files
:
795 doc
= et
.parse(filename
)
796 entrypoints
+= get_entrypoints(doc
, get_entrypoints_defines(doc
))
798 # Manually add CreateDmaBufImageINTEL for which we don't have an extension
800 entrypoints
.append(Entrypoint('vkCreateDmaBufImageINTEL', 'VkResult', [
801 EntrypointParam('VkDevice', 'device', 'VkDevice device'),
802 EntrypointParam('VkDmaBufImageCreateInfo', 'pCreateInfo',
803 'const VkDmaBufImageCreateInfo* pCreateInfo'),
804 EntrypointParam('VkAllocationCallbacks', 'pAllocator',
805 'const VkAllocationCallbacks* pAllocator'),
806 EntrypointParam('VkDeviceMemory', 'pMem', 'VkDeviceMemory* pMem'),
807 EntrypointParam('VkImage', 'pImage', 'VkImage* pImage')
810 device_entrypoints
= []
811 physical_device_entrypoints
= []
812 instance_entrypoints
= []
813 for e
in entrypoints
:
814 if e
.is_device_entrypoint():
815 device_entrypoints
.append(e
)
816 elif e
.is_physical_device_entrypoint():
817 physical_device_entrypoints
.append(e
)
819 instance_entrypoints
.append(e
)
821 device_strmap
= StringIntMap()
822 for num
, e
in enumerate(device_entrypoints
):
823 device_strmap
.add_string(e
.name
, num
)
827 physical_device_strmap
= StringIntMap()
828 for num
, e
in enumerate(physical_device_entrypoints
):
829 physical_device_strmap
.add_string(e
.name
, num
)
831 physical_device_strmap
.bake()
833 instance_strmap
= StringIntMap()
834 for num
, e
in enumerate(instance_entrypoints
):
835 instance_strmap
.add_string(e
.name
, num
)
837 instance_strmap
.bake()
839 # For outputting entrypoints.h we generate a anv_EntryPoint() prototype
842 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.h'), 'wb') as f
:
843 f
.write(TEMPLATE_H
.render(instance_entrypoints
=instance_entrypoints
,
844 physical_device_entrypoints
=physical_device_entrypoints
,
845 device_entrypoints
=device_entrypoints
,
847 filename
=os
.path
.basename(__file__
)))
848 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.c'), 'wb') as f
:
849 f
.write(TEMPLATE_C
.render(instance_entrypoints
=instance_entrypoints
,
850 physical_device_entrypoints
=physical_device_entrypoints
,
851 device_entrypoints
=device_entrypoints
,
853 instance_strmap
=instance_strmap
,
854 physical_device_strmap
=physical_device_strmap
,
855 device_strmap
=device_strmap
,
856 filename
=os
.path
.basename(__file__
)))
858 # In the event there's an error, this imports some helpers from mako
859 # to print a useful stack trace and prints it, then exits with
860 # status 1, if python is run with debug; otherwise it just raises
864 from mako
import exceptions
865 sys
.stderr
.write(exceptions
.text_error_template().render() + '\n')
870 if __name__
== '__main__':