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