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