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