blob: 855292e7ea9a5cf7e41da9a32cfad46bfce1a264 [file] [log] [blame]
Mark Lobodzinskia509c292016-10-11 14:33:07 -06001#!/usr/bin/python3 -i
2#
3# Copyright (c) 2015-2016 The Khronos Group Inc.
4# Copyright (c) 2015-2016 Valve Corporation
5# Copyright (c) 2015-2016 LunarG, Inc.
6# Copyright (c) 2015-2016 Google Inc.
7#
8# Licensed under the Apache License, Version 2.0 (the "License");
9# you may not use this file except in compliance with the License.
10# You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS,
16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19#
20# Author: Tobin Ehlis <tobine@google.com>
21# Author: Mark Lobodzinski <mark@lunarg.com>
22
23import os,re,sys
24import xml.etree.ElementTree as etree
25from generator import *
26from collections import namedtuple
27
28# UniqueObjectsGeneratorOptions - subclass of GeneratorOptions.
29#
30# Adds options used by UniqueObjectsOutputGenerator objects during
31# unique objects layer generation.
32#
33# Additional members
34# prefixText - list of strings to prefix generated header with
35# (usually a copyright statement + calling convention macros).
36# protectFile - True if multiple inclusion protection should be
37# generated (based on the filename) around the entire header.
38# protectFeature - True if #ifndef..#endif protection should be
39# generated around a feature interface in the header file.
40# genFuncPointers - True if function pointer typedefs should be
41# generated
42# protectProto - If conditional protection should be generated
43# around prototype declarations, set to either '#ifdef'
44# to require opt-in (#ifdef protectProtoStr) or '#ifndef'
45# to require opt-out (#ifndef protectProtoStr). Otherwise
46# set to None.
47# protectProtoStr - #ifdef/#ifndef symbol to use around prototype
48# declarations, if protectProto is set
49# apicall - string to use for the function declaration prefix,
50# such as APICALL on Windows.
51# apientry - string to use for the calling convention macro,
52# in typedefs, such as APIENTRY.
53# apientryp - string to use for the calling convention macro
54# in function pointer typedefs, such as APIENTRYP.
55# indentFuncProto - True if prototype declarations should put each
56# parameter on a separate line
57# indentFuncPointer - True if typedefed function pointers should put each
58# parameter on a separate line
59# alignFuncParam - if nonzero and parameters are being put on a
60# separate line, align parameter names at the specified column
61class UniqueObjectsGeneratorOptions(GeneratorOptions):
62 def __init__(self,
63 filename = None,
64 directory = '.',
65 apiname = None,
66 profile = None,
67 versions = '.*',
68 emitversions = '.*',
69 defaultExtensions = None,
70 addExtensions = None,
71 removeExtensions = None,
72 sortProcedure = regSortFeatures,
73 prefixText = "",
74 genFuncPointers = True,
75 protectFile = True,
76 protectFeature = True,
77 protectProto = None,
78 protectProtoStr = None,
79 apicall = '',
80 apientry = '',
81 apientryp = '',
82 indentFuncProto = True,
83 indentFuncPointer = False,
84 alignFuncParam = 0):
85 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
86 versions, emitversions, defaultExtensions,
87 addExtensions, removeExtensions, sortProcedure)
88 self.prefixText = prefixText
89 self.genFuncPointers = genFuncPointers
90 self.protectFile = protectFile
91 self.protectFeature = protectFeature
92 self.protectProto = protectProto
93 self.protectProtoStr = protectProtoStr
94 self.apicall = apicall
95 self.apientry = apientry
96 self.apientryp = apientryp
97 self.indentFuncProto = indentFuncProto
98 self.indentFuncPointer = indentFuncPointer
99 self.alignFuncParam = alignFuncParam
100
101# UniqueObjectsOutputGenerator - subclass of OutputGenerator.
102# Generates unique objects layer non-dispatchable handle-wrapping code.
103#
104# ---- methods ----
105# UniqueObjectsOutputGenerator(errFile, warnFile, diagFile) - args as for OutputGenerator. Defines additional internal state.
106# ---- methods overriding base class ----
107# beginFile(genOpts)
108# endFile()
109# beginFeature(interface, emit)
110# endFeature()
111# genCmd(cmdinfo)
112# genStruct()
113# genType()
114class UniqueObjectsOutputGenerator(OutputGenerator):
115 """Generate UniqueObjects code based on XML element attributes"""
116 # This is an ordered list of sections in the header file.
117 ALL_SECTIONS = ['command']
118 def __init__(self,
119 errFile = sys.stderr,
120 warnFile = sys.stderr,
121 diagFile = sys.stdout):
122 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
123 self.INDENT_SPACES = 4
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600124 self.intercepts = []
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700125 self.instance_extensions = []
126 self.device_extensions = []
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600127 # Commands which are not autogenerated but still intercepted
128 self.no_autogen_list = [
Jamie Madill24aa9742016-12-13 17:02:57 -0500129 'vkGetDeviceProcAddr',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600130 'vkGetInstanceProcAddr',
131 'vkCreateInstance',
132 'vkDestroyInstance',
133 'vkCreateDevice',
134 'vkDestroyDevice',
135 'vkAllocateMemory',
136 'vkCreateComputePipelines',
137 'vkCreateGraphicsPipelines',
138 'vkCreateSwapchainKHR',
Dustin Graves9a6eb052017-03-28 14:18:54 -0600139 'vkCreateSharedSwapchainsKHR',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600140 'vkGetSwapchainImagesKHR',
141 'vkEnumerateInstanceLayerProperties',
142 'vkEnumerateDeviceLayerProperties',
143 'vkEnumerateInstanceExtensionProperties',
Mark Lobodzinski71703a52017-03-03 08:40:16 -0700144 'vkCreateDescriptorUpdateTemplateKHR',
145 'vkDestroyDescriptorUpdateTemplateKHR',
146 'vkUpdateDescriptorSetWithTemplateKHR',
147 'vkCmdPushDescriptorSetWithTemplateKHR',
Mark Lobodzinskia096c122017-03-16 11:54:35 -0600148 'vkDebugMarkerSetObjectTagEXT',
149 'vkDebugMarkerSetObjectNameEXT',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600150 ]
151 # Commands shadowed by interface functions and are not implemented
152 self.interface_functions = [
153 'vkGetPhysicalDeviceDisplayPropertiesKHR',
154 'vkGetPhysicalDeviceDisplayPlanePropertiesKHR',
155 'vkGetDisplayPlaneSupportedDisplaysKHR',
156 'vkGetDisplayModePropertiesKHR',
Norbert Nopper1dec9a52016-11-25 07:55:13 +0100157 'vkGetDisplayPlaneCapabilitiesKHR',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600158 # DebugReport APIs are hooked, but handled separately in the source file
159 'vkCreateDebugReportCallbackEXT',
160 'vkDestroyDebugReportCallbackEXT',
161 'vkDebugReportMessageEXT',
162 ]
163 self.headerVersion = None
164 # Internal state - accumulators for different inner block text
165 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600166 self.cmdMembers = []
167 self.cmd_feature_protect = [] # Save ifdef's for each command
168 self.cmd_info_data = [] # Save the cmdinfo data for wrapping the handles when processing is complete
169 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600170 # Named tuples to store struct and command data
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600171 self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members'])
172 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo'])
173 self.CmdExtraProtect = namedtuple('CmdExtraProtect', ['name', 'extra_protect'])
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600174 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy'])
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600175 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
176 #
177 def incIndent(self, indent):
178 inc = ' ' * self.INDENT_SPACES
179 if indent:
180 return indent + inc
181 return inc
182 #
183 def decIndent(self, indent):
184 if indent and (len(indent) > self.INDENT_SPACES):
185 return indent[:-self.INDENT_SPACES]
186 return ''
187 #
188 # Override makeProtoName to drop the "vk" prefix
189 def makeProtoName(self, name, tail):
190 return self.genOpts.apientry + name[2:] + tail
191 #
192 # Check if the parameter passed in is a pointer to an array
193 def paramIsArray(self, param):
194 return param.attrib.get('len') is not None
195 #
196 def beginFile(self, genOpts):
197 OutputGenerator.beginFile(self, genOpts)
198 # User-supplied prefix text, if any (list of strings)
199 if (genOpts.prefixText):
200 for s in genOpts.prefixText:
201 write(s, file=self.outFile)
202 # Namespace
203 self.newline()
204 write('namespace unique_objects {', file = self.outFile)
205 #
206 def endFile(self):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600207
208 # Write out wrapping/unwrapping functions
209 self.WrapCommands()
210
211 # Actually write the interface to the output file.
212 if (self.emit):
213 self.newline()
214 if (self.featureExtraProtect != None):
215 write('#ifdef', self.featureExtraProtect, file=self.outFile)
216 # Write the unique_objects code to the file
217 if (self.sections['command']):
218 if (self.genOpts.protectProto):
219 write(self.genOpts.protectProto,
220 self.genOpts.protectProtoStr, file=self.outFile)
221 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
222 if (self.featureExtraProtect != None):
223 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
224 else:
225 self.newline()
226
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700227 # Write out device extension white list
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600228 self.newline()
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700229 write('// Layer Device Extension Whitelist', file=self.outFile)
230 write('static const char *kUniqueObjectsSupportedDeviceExtensions =', file=self.outFile)
231 for line in self.device_extensions:
232 write('%s' % line, file=self.outFile)
233 write(';\n', file=self.outFile)
234
235 # Write out instance extension white list
236 self.newline()
237 write('// Layer Instance Extension Whitelist', file=self.outFile)
238 write('static const char *kUniqueObjectsSupportedInstanceExtensions =', file=self.outFile)
239 for line in self.instance_extensions:
240 write('%s' % line, file=self.outFile)
241 write(';\n', file=self.outFile)
242 self.newline()
243
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600244 # Record intercepted procedures
245 write('// intercepts', file=self.outFile)
246 write('struct { const char* name; PFN_vkVoidFunction pFunc;} procmap[] = {', file=self.outFile)
247 write('\n'.join(self.intercepts), file=self.outFile)
248 write('};\n', file=self.outFile)
249 self.newline()
250 write('} // namespace unique_objects', file=self.outFile)
251 # Finish processing in superclass
252 OutputGenerator.endFile(self)
253 #
254 def beginFeature(self, interface, emit):
255 # Start processing in superclass
256 OutputGenerator.beginFeature(self, interface, emit)
257 self.headerVersion = None
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600258
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700259 if self.featureName != 'VK_VERSION_1_0':
260 white_list_entry = []
261 if (self.featureExtraProtect != None):
262 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
263 white_list_entry += [ '"%s"' % self.featureName ]
264 if (self.featureExtraProtect != None):
265 white_list_entry += [ '#endif' ]
266 featureType = interface.get('type')
267 if featureType == 'instance':
268 self.instance_extensions += white_list_entry
269 elif featureType == 'device':
270 self.device_extensions += white_list_entry
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600271 #
272 def endFeature(self):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600273 # Finish processing in superclass
274 OutputGenerator.endFeature(self)
275 #
276 def genType(self, typeinfo, name):
277 OutputGenerator.genType(self, typeinfo, name)
278 typeElem = typeinfo.elem
279 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
280 # Otherwise, emit the tag text.
281 category = typeElem.get('category')
282 if (category == 'struct' or category == 'union'):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600283 self.genStruct(typeinfo, name)
284 #
285 # Append a definition to the specified section
286 def appendSection(self, section, text):
287 # self.sections[section].append('SECTION: ' + section + '\n')
288 self.sections[section].append(text)
289 #
290 # Check if the parameter passed in is a pointer
291 def paramIsPointer(self, param):
292 ispointer = False
293 for elem in param:
294 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
295 ispointer = True
296 return ispointer
297 #
298 # Get the category of a type
299 def getTypeCategory(self, typename):
300 types = self.registry.tree.findall("types/type")
301 for elem in types:
302 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
303 return elem.attrib.get('category')
304 #
305 # Check if a parent object is dispatchable or not
306 def isHandleTypeNonDispatchable(self, handletype):
307 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
308 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
309 return True
310 else:
311 return False
312 #
313 # Retrieve the type and name for a parameter
314 def getTypeNameTuple(self, param):
315 type = ''
316 name = ''
317 for elem in param:
318 if elem.tag == 'type':
319 type = noneStr(elem.text)
320 elif elem.tag == 'name':
321 name = noneStr(elem.text)
322 return (type, name)
323 #
324 # Retrieve the value of the len tag
325 def getLen(self, param):
326 result = None
327 len = param.attrib.get('len')
328 if len and len != 'null-terminated':
329 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
330 # have a null terminated array of strings. We strip the null-terminated from the
331 # 'len' field and only return the parameter specifying the string count
332 if 'null-terminated' in len:
333 result = len.split(',')[0]
334 else:
335 result = len
336 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
337 result = str(result).replace('::', '->')
338 return result
339 #
340 # Generate a VkStructureType based on a structure typename
341 def genVkStructureType(self, typename):
342 # Add underscore between lowercase then uppercase
343 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
344 # Change to uppercase
345 value = value.upper()
346 # Add STRUCTURE_TYPE_
347 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
348 #
349 # Struct parameter check generation.
350 # This is a special case of the <type> tag where the contents are interpreted as a set of
351 # <member> tags instead of freeform C type declarations. The <member> tags are just like
352 # <param> tags - they are a declaration of a struct or union member. Only simple member
353 # declarations are supported (no nested structs etc.)
354 def genStruct(self, typeinfo, typeName):
355 OutputGenerator.genStruct(self, typeinfo, typeName)
356 members = typeinfo.elem.findall('.//member')
357 # Iterate over members once to get length parameters for arrays
358 lens = set()
359 for member in members:
360 len = self.getLen(member)
361 if len:
362 lens.add(len)
363 # Generate member info
364 membersInfo = []
365 for member in members:
366 # Get the member's type and name
367 info = self.getTypeNameTuple(member)
368 type = info[0]
369 name = info[1]
370 cdecl = self.makeCParamDecl(member, 0)
371 # Process VkStructureType
372 if type == 'VkStructureType':
373 # Extract the required struct type value from the comments
374 # embedded in the original text defining the 'typeinfo' element
375 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
376 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
377 if result:
378 value = result.group(0)
379 else:
380 value = self.genVkStructureType(typeName)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600381 # Store pointer/array/string info
382 membersInfo.append(self.CommandParam(type=type,
383 name=name,
384 ispointer=self.paramIsPointer(member),
385 isconst=True if 'const' in cdecl else False,
386 iscount=True if name in lens else False,
387 len=self.getLen(member),
388 extstructs=member.attrib.get('validextensionstructs') if name == 'pNext' else None,
389 cdecl=cdecl,
390 islocal=False,
391 iscreate=False,
392 isdestroy=False))
393 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
394 #
395 # Insert a lock_guard line
396 def lock_guard(self, indent):
397 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
398 #
399 # Determine if a struct has an NDO as a member or an embedded member
400 def struct_contains_ndo(self, struct_item):
401 struct_member_dict = dict(self.structMembers)
402 struct_members = struct_member_dict[struct_item]
403
404 for member in struct_members:
405 if self.isHandleTypeNonDispatchable(member.type):
406 return True
407 elif member.type in struct_member_dict:
408 if self.struct_contains_ndo(member.type) == True:
409 return True
410 return False
411 #
412 # Return list of struct members which contain, or which sub-structures contain
413 # an NDO in a given list of parameters or members
414 def getParmeterStructsWithNdos(self, item_list):
415 struct_list = set()
416 for item in item_list:
417 paramtype = item.find('type')
418 typecategory = self.getTypeCategory(paramtype.text)
419 if typecategory == 'struct':
420 if self.struct_contains_ndo(paramtype.text) == True:
421 struct_list.add(item)
422 return struct_list
423 #
424 # Return list of non-dispatchable objects from a given list of parameters or members
425 def getNdosInParameterList(self, item_list, create_func):
426 ndo_list = set()
427 if create_func == True:
428 member_list = item_list[0:-1]
429 else:
430 member_list = item_list
431 for item in member_list:
432 if self.isHandleTypeNonDispatchable(paramtype.text):
433 ndo_list.add(item)
434 return ndo_list
435 #
436 # Generate source for creating a non-dispatchable object
437 def generate_create_ndo_code(self, indent, proto, params, cmd_info):
438 create_ndo_code = ''
Mark Young39389872017-01-19 21:10:49 -0700439 handle_type = params[-1].find('type')
440 if self.isHandleTypeNonDispatchable(handle_type.text):
441 # Check for special case where multiple handles are returned
442 ndo_array = False
443 if cmd_info[-1].len is not None:
444 ndo_array = True;
445 handle_name = params[-1].find('name')
446 create_ndo_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
447 indent = self.incIndent(indent)
448 create_ndo_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
449 ndo_dest = '*%s' % handle_name.text
450 if ndo_array == True:
451 create_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[-1].len)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600452 indent = self.incIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700453 ndo_dest = '%s[index0]' % cmd_info[-1].name
454 create_ndo_code += '%suint64_t unique_id = global_unique_id++;\n' % (indent)
455 create_ndo_code += '%sdev_data->unique_id_mapping[unique_id] = reinterpret_cast<uint64_t &>(%s);\n' % (indent, ndo_dest)
456 create_ndo_code += '%s%s = reinterpret_cast<%s&>(unique_id);\n' % (indent, ndo_dest, handle_type.text)
457 if ndo_array == True:
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600458 indent = self.decIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700459 create_ndo_code += '%s}\n' % indent
460 indent = self.decIndent(indent)
461 create_ndo_code += '%s}\n' % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600462 return create_ndo_code
463 #
464 # Generate source for destroying a non-dispatchable object
465 def generate_destroy_ndo_code(self, indent, proto, cmd_info):
466 destroy_ndo_code = ''
467 ndo_array = False
468 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
469 # Check for special case where multiple handles are returned
470 if cmd_info[-1].len is not None:
471 ndo_array = True;
472 param = -1
473 else:
474 param = -2
475 if self.isHandleTypeNonDispatchable(cmd_info[param].type) == True:
476 if ndo_array == True:
477 # This API is freeing an array of handles. Remove them from the unique_id map.
478 destroy_ndo_code += '%sif ((VK_SUCCESS == result) && (%s)) {\n' % (indent, cmd_info[param].name)
479 indent = self.incIndent(indent)
480 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
481 destroy_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[param].len)
482 indent = self.incIndent(indent)
483 destroy_ndo_code += '%s%s handle = %s[index0];\n' % (indent, cmd_info[param].type, cmd_info[param].name)
484 destroy_ndo_code += '%suint64_t unique_id = reinterpret_cast<uint64_t &>(handle);\n' % (indent)
485 destroy_ndo_code += '%sdev_data->unique_id_mapping.erase(unique_id);\n' % (indent)
486 indent = self.decIndent(indent);
487 destroy_ndo_code += '%s}\n' % indent
488 indent = self.decIndent(indent);
489 destroy_ndo_code += '%s}\n' % indent
490 else:
491 # Remove a single handle from the map
492 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
493 destroy_ndo_code += '%suint64_t %s_id = reinterpret_cast<uint64_t &>(%s);\n' % (indent, cmd_info[param].name, cmd_info[param].name)
494 destroy_ndo_code += '%s%s = (%s)dev_data->unique_id_mapping[%s_id];\n' % (indent, cmd_info[param].name, cmd_info[param].type, cmd_info[param].name)
495 destroy_ndo_code += '%sdev_data->unique_id_mapping.erase(%s_id);\n' % (indent, cmd_info[param].name)
496 destroy_ndo_code += '%slock.unlock();\n' % (indent)
497 return ndo_array, destroy_ndo_code
498
499 #
500 # Clean up local declarations
501 def cleanUpLocalDeclarations(self, indent, prefix, name, len):
502 cleanup = '%sif (local_%s%s)\n' % (indent, prefix, name)
503 if len is not None:
504 cleanup += '%s delete[] local_%s%s;\n' % (indent, prefix, name)
505 else:
506 cleanup += '%s delete local_%s%s;\n' % (indent, prefix, name)
507 return cleanup
508 #
509 # Output UO code for a single NDO (ndo_count is NULL) or a counted list of NDOs
510 def outputNDOs(self, ndo_type, ndo_name, ndo_count, prefix, index, indent, destroy_func, destroy_array, top_level):
511 decl_code = ''
512 pre_call_code = ''
513 post_call_code = ''
514 if ndo_count is not None:
515 if top_level == True:
516 decl_code += '%s%s *local_%s%s = NULL;\n' % (indent, ndo_type, prefix, ndo_name)
517 pre_call_code += '%s if (%s%s) {\n' % (indent, prefix, ndo_name)
518 indent = self.incIndent(indent)
519 if top_level == True:
520 pre_call_code += '%s local_%s%s = new %s[%s];\n' % (indent, prefix, ndo_name, ndo_type, ndo_count)
521 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
522 indent = self.incIndent(indent)
523 pre_call_code += '%s local_%s%s[%s] = (%s)dev_data->unique_id_mapping[reinterpret_cast<const uint64_t &>(%s[%s])];\n' % (indent, prefix, ndo_name, index, ndo_type, ndo_name, index)
524 else:
525 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
526 indent = self.incIndent(indent)
527 pre_call_code += '%s %s%s[%s] = (%s)dev_data->unique_id_mapping[reinterpret_cast<const uint64_t &>(%s%s[%s])];\n' % (indent, prefix, ndo_name, index, ndo_type, prefix, ndo_name, index)
528 indent = self.decIndent(indent)
529 pre_call_code += '%s }\n' % indent
530 indent = self.decIndent(indent)
531 pre_call_code += '%s }\n' % indent
532 if top_level == True:
533 post_call_code += '%sif (local_%s%s)\n' % (indent, prefix, ndo_name)
534 indent = self.incIndent(indent)
535 post_call_code += '%sdelete[] local_%s;\n' % (indent, ndo_name)
536 else:
537 if top_level == True:
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600538 if (destroy_func == False) or (destroy_array == True):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600539 pre_call_code += '%s %s = (%s)dev_data->unique_id_mapping[reinterpret_cast<uint64_t &>(%s)];\n' % (indent, ndo_name, ndo_type, ndo_name)
540 else:
541 # Make temp copy of this var with the 'local' removed. It may be better to not pass in 'local_'
542 # as part of the string and explicitly print it
543 fix = str(prefix).strip('local_');
544 pre_call_code += '%s if (%s%s) {\n' % (indent, fix, ndo_name)
545 indent = self.incIndent(indent)
546 pre_call_code += '%s %s%s = (%s)dev_data->unique_id_mapping[reinterpret_cast<const uint64_t &>(%s%s)];\n' % (indent, prefix, ndo_name, ndo_type, fix, ndo_name)
547 indent = self.decIndent(indent)
548 pre_call_code += '%s }\n' % indent
549 return decl_code, pre_call_code, post_call_code
550 #
551 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
552 # create_func means that this is API creates or allocates NDOs
553 # destroy_func indicates that this API destroys or frees NDOs
554 # destroy_array means that the destroy_func operated on an array of NDOs
555 def uniquify_members(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, first_level_param):
556 decls = ''
557 pre_code = ''
558 post_code = ''
559 struct_member_dict = dict(self.structMembers)
560 index = 'index%s' % str(array_index)
561 array_index += 1
562 # Process any NDOs in this structure and recurse for any sub-structs in this struct
563 for member in members:
564 # Handle NDOs
565 if self.isHandleTypeNonDispatchable(member.type) == True:
Jamie Madill24aa9742016-12-13 17:02:57 -0500566 count_name = member.len
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600567 if (count_name is not None):
568 if first_level_param == False:
569 count_name = '%s%s' % (prefix, member.len)
570
571 if (first_level_param == False) or (create_func == False):
572 (tmp_decl, tmp_pre, tmp_post) = self.outputNDOs(member.type, member.name, count_name, prefix, index, indent, destroy_func, destroy_array, first_level_param)
573 decls += tmp_decl
574 pre_code += tmp_pre
575 post_code += tmp_post
576 # Handle Structs that contain NDOs at some level
577 elif member.type in struct_member_dict:
578 # All structs at first level will have an NDO
579 if self.struct_contains_ndo(member.type) == True:
580 struct_info = struct_member_dict[member.type]
581 # Struct Array
582 if member.len is not None:
583 # Update struct prefix
584 if first_level_param == True:
585 new_prefix = 'local_%s' % member.name
586 # Declare safe_VarType for struct
587 decls += '%ssafe_%s *%s = NULL;\n' % (indent, member.type, new_prefix)
588 else:
589 new_prefix = '%s%s' % (prefix, member.name)
590 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
591 indent = self.incIndent(indent)
592 if first_level_param == True:
593 pre_code += '%s %s = new safe_%s[%s];\n' % (indent, new_prefix, member.type, member.len)
594 pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
595 indent = self.incIndent(indent)
596 if first_level_param == True:
597 pre_code += '%s %s[%s].initialize(&%s[%s]);\n' % (indent, new_prefix, index, member.name, index)
598 local_prefix = '%s[%s].' % (new_prefix, index)
599 # Process sub-structs in this struct
600 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, local_prefix, array_index, create_func, destroy_func, destroy_array, False)
601 decls += tmp_decl
602 pre_code += tmp_pre
603 post_code += tmp_post
604 indent = self.decIndent(indent)
605 pre_code += '%s }\n' % indent
606 indent = self.decIndent(indent)
607 pre_code += '%s }\n' % indent
608 if first_level_param == True:
609 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len)
610 # Single Struct
611 else:
612 # Update struct prefix
613 if first_level_param == True:
614 new_prefix = 'local_%s->' % member.name
615 decls += '%ssafe_%s *local_%s%s = NULL;\n' % (indent, member.type, prefix, member.name)
616 else:
617 new_prefix = '%s%s->' % (prefix, member.name)
618 # Declare safe_VarType for struct
619 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
620 indent = self.incIndent(indent)
621 if first_level_param == True:
622 pre_code += '%s local_%s%s = new safe_%s(%s);\n' % (indent, prefix, member.name, member.type, member.name)
623 # Process sub-structs in this struct
624 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, False)
625 decls += tmp_decl
626 pre_code += tmp_pre
627 post_code += tmp_post
628 indent = self.decIndent(indent)
629 pre_code += '%s }\n' % indent
630 if first_level_param == True:
631 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len)
632 return decls, pre_code, post_code
633 #
634 # For a particular API, generate the non-dispatchable-object wrapping/unwrapping code
635 def generate_wrapping_code(self, cmd):
636 indent = ' '
637 proto = cmd.find('proto/name')
638 params = cmd.findall('param')
639 if proto.text is not None:
640 cmd_member_dict = dict(self.cmdMembers)
641 cmd_info = cmd_member_dict[proto.text]
642 # Handle ndo create/allocate operations
643 if cmd_info[0].iscreate:
644 create_ndo_code = self.generate_create_ndo_code(indent, proto, params, cmd_info)
645 else:
646 create_ndo_code = ''
647 # Handle ndo destroy/free operations
648 if cmd_info[0].isdestroy:
649 (destroy_array, destroy_ndo_code) = self.generate_destroy_ndo_code(indent, proto, cmd_info)
650 else:
651 destroy_array = False
652 destroy_ndo_code = ''
653 paramdecl = ''
654 param_pre_code = ''
655 param_post_code = ''
656 create_func = True if create_ndo_code else False
657 destroy_func = True if destroy_ndo_code else False
658 (paramdecl, param_pre_code, param_post_code) = self.uniquify_members(cmd_info, indent, '', 0, create_func, destroy_func, destroy_array, True)
659 param_post_code += create_ndo_code
660 if destroy_ndo_code:
661 if destroy_array == True:
662 param_post_code += destroy_ndo_code
663 else:
664 param_pre_code += destroy_ndo_code
665 if param_pre_code:
666 if (not destroy_func) or (destroy_array):
667 param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent)
668 return paramdecl, param_pre_code, param_post_code
669 #
670 # Capture command parameter info needed to wrap NDOs as well as handling some boilerplate code
671 def genCmd(self, cmdinfo, cmdname):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600672
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600673 # Add struct-member type information to command parameter information
674 OutputGenerator.genCmd(self, cmdinfo, cmdname)
675 members = cmdinfo.elem.findall('.//param')
676 # Iterate over members once to get length parameters for arrays
677 lens = set()
678 for member in members:
679 len = self.getLen(member)
680 if len:
681 lens.add(len)
682 struct_member_dict = dict(self.structMembers)
683 # Generate member info
684 membersInfo = []
685 for member in members:
686 # Get type and name of member
687 info = self.getTypeNameTuple(member)
688 type = info[0]
689 name = info[1]
690 cdecl = self.makeCParamDecl(member, 0)
691 # Check for parameter name in lens set
692 iscount = True if name in lens else False
693 len = self.getLen(member)
694 isconst = True if 'const' in cdecl else False
695 ispointer = self.paramIsPointer(member)
696 # Mark param as local if it is an array of NDOs
697 islocal = False;
698 if self.isHandleTypeNonDispatchable(type) == True:
699 if (len is not None) and (isconst == True):
700 islocal = True
701 # Or if it's a struct that contains an NDO
702 elif type in struct_member_dict:
703 if self.struct_contains_ndo(type) == True:
704 islocal = True
705
706 isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False
Mark Young39389872017-01-19 21:10:49 -0700707 iscreate = True if True in [create_txt in cmdname for create_txt in ['Create', 'Allocate', 'GetRandROutputDisplayEXT', 'RegisterDeviceEvent', 'RegisterDisplayEvent']] else False
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600708
709 membersInfo.append(self.CommandParam(type=type,
710 name=name,
711 ispointer=ispointer,
712 isconst=isconst,
713 iscount=iscount,
714 len=len,
715 extstructs=member.attrib.get('validextensionstructs') if name == 'pNext' else None,
716 cdecl=cdecl,
717 islocal=islocal,
718 iscreate=iscreate,
719 isdestroy=isdestroy))
720 self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo))
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600721 self.cmd_info_data.append(self.CmdInfoData(name=cmdname, cmdinfo=cmdinfo))
722 self.cmd_feature_protect.append(self.CmdExtraProtect(name=cmdname, extra_protect=self.featureExtraProtect))
723 #
724 # Create code to wrap NDOs as well as handling some boilerplate code
725 def WrapCommands(self):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600726 cmd_member_dict = dict(self.cmdMembers)
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600727 cmd_info_dict = dict(self.cmd_info_data)
728 cmd_protect_dict = dict(self.cmd_feature_protect)
729
730 for api_call in self.cmdMembers:
731 cmdname = api_call.name
732 cmdinfo = cmd_info_dict[api_call.name]
733 if cmdname in self.interface_functions:
734 continue
735 if cmdname in self.no_autogen_list:
736 decls = self.makeCDecls(cmdinfo.elem)
737 self.appendSection('command', '')
738 self.appendSection('command', '// Declare only')
739 self.appendSection('command', decls[0])
740 self.intercepts += [ ' {"%s", reinterpret_cast<PFN_vkVoidFunction>(%s)},' % (cmdname,cmdname[2:]) ]
741 continue
742 # Generate NDO wrapping/unwrapping code for all parameters
743 (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
744 # If API doesn't contain an NDO's, don't fool with it
745 if not api_decls and not api_pre and not api_post:
746 continue
747 feature_extra_protect = cmd_protect_dict[api_call.name]
748 if (feature_extra_protect != None):
749 self.appendSection('command', '')
750 self.appendSection('command', '#ifdef '+ feature_extra_protect)
751 self.intercepts += [ '#ifdef %s' % feature_extra_protect ]
752 # Add intercept to procmap
753 self.intercepts += [ ' {"%s", reinterpret_cast<PFN_vkVoidFunction>(%s)},' % (cmdname,cmdname[2:]) ]
754 decls = self.makeCDecls(cmdinfo.elem)
755 self.appendSection('command', '')
756 self.appendSection('command', decls[0][:-1])
757 self.appendSection('command', '{')
758 # Setup common to call wrappers, first parameter is always dispatchable
759 dispatchable_type = cmdinfo.elem.find('param/type').text
760 dispatchable_name = cmdinfo.elem.find('param/name').text
761 # Generate local instance/pdev/device data lookup
762 self.appendSection('command', ' layer_data *dev_data = GetLayerDataPtr(get_dispatch_key('+dispatchable_name+'), layer_data_map);')
763 # Handle return values, if any
764 resulttype = cmdinfo.elem.find('proto/type')
765 if (resulttype != None and resulttype.text == 'void'):
766 resulttype = None
767 if (resulttype != None):
768 assignresult = resulttype.text + ' result = '
769 else:
770 assignresult = ''
771 # Pre-pend declarations and pre-api-call codegen
772 if api_decls:
773 self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
774 if api_pre:
775 self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
776 # Generate the API call itself
777 # Gather the parameter items
778 params = cmdinfo.elem.findall('param/name')
779 # Pull out the text for each of the parameters, separate them by commas in a list
780 paramstext = ', '.join([str(param.text) for param in params])
781 # If any of these paramters has been replaced by a local var, fix up the list
782 params = cmd_member_dict[cmdname]
783 for param in params:
784 if param.islocal == True:
785 if param.ispointer == True:
786 paramstext = paramstext.replace(param.name, '(%s %s*)local_%s' % ('const', param.type, param.name))
787 else:
788 paramstext = paramstext.replace(param.name, '(%s %s)local_%s' % ('const', param.type, param.name))
789 # Use correct dispatch table
790 if dispatchable_type in ["VkPhysicalDevice", "VkInstance"]:
791 API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->instance_dispatch_table->',1)
792 else:
793 API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->device_dispatch_table->',1)
794 # Put all this together for the final down-chain call
795 self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');')
796 # And add the post-API-call codegen
797 self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n")))
798 # Handle the return result variable, if any
799 if (resulttype != None):
800 self.appendSection('command', ' return result;')
801 self.appendSection('command', '}')
802 if (feature_extra_protect != None):
803 self.appendSection('command', '#endif // '+ feature_extra_protect)
804 self.intercepts += [ '#endif' ]