anv: Drop support for VK_KHX_external_memory_*
[mesa.git] / src / intel / vulkan / anv_entrypoints_gen.py
1 # coding=utf-8
2 #
3 # Copyright © 2015, 2017 Intel Corporation
4 #
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:
11 #
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
14 # Software.
15 #
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
22 # IN THE SOFTWARE.
23 #
24
25 import argparse
26 import functools
27 import os
28 import textwrap
29 import xml.etree.cElementTree as et
30
31 from mako.template import Template
32
33 MAX_API_VERSION = 1.0
34
35 SUPPORTED_EXTENSIONS = [
36 'VK_KHR_descriptor_update_template',
37 'VK_KHR_get_physical_device_properties2',
38 'VK_KHR_get_surface_capabilities2',
39 'VK_KHR_incremental_present',
40 'VK_KHR_maintenance1',
41 'VK_KHR_push_descriptor',
42 'VK_KHR_sampler_mirror_clamp_to_edge',
43 'VK_KHR_shader_draw_parameters',
44 'VK_KHR_surface',
45 'VK_KHR_swapchain',
46 'VK_KHR_wayland_surface',
47 'VK_KHR_xcb_surface',
48 'VK_KHR_xlib_surface',
49 'VK_KHX_external_semaphore',
50 'VK_KHX_external_semaphore_capabilities',
51 'VK_KHX_external_semaphore_fd',
52 'VK_KHX_multiview',
53 ]
54
55 # We generate a static hash table for entry point lookup
56 # (vkGetProcAddress). We use a linear congruential generator for our hash
57 # function and a power-of-two size table. The prime numbers are determined
58 # experimentally.
59
60 TEMPLATE_H = Template(textwrap.dedent("""\
61 /* This file generated from ${filename}, don't edit directly. */
62
63 struct anv_dispatch_table {
64 union {
65 void *entrypoints[${len(entrypoints)}];
66 struct {
67 % for _, name, _, _, _, guard in entrypoints:
68 % if guard is not None:
69 #ifdef ${guard}
70 PFN_vk${name} ${name};
71 #else
72 void *${name};
73 # endif
74 % else:
75 PFN_vk${name} ${name};
76 % endif
77 % endfor
78 };
79 };
80 };
81
82 % for type_, name, args, num, h, guard in entrypoints:
83 % if guard is not None:
84 #ifdef ${guard}
85 % endif
86 ${type_} anv_${name}(${args});
87 ${type_} gen7_${name}(${args});
88 ${type_} gen75_${name}(${args});
89 ${type_} gen8_${name}(${args});
90 ${type_} gen9_${name}(${args});
91 ${type_} gen10_${name}(${args});
92 % if guard is not None:
93 #endif // ${guard}
94 % endif
95 % endfor
96 """), output_encoding='utf-8')
97
98 TEMPLATE_C = Template(textwrap.dedent(u"""\
99 /*
100 * Copyright © 2015 Intel Corporation
101 *
102 * Permission is hereby granted, free of charge, to any person obtaining a
103 * copy of this software and associated documentation files (the "Software"),
104 * to deal in the Software without restriction, including without limitation
105 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
106 * and/or sell copies of the Software, and to permit persons to whom the
107 * Software is furnished to do so, subject to the following conditions:
108 *
109 * The above copyright notice and this permission notice (including the next
110 * paragraph) shall be included in all copies or substantial portions of the
111 * Software.
112 *
113 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
114 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
115 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
116 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
117 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
118 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
119 * IN THE SOFTWARE.
120 */
121
122 /* This file generated from ${filename}, don't edit directly. */
123
124 #include "anv_private.h"
125
126 struct anv_entrypoint {
127 uint32_t name;
128 uint32_t hash;
129 };
130
131 /* We use a big string constant to avoid lots of reloctions from the entry
132 * point table to lots of little strings. The entries in the entry point table
133 * store the index into this big string.
134 */
135
136 static const char strings[] =
137 % for _, name, _, _, _, _ in entrypoints:
138 "vk${name}\\0"
139 % endfor
140 ;
141
142 static const struct anv_entrypoint entrypoints[] = {
143 % for _, _, _, num, h, _ in entrypoints:
144 { ${offsets[num]}, ${'{:0=#8x}'.format(h)} },
145 % endfor
146 };
147
148 /* Weak aliases for all potential implementations. These will resolve to
149 * NULL if they're not defined, which lets the resolve_entrypoint() function
150 * either pick the correct entry point.
151 */
152
153 % for layer in ['anv', 'gen7', 'gen75', 'gen8', 'gen9', 'gen10']:
154 % for type_, name, args, _, _, guard in entrypoints:
155 % if guard is not None:
156 #ifdef ${guard}
157 % endif
158 ${type_} ${layer}_${name}(${args}) __attribute__ ((weak));
159 % if guard is not None:
160 #endif // ${guard}
161 % endif
162 % endfor
163
164 const struct anv_dispatch_table ${layer}_layer = {
165 % for _, name, args, _, _, guard in entrypoints:
166 % if guard is not None:
167 #ifdef ${guard}
168 % endif
169 .${name} = ${layer}_${name},
170 % if guard is not None:
171 #endif // ${guard}
172 % endif
173 % endfor
174 };
175 % endfor
176
177 static void * __attribute__ ((noinline))
178 anv_resolve_entrypoint(const struct gen_device_info *devinfo, uint32_t index)
179 {
180 if (devinfo == NULL) {
181 return anv_layer.entrypoints[index];
182 }
183
184 switch (devinfo->gen) {
185 case 10:
186 if (gen10_layer.entrypoints[index])
187 return gen10_layer.entrypoints[index];
188 /* fall through */
189 case 9:
190 if (gen9_layer.entrypoints[index])
191 return gen9_layer.entrypoints[index];
192 /* fall through */
193 case 8:
194 if (gen8_layer.entrypoints[index])
195 return gen8_layer.entrypoints[index];
196 /* fall through */
197 case 7:
198 if (devinfo->is_haswell && gen75_layer.entrypoints[index])
199 return gen75_layer.entrypoints[index];
200
201 if (gen7_layer.entrypoints[index])
202 return gen7_layer.entrypoints[index];
203 /* fall through */
204 case 0:
205 return anv_layer.entrypoints[index];
206 default:
207 unreachable("unsupported gen\\n");
208 }
209 }
210
211 /* Hash table stats:
212 * size ${hash_size} entries
213 * collisions entries:
214 % for i in xrange(10):
215 * ${i}${'+' if i == 9 else ''} ${collisions[i]}
216 % endfor
217 */
218
219 #define none ${'{:#x}'.format(none)}
220 static const uint16_t map[] = {
221 % for i in xrange(0, hash_size, 8):
222 % for j in xrange(i, i + 8):
223 ## This is 6 because the 0x is counted in the length
224 % if mapping[j] & 0xffff == 0xffff:
225 none,
226 % else:
227 ${'{:0=#6x}'.format(mapping[j] & 0xffff)},
228 % endif
229 % endfor
230 % endfor
231 };
232
233 void *
234 anv_lookup_entrypoint(const struct gen_device_info *devinfo, const char *name)
235 {
236 static const uint32_t prime_factor = ${prime_factor};
237 static const uint32_t prime_step = ${prime_step};
238 const struct anv_entrypoint *e;
239 uint32_t hash, h, i;
240 const char *p;
241
242 hash = 0;
243 for (p = name; *p; p++)
244 hash = hash * prime_factor + *p;
245
246 h = hash;
247 do {
248 i = map[h & ${hash_mask}];
249 if (i == none)
250 return NULL;
251 e = &entrypoints[i];
252 h += prime_step;
253 } while (e->hash != hash);
254
255 if (strcmp(name, strings + e->name) != 0)
256 return NULL;
257
258 return anv_resolve_entrypoint(devinfo, i);
259 }"""), output_encoding='utf-8')
260
261 NONE = 0xffff
262 HASH_SIZE = 256
263 U32_MASK = 2**32 - 1
264 HASH_MASK = HASH_SIZE - 1
265
266 PRIME_FACTOR = 5024183
267 PRIME_STEP = 19
268
269
270 def cal_hash(name):
271 """Calculate the same hash value that Mesa will calculate in C."""
272 return functools.reduce(
273 lambda h, c: (h * PRIME_FACTOR + ord(c)) & U32_MASK, name, 0)
274
275
276 def get_entrypoints(doc, entrypoints_to_defines):
277 """Extract the entry points from the registry."""
278 entrypoints = []
279
280 enabled_commands = set()
281 for feature in doc.findall('./feature'):
282 assert feature.attrib['api'] == 'vulkan'
283 if float(feature.attrib['number']) > MAX_API_VERSION:
284 continue
285
286 for command in feature.findall('./require/command'):
287 enabled_commands.add(command.attrib['name'])
288
289 for extension in doc.findall('.extensions/extension'):
290 if extension.attrib['name'] not in SUPPORTED_EXTENSIONS:
291 continue
292
293 assert extension.attrib['supported'] == 'vulkan'
294 for command in extension.findall('./require/command'):
295 enabled_commands.add(command.attrib['name'])
296
297 index = 0
298 for command in doc.findall('./commands/command'):
299 type = command.find('./proto/type').text
300 fullname = command.find('./proto/name').text
301
302 if fullname not in enabled_commands:
303 continue
304
305 shortname = fullname[2:]
306 params = (''.join(p.itertext()) for p in command.findall('./param'))
307 params = ', '.join(params)
308 guard = entrypoints_to_defines.get(fullname)
309 entrypoints.append((type, shortname, params, index, cal_hash(fullname), guard))
310 index += 1
311
312 return entrypoints
313
314
315 def get_entrypoints_defines(doc):
316 """Maps entry points to extension defines."""
317 entrypoints_to_defines = {}
318
319 for extension in doc.findall('./extensions/extension[@protect]'):
320 define = extension.attrib['protect']
321
322 for entrypoint in extension.findall('./require/command'):
323 fullname = entrypoint.attrib['name']
324 entrypoints_to_defines[fullname] = define
325
326 return entrypoints_to_defines
327
328
329 def gen_code(entrypoints):
330 """Generate the C code."""
331 i = 0
332 offsets = []
333 for _, name, _, _, _, _ in entrypoints:
334 offsets.append(i)
335 i += 2 + len(name) + 1
336
337 mapping = [NONE] * HASH_SIZE
338 collisions = [0] * 10
339 for _, name, _, num, h, _ in entrypoints:
340 level = 0
341 while mapping[h & HASH_MASK] != NONE:
342 h = h + PRIME_STEP
343 level = level + 1
344 if level > 9:
345 collisions[9] += 1
346 else:
347 collisions[level] += 1
348 mapping[h & HASH_MASK] = num
349
350 return TEMPLATE_C.render(entrypoints=entrypoints,
351 offsets=offsets,
352 collisions=collisions,
353 mapping=mapping,
354 hash_mask=HASH_MASK,
355 prime_step=PRIME_STEP,
356 prime_factor=PRIME_FACTOR,
357 none=NONE,
358 hash_size=HASH_SIZE,
359 filename=os.path.basename(__file__))
360
361
362 def main():
363 parser = argparse.ArgumentParser()
364 parser.add_argument('--outdir', help='Where to write the files.',
365 required=True)
366 parser.add_argument('--xml', help='Vulkan API XML file.', required=True)
367 args = parser.parse_args()
368
369 doc = et.parse(args.xml)
370 entrypoints = get_entrypoints(doc, get_entrypoints_defines(doc))
371
372 # Manually add CreateDmaBufImageINTEL for which we don't have an extension
373 # defined.
374 entrypoints.append(('VkResult', 'CreateDmaBufImageINTEL',
375 'VkDevice device, ' +
376 'const VkDmaBufImageCreateInfo* pCreateInfo, ' +
377 'const VkAllocationCallbacks* pAllocator,' +
378 'VkDeviceMemory* pMem,' +
379 'VkImage* pImage', len(entrypoints),
380 cal_hash('vkCreateDmaBufImageINTEL'), None))
381
382 # For outputting entrypoints.h we generate a anv_EntryPoint() prototype
383 # per entry point.
384 with open(os.path.join(args.outdir, 'anv_entrypoints.h'), 'wb') as f:
385 f.write(TEMPLATE_H.render(entrypoints=entrypoints,
386 filename=os.path.basename(__file__)))
387 with open(os.path.join(args.outdir, 'anv_entrypoints.c'), 'wb') as f:
388 f.write(gen_code(entrypoints))
389
390
391 if __name__ == '__main__':
392 main()