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
.ElementTree
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 e in physical_device_entrypoints:
306 % if e.alias and e.alias.enabled:
309 % if e.guard is not None:
312 ${e.return_type} ${e.prefixed_name('anv')}(${e.decl_params()}) __attribute__ ((weak));
313 % if e.guard is not None:
318 const struct anv_physical_device_dispatch_table anv_physical_device_dispatch_table = {
319 % for e in physical_device_entrypoints:
320 % if e.guard is not None:
323 .${e.name} = ${e.prefixed_name('anv')},
324 % if e.guard is not None:
331 % for layer in LAYERS:
332 % for e in device_entrypoints:
333 % if e.alias and e.alias.enabled:
336 % if e.guard is not None:
340 ${e.return_type} __attribute__ ((weak))
341 ${e.prefixed_name('anv')}(${e.decl_params()})
343 % if e.params[0].type == 'VkDevice':
344 ANV_FROM_HANDLE(anv_device, anv_device, ${e.params[0].name});
345 return anv_device->dispatch.${e.name}(${e.call_params()});
346 % elif e.params[0].type == 'VkCommandBuffer':
347 ANV_FROM_HANDLE(anv_cmd_buffer, anv_cmd_buffer, ${e.params[0].name});
348 return anv_cmd_buffer->device->dispatch.${e.name}(${e.call_params()});
349 % elif e.params[0].type == 'VkQueue':
350 ANV_FROM_HANDLE(anv_queue, anv_queue, ${e.params[0].name});
351 return anv_queue->device->dispatch.${e.name}(${e.call_params()});
353 assert(!"Unhandled device child trampoline case: ${e.params[0].type}");
357 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()}) __attribute__ ((weak));
359 % if e.guard is not None:
364 const struct anv_device_dispatch_table ${layer}_device_dispatch_table = {
365 % for e in device_entrypoints:
366 % if e.guard is not None:
369 .${e.name} = ${e.prefixed_name(layer)},
370 % if e.guard is not None:
378 /** Return true if the core version or extension in which the given entrypoint
379 * is defined is enabled.
381 * If device is NULL, all device extensions are considered enabled.
384 anv_instance_entrypoint_is_enabled(int index, uint32_t core_version,
385 const struct anv_instance_extension_table *instance)
388 % for e in instance_entrypoints:
392 return ${e.core_version.c_vk_version()} <= core_version;
394 % for ext in e.extensions:
395 % if ext.type == 'instance':
396 if (instance->${ext.name[3:]}) return true;
398 /* All device extensions are considered enabled at the instance level */
412 /** Return true if the core version or extension in which the given entrypoint
413 * is defined is enabled.
415 * If device is NULL, all device extensions are considered enabled.
418 anv_physical_device_entrypoint_is_enabled(int index, uint32_t core_version,
419 const struct anv_instance_extension_table *instance)
422 % for e in physical_device_entrypoints:
426 return ${e.core_version.c_vk_version()} <= core_version;
428 % for ext in e.extensions:
429 % if ext.type == 'instance':
430 if (instance->${ext.name[3:]}) return true;
432 /* All device extensions are considered enabled at the instance level */
446 /** Return true if the core version or extension in which the given entrypoint
447 * is defined is enabled.
449 * If device is NULL, all device extensions are considered enabled.
452 anv_device_entrypoint_is_enabled(int index, uint32_t core_version,
453 const struct anv_instance_extension_table *instance,
454 const struct anv_device_extension_table *device)
457 % for e in device_entrypoints:
461 return ${e.core_version.c_vk_version()} <= core_version;
463 % for ext in e.extensions:
464 % if ext.type == 'instance':
467 if (!device || device->${ext.name[3:]}) return true;
481 anv_get_instance_entrypoint_index(const char *name)
483 return instance_string_map_lookup(name);
487 anv_get_physical_device_entrypoint_index(const char *name)
489 return physical_device_string_map_lookup(name);
493 anv_get_device_entrypoint_index(const char *name)
495 return device_string_map_lookup(name);
499 anv_get_instance_entry_name(int index)
501 return instance_entry_name(index);
505 anv_get_physical_device_entry_name(int index)
507 return physical_device_entry_name(index);
511 anv_get_device_entry_name(int index)
513 return device_entry_name(index);
516 static void * __attribute__ ((noinline))
517 anv_resolve_device_entrypoint(const struct gen_device_info *devinfo, uint32_t index)
519 const struct anv_device_dispatch_table *genX_table;
520 switch (devinfo->gen) {
522 genX_table = &gen12_device_dispatch_table;
525 genX_table = &gen11_device_dispatch_table;
528 genX_table = &gen10_device_dispatch_table;
531 genX_table = &gen9_device_dispatch_table;
534 genX_table = &gen8_device_dispatch_table;
537 if (devinfo->is_haswell)
538 genX_table = &gen75_device_dispatch_table;
540 genX_table = &gen7_device_dispatch_table;
543 unreachable("unsupported gen\\n");
546 if (genX_table->entrypoints[index])
547 return genX_table->entrypoints[index];
549 return anv_device_dispatch_table.entrypoints[index];
553 anv_lookup_entrypoint(const struct gen_device_info *devinfo, const char *name)
555 int idx = anv_get_instance_entrypoint_index(name);
557 return anv_instance_dispatch_table.entrypoints[idx];
559 idx = anv_get_physical_device_entrypoint_index(name);
561 return anv_physical_device_dispatch_table.entrypoints[idx];
563 idx = anv_get_device_entrypoint_index(name);
565 return anv_resolve_device_entrypoint(devinfo, idx);
568 }""", output_encoding
='utf-8')
572 PRIME_FACTOR
= 5024183
575 class StringIntMapEntry(object):
576 def __init__(self
, string
, num
):
580 # Calculate the same hash value that we will calculate in C.
583 h
= ((h
* PRIME_FACTOR
) + ord(c
)) & U32_MASK
588 def round_to_pow2(x
):
589 return 2**int(math
.ceil(math
.log(x
, 2)))
591 class StringIntMap(object):
594 self
.strings
= dict()
596 def add_string(self
, string
, num
):
597 assert not self
.baked
598 assert string
not in self
.strings
599 assert 0 <= num
< 2**31
600 self
.strings
[string
] = StringIntMapEntry(string
, num
)
603 self
.sorted_strings
= \
604 sorted(self
.strings
.values(), key
=lambda x
: x
.string
)
606 for entry
in self
.sorted_strings
:
607 entry
.offset
= offset
608 offset
+= len(entry
.string
) + 1
610 # Save off some values that we'll need in C
611 self
.hash_size
= round_to_pow2(len(self
.strings
) * 1.25)
612 self
.hash_mask
= self
.hash_size
- 1
613 self
.prime_factor
= PRIME_FACTOR
614 self
.prime_step
= PRIME_STEP
616 self
.mapping
= [-1] * self
.hash_size
617 self
.collisions
= [0] * 10
618 for idx
, s
in enumerate(self
.sorted_strings
):
621 while self
.mapping
[h
& self
.hash_mask
] >= 0:
624 self
.collisions
[min(level
, 9)] += 1
625 self
.mapping
[h
& self
.hash_mask
] = idx
627 EntrypointParam
= namedtuple('EntrypointParam', 'type name decl')
629 class EntrypointBase(object):
630 def __init__(self
, name
):
636 # Extensions which require this entrypoint
637 self
.core_version
= None
640 def prefixed_name(self
, prefix
):
641 assert self
.name
.startswith('vk')
642 return prefix
+ '_' + self
.name
[2:]
644 class Entrypoint(EntrypointBase
):
645 def __init__(self
, name
, return_type
, params
, guard
=None):
646 super(Entrypoint
, self
).__init
__(name
)
647 self
.return_type
= return_type
651 def is_physical_device_entrypoint(self
):
652 return self
.params
[0].type in ('VkPhysicalDevice', )
654 def is_device_entrypoint(self
):
655 return self
.params
[0].type in ('VkDevice', 'VkCommandBuffer', 'VkQueue')
657 def decl_params(self
):
658 return ', '.join(p
.decl
for p
in self
.params
)
660 def call_params(self
):
661 return ', '.join(p
.name
for p
in self
.params
)
663 class EntrypointAlias(EntrypointBase
):
664 def __init__(self
, name
, entrypoint
):
665 super(EntrypointAlias
, self
).__init
__(name
)
666 self
.alias
= entrypoint
668 def is_physical_device_entrypoint(self
):
669 return self
.alias
.is_physical_device_entrypoint()
671 def is_device_entrypoint(self
):
672 return self
.alias
.is_device_entrypoint()
674 def prefixed_name(self
, prefix
):
675 if self
.alias
.enabled
:
676 return self
.alias
.prefixed_name(prefix
)
677 return super(EntrypointAlias
, self
).prefixed_name(prefix
)
681 return self
.alias
.params
684 def return_type(self
):
685 return self
.alias
.return_type
687 def decl_params(self
):
688 return self
.alias
.decl_params()
690 def call_params(self
):
691 return self
.alias
.call_params()
693 def get_entrypoints(doc
, entrypoints_to_defines
):
694 """Extract the entry points from the registry."""
695 entrypoints
= OrderedDict()
697 for command
in doc
.findall('./commands/command'):
698 if 'alias' in command
.attrib
:
699 alias
= command
.attrib
['name']
700 target
= command
.attrib
['alias']
701 entrypoints
[alias
] = EntrypointAlias(alias
, entrypoints
[target
])
703 name
= command
.find('./proto/name').text
704 ret_type
= command
.find('./proto/type').text
705 params
= [EntrypointParam(
706 type=p
.find('./type').text
,
707 name
=p
.find('./name').text
,
708 decl
=''.join(p
.itertext())
709 ) for p
in command
.findall('./param')]
710 guard
= entrypoints_to_defines
.get(name
)
711 # They really need to be unique
712 assert name
not in entrypoints
713 entrypoints
[name
] = Entrypoint(name
, ret_type
, params
, guard
)
715 for feature
in doc
.findall('./feature'):
716 assert feature
.attrib
['api'] == 'vulkan'
717 version
= VkVersion(feature
.attrib
['number'])
718 if version
> MAX_API_VERSION
:
721 for command
in feature
.findall('./require/command'):
722 e
= entrypoints
[command
.attrib
['name']]
724 assert e
.core_version
is None
725 e
.core_version
= version
727 supported_exts
= dict((ext
.name
, ext
) for ext
in EXTENSIONS
)
728 for extension
in doc
.findall('.extensions/extension'):
729 ext_name
= extension
.attrib
['name']
730 if ext_name
not in supported_exts
:
733 ext
= supported_exts
[ext_name
]
734 ext
.type = extension
.attrib
['type']
736 for command
in extension
.findall('./require/command'):
737 e
= entrypoints
[command
.attrib
['name']]
739 assert e
.core_version
is None
740 e
.extensions
.append(ext
)
742 return [e
for e
in entrypoints
.values() if e
.enabled
]
745 def get_entrypoints_defines(doc
):
746 """Maps entry points to extension defines."""
747 entrypoints_to_defines
= {}
750 for platform
in doc
.findall('./platforms/platform'):
751 name
= platform
.attrib
['name']
752 define
= platform
.attrib
['protect']
753 platform_define
[name
] = define
755 for extension
in doc
.findall('./extensions/extension[@platform]'):
756 platform
= extension
.attrib
['platform']
757 define
= platform_define
[platform
]
759 for entrypoint
in extension
.findall('./require/command'):
760 fullname
= entrypoint
.attrib
['name']
761 entrypoints_to_defines
[fullname
] = define
763 return entrypoints_to_defines
767 parser
= argparse
.ArgumentParser()
768 parser
.add_argument('--outdir', help='Where to write the files.',
770 parser
.add_argument('--xml',
771 help='Vulkan API XML file.',
775 args
= parser
.parse_args()
779 for filename
in args
.xml_files
:
780 doc
= et
.parse(filename
)
781 entrypoints
+= get_entrypoints(doc
, get_entrypoints_defines(doc
))
783 # Manually add CreateDmaBufImageINTEL for which we don't have an extension
785 entrypoints
.append(Entrypoint('vkCreateDmaBufImageINTEL', 'VkResult', [
786 EntrypointParam('VkDevice', 'device', 'VkDevice device'),
787 EntrypointParam('VkDmaBufImageCreateInfo', 'pCreateInfo',
788 'const VkDmaBufImageCreateInfo* pCreateInfo'),
789 EntrypointParam('VkAllocationCallbacks', 'pAllocator',
790 'const VkAllocationCallbacks* pAllocator'),
791 EntrypointParam('VkDeviceMemory', 'pMem', 'VkDeviceMemory* pMem'),
792 EntrypointParam('VkImage', 'pImage', 'VkImage* pImage')
795 device_entrypoints
= []
796 physical_device_entrypoints
= []
797 instance_entrypoints
= []
798 for e
in entrypoints
:
799 if e
.is_device_entrypoint():
800 device_entrypoints
.append(e
)
801 elif e
.is_physical_device_entrypoint():
802 physical_device_entrypoints
.append(e
)
804 instance_entrypoints
.append(e
)
806 device_strmap
= StringIntMap()
807 for num
, e
in enumerate(device_entrypoints
):
808 device_strmap
.add_string(e
.name
, num
)
812 physical_device_strmap
= StringIntMap()
813 for num
, e
in enumerate(physical_device_entrypoints
):
814 physical_device_strmap
.add_string(e
.name
, num
)
816 physical_device_strmap
.bake()
818 instance_strmap
= StringIntMap()
819 for num
, e
in enumerate(instance_entrypoints
):
820 instance_strmap
.add_string(e
.name
, num
)
822 instance_strmap
.bake()
824 # For outputting entrypoints.h we generate a anv_EntryPoint() prototype
827 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.h'), 'wb') as f
:
828 f
.write(TEMPLATE_H
.render(instance_entrypoints
=instance_entrypoints
,
829 physical_device_entrypoints
=physical_device_entrypoints
,
830 device_entrypoints
=device_entrypoints
,
832 filename
=os
.path
.basename(__file__
)))
833 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.c'), 'wb') as f
:
834 f
.write(TEMPLATE_C
.render(instance_entrypoints
=instance_entrypoints
,
835 physical_device_entrypoints
=physical_device_entrypoints
,
836 device_entrypoints
=device_entrypoints
,
838 instance_strmap
=instance_strmap
,
839 physical_device_strmap
=physical_device_strmap
,
840 device_strmap
=device_strmap
,
841 filename
=os
.path
.basename(__file__
)))
843 # In the event there's an error, this imports some helpers from mako
844 # to print a useful stack trace and prints it, then exits with
845 # status 1, if python is run with debug; otherwise it just raises
849 from mako
import exceptions
850 sys
.stderr
.write(exceptions
.text_error_template().render() + '\n')
855 if __name__
== '__main__':