Mark Lobodzinski | a509c29 | 2016-10-11 14:33:07 -0600 | [diff] [blame] | 1 | #!/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 | |
| 23 | import os,re,sys |
| 24 | import xml.etree.ElementTree as etree |
| 25 | from generator import * |
| 26 | from 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 |
| 61 | class 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() |
| 114 | class 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 |
| 124 | # Commands to ignore |
| 125 | self.intercepts = [] |
| 126 | # Commands which are not autogenerated but still intercepted |
| 127 | self.no_autogen_list = [ |
Jamie Madill | 24aa974 | 2016-12-13 17:02:57 -0500 | [diff] [blame^] | 128 | 'vkGetDeviceProcAddr', |
Mark Lobodzinski | a509c29 | 2016-10-11 14:33:07 -0600 | [diff] [blame] | 129 | 'vkGetInstanceProcAddr', |
| 130 | 'vkCreateInstance', |
| 131 | 'vkDestroyInstance', |
| 132 | 'vkCreateDevice', |
| 133 | 'vkDestroyDevice', |
| 134 | 'vkAllocateMemory', |
| 135 | 'vkCreateComputePipelines', |
| 136 | 'vkCreateGraphicsPipelines', |
| 137 | 'vkCreateSwapchainKHR', |
| 138 | 'vkGetSwapchainImagesKHR', |
| 139 | 'vkEnumerateInstanceLayerProperties', |
| 140 | 'vkEnumerateDeviceLayerProperties', |
| 141 | 'vkEnumerateInstanceExtensionProperties', |
| 142 | ] |
| 143 | # Commands shadowed by interface functions and are not implemented |
| 144 | self.interface_functions = [ |
| 145 | 'vkGetPhysicalDeviceDisplayPropertiesKHR', |
| 146 | 'vkGetPhysicalDeviceDisplayPlanePropertiesKHR', |
| 147 | 'vkGetDisplayPlaneSupportedDisplaysKHR', |
| 148 | 'vkGetDisplayModePropertiesKHR', |
Norbert Nopper | 1dec9a5 | 2016-11-25 07:55:13 +0100 | [diff] [blame] | 149 | 'vkGetDisplayPlaneCapabilitiesKHR', |
Mark Lobodzinski | a509c29 | 2016-10-11 14:33:07 -0600 | [diff] [blame] | 150 | # DebugReport APIs are hooked, but handled separately in the source file |
| 151 | 'vkCreateDebugReportCallbackEXT', |
| 152 | 'vkDestroyDebugReportCallbackEXT', |
| 153 | 'vkDebugReportMessageEXT', |
| 154 | ] |
| 155 | self.headerVersion = None |
| 156 | # Internal state - accumulators for different inner block text |
| 157 | self.sections = dict([(section, []) for section in self.ALL_SECTIONS]) |
| 158 | self.structNames = [] # List of Vulkan struct typenames |
| 159 | self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType |
| 160 | self.handleTypes = set() # Set of handle type names |
| 161 | self.commands = [] # List of CommandData records for all Vulkan commands |
| 162 | self.structMembers = [] # List of StructMemberData records for all Vulkan structs |
| 163 | self.flags = set() # Map of flags typenames |
| 164 | # Named tuples to store struct and command data |
| 165 | self.StructType = namedtuple('StructType', ['name', 'value']) |
| 166 | self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy']) |
| 167 | self.CommandData = namedtuple('CommandData', ['name', 'return_type', 'params', 'cdecl']) |
| 168 | self.StructMemberData = namedtuple('StructMemberData', ['name', 'members']) |
| 169 | # |
| 170 | def incIndent(self, indent): |
| 171 | inc = ' ' * self.INDENT_SPACES |
| 172 | if indent: |
| 173 | return indent + inc |
| 174 | return inc |
| 175 | # |
| 176 | def decIndent(self, indent): |
| 177 | if indent and (len(indent) > self.INDENT_SPACES): |
| 178 | return indent[:-self.INDENT_SPACES] |
| 179 | return '' |
| 180 | # |
| 181 | # Override makeProtoName to drop the "vk" prefix |
| 182 | def makeProtoName(self, name, tail): |
| 183 | return self.genOpts.apientry + name[2:] + tail |
| 184 | # |
| 185 | # Check if the parameter passed in is a pointer to an array |
| 186 | def paramIsArray(self, param): |
| 187 | return param.attrib.get('len') is not None |
| 188 | # |
| 189 | def beginFile(self, genOpts): |
| 190 | OutputGenerator.beginFile(self, genOpts) |
| 191 | # User-supplied prefix text, if any (list of strings) |
| 192 | if (genOpts.prefixText): |
| 193 | for s in genOpts.prefixText: |
| 194 | write(s, file=self.outFile) |
| 195 | # Namespace |
| 196 | self.newline() |
| 197 | write('namespace unique_objects {', file = self.outFile) |
| 198 | # |
| 199 | def endFile(self): |
| 200 | self.newline() |
| 201 | # Record intercepted procedures |
| 202 | write('// intercepts', file=self.outFile) |
| 203 | write('struct { const char* name; PFN_vkVoidFunction pFunc;} procmap[] = {', file=self.outFile) |
| 204 | write('\n'.join(self.intercepts), file=self.outFile) |
| 205 | write('};\n', file=self.outFile) |
| 206 | self.newline() |
| 207 | write('} // namespace unique_objects', file=self.outFile) |
| 208 | # Finish processing in superclass |
| 209 | OutputGenerator.endFile(self) |
| 210 | # |
| 211 | def beginFeature(self, interface, emit): |
| 212 | # Start processing in superclass |
| 213 | OutputGenerator.beginFeature(self, interface, emit) |
| 214 | self.headerVersion = None |
| 215 | self.sections = dict([(section, []) for section in self.ALL_SECTIONS]) |
| 216 | self.structNames = [] |
| 217 | self.structTypes = dict() |
| 218 | self.handleTypes = set() |
| 219 | self.commands = [] |
| 220 | self.structMembers = [] |
| 221 | self.cmdMembers = [] |
| 222 | self.flags = set() |
| 223 | self.StructMemberData = namedtuple('StructMemberData', ['name', 'members']) |
| 224 | self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members']) |
| 225 | # |
| 226 | def endFeature(self): |
| 227 | # Actually write the interface to the output file. |
| 228 | if (self.emit): |
| 229 | self.newline() |
| 230 | if (self.featureExtraProtect != None): |
| 231 | write('#ifdef', self.featureExtraProtect, file=self.outFile) |
| 232 | # Write the unique_objects code to the file |
| 233 | if (self.sections['command']): |
| 234 | if (self.genOpts.protectProto): |
| 235 | write(self.genOpts.protectProto, |
| 236 | self.genOpts.protectProtoStr, file=self.outFile) |
Jamie Madill | 24aa974 | 2016-12-13 17:02:57 -0500 | [diff] [blame^] | 237 | write('\n'.join(self.sections['command']), end=u'', file=self.outFile) |
Mark Lobodzinski | a509c29 | 2016-10-11 14:33:07 -0600 | [diff] [blame] | 238 | if (self.featureExtraProtect != None): |
| 239 | write('\n#endif //', self.featureExtraProtect, file=self.outFile) |
| 240 | else: |
| 241 | self.newline() |
| 242 | # Finish processing in superclass |
| 243 | OutputGenerator.endFeature(self) |
| 244 | # |
| 245 | def genType(self, typeinfo, name): |
| 246 | OutputGenerator.genType(self, typeinfo, name) |
| 247 | typeElem = typeinfo.elem |
| 248 | # If the type is a struct type, traverse the imbedded <member> tags generating a structure. |
| 249 | # Otherwise, emit the tag text. |
| 250 | category = typeElem.get('category') |
| 251 | if (category == 'struct' or category == 'union'): |
| 252 | self.structNames.append(name) |
| 253 | self.genStruct(typeinfo, name) |
| 254 | # |
| 255 | # Append a definition to the specified section |
| 256 | def appendSection(self, section, text): |
| 257 | # self.sections[section].append('SECTION: ' + section + '\n') |
| 258 | self.sections[section].append(text) |
| 259 | # |
| 260 | # Check if the parameter passed in is a pointer |
| 261 | def paramIsPointer(self, param): |
| 262 | ispointer = False |
| 263 | for elem in param: |
| 264 | if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail: |
| 265 | ispointer = True |
| 266 | return ispointer |
| 267 | # |
| 268 | # Get the category of a type |
| 269 | def getTypeCategory(self, typename): |
| 270 | types = self.registry.tree.findall("types/type") |
| 271 | for elem in types: |
| 272 | if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename: |
| 273 | return elem.attrib.get('category') |
| 274 | # |
| 275 | # Check if a parent object is dispatchable or not |
| 276 | def isHandleTypeNonDispatchable(self, handletype): |
| 277 | handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']") |
| 278 | if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE': |
| 279 | return True |
| 280 | else: |
| 281 | return False |
| 282 | # |
| 283 | # Retrieve the type and name for a parameter |
| 284 | def getTypeNameTuple(self, param): |
| 285 | type = '' |
| 286 | name = '' |
| 287 | for elem in param: |
| 288 | if elem.tag == 'type': |
| 289 | type = noneStr(elem.text) |
| 290 | elif elem.tag == 'name': |
| 291 | name = noneStr(elem.text) |
| 292 | return (type, name) |
| 293 | # |
| 294 | # Retrieve the value of the len tag |
| 295 | def getLen(self, param): |
| 296 | result = None |
| 297 | len = param.attrib.get('len') |
| 298 | if len and len != 'null-terminated': |
| 299 | # For string arrays, 'len' can look like 'count,null-terminated', indicating that we |
| 300 | # have a null terminated array of strings. We strip the null-terminated from the |
| 301 | # 'len' field and only return the parameter specifying the string count |
| 302 | if 'null-terminated' in len: |
| 303 | result = len.split(',')[0] |
| 304 | else: |
| 305 | result = len |
| 306 | # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol |
| 307 | result = str(result).replace('::', '->') |
| 308 | return result |
| 309 | # |
| 310 | # Generate a VkStructureType based on a structure typename |
| 311 | def genVkStructureType(self, typename): |
| 312 | # Add underscore between lowercase then uppercase |
| 313 | value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename) |
| 314 | # Change to uppercase |
| 315 | value = value.upper() |
| 316 | # Add STRUCTURE_TYPE_ |
| 317 | return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value) |
| 318 | # |
| 319 | # Struct parameter check generation. |
| 320 | # This is a special case of the <type> tag where the contents are interpreted as a set of |
| 321 | # <member> tags instead of freeform C type declarations. The <member> tags are just like |
| 322 | # <param> tags - they are a declaration of a struct or union member. Only simple member |
| 323 | # declarations are supported (no nested structs etc.) |
| 324 | def genStruct(self, typeinfo, typeName): |
| 325 | OutputGenerator.genStruct(self, typeinfo, typeName) |
| 326 | members = typeinfo.elem.findall('.//member') |
| 327 | # Iterate over members once to get length parameters for arrays |
| 328 | lens = set() |
| 329 | for member in members: |
| 330 | len = self.getLen(member) |
| 331 | if len: |
| 332 | lens.add(len) |
| 333 | # Generate member info |
| 334 | membersInfo = [] |
| 335 | for member in members: |
| 336 | # Get the member's type and name |
| 337 | info = self.getTypeNameTuple(member) |
| 338 | type = info[0] |
| 339 | name = info[1] |
| 340 | cdecl = self.makeCParamDecl(member, 0) |
| 341 | # Process VkStructureType |
| 342 | if type == 'VkStructureType': |
| 343 | # Extract the required struct type value from the comments |
| 344 | # embedded in the original text defining the 'typeinfo' element |
| 345 | rawXml = etree.tostring(typeinfo.elem).decode('ascii') |
| 346 | result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml) |
| 347 | if result: |
| 348 | value = result.group(0) |
| 349 | else: |
| 350 | value = self.genVkStructureType(typeName) |
| 351 | # Store the required type value |
| 352 | self.structTypes[typeName] = self.StructType(name=name, value=value) |
| 353 | # Store pointer/array/string info |
| 354 | membersInfo.append(self.CommandParam(type=type, |
| 355 | name=name, |
| 356 | ispointer=self.paramIsPointer(member), |
| 357 | isconst=True if 'const' in cdecl else False, |
| 358 | iscount=True if name in lens else False, |
| 359 | len=self.getLen(member), |
| 360 | extstructs=member.attrib.get('validextensionstructs') if name == 'pNext' else None, |
| 361 | cdecl=cdecl, |
| 362 | islocal=False, |
| 363 | iscreate=False, |
| 364 | isdestroy=False)) |
| 365 | self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo)) |
| 366 | # |
| 367 | # Insert a lock_guard line |
| 368 | def lock_guard(self, indent): |
| 369 | return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent |
| 370 | # |
| 371 | # Determine if a struct has an NDO as a member or an embedded member |
| 372 | def struct_contains_ndo(self, struct_item): |
| 373 | struct_member_dict = dict(self.structMembers) |
| 374 | struct_members = struct_member_dict[struct_item] |
| 375 | |
| 376 | for member in struct_members: |
| 377 | if self.isHandleTypeNonDispatchable(member.type): |
| 378 | return True |
| 379 | elif member.type in struct_member_dict: |
| 380 | if self.struct_contains_ndo(member.type) == True: |
| 381 | return True |
| 382 | return False |
| 383 | # |
| 384 | # Return list of struct members which contain, or which sub-structures contain |
| 385 | # an NDO in a given list of parameters or members |
| 386 | def getParmeterStructsWithNdos(self, item_list): |
| 387 | struct_list = set() |
| 388 | for item in item_list: |
| 389 | paramtype = item.find('type') |
| 390 | typecategory = self.getTypeCategory(paramtype.text) |
| 391 | if typecategory == 'struct': |
| 392 | if self.struct_contains_ndo(paramtype.text) == True: |
| 393 | struct_list.add(item) |
| 394 | return struct_list |
| 395 | # |
| 396 | # Return list of non-dispatchable objects from a given list of parameters or members |
| 397 | def getNdosInParameterList(self, item_list, create_func): |
| 398 | ndo_list = set() |
| 399 | if create_func == True: |
| 400 | member_list = item_list[0:-1] |
| 401 | else: |
| 402 | member_list = item_list |
| 403 | for item in member_list: |
| 404 | if self.isHandleTypeNonDispatchable(paramtype.text): |
| 405 | ndo_list.add(item) |
| 406 | return ndo_list |
| 407 | # |
| 408 | # Generate source for creating a non-dispatchable object |
| 409 | def generate_create_ndo_code(self, indent, proto, params, cmd_info): |
| 410 | create_ndo_code = '' |
| 411 | if True in [create_txt in proto.text for create_txt in ['Create', 'Allocate']]: |
| 412 | handle_type = params[-1].find('type') |
| 413 | if self.isHandleTypeNonDispatchable(handle_type.text): |
| 414 | # Check for special case where multiple handles are returned |
| 415 | ndo_array = False |
| 416 | if cmd_info[-1].len is not None: |
| 417 | ndo_array = True; |
| 418 | handle_name = params[-1].find('name') |
| 419 | create_ndo_code += '%sif (VK_SUCCESS == result) {\n' % (indent) |
| 420 | indent = self.incIndent(indent) |
| 421 | create_ndo_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent) |
| 422 | ndo_dest = '*%s' % handle_name.text |
| 423 | if ndo_array == True: |
| 424 | create_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[-1].len) |
| 425 | indent = self.incIndent(indent) |
| 426 | ndo_dest = '%s[index0]' % cmd_info[-1].name |
| 427 | create_ndo_code += '%suint64_t unique_id = global_unique_id++;\n' % (indent) |
| 428 | create_ndo_code += '%sdev_data->unique_id_mapping[unique_id] = reinterpret_cast<uint64_t &>(%s);\n' % (indent, ndo_dest) |
| 429 | create_ndo_code += '%s%s = reinterpret_cast<%s&>(unique_id);\n' % (indent, ndo_dest, handle_type.text) |
| 430 | if ndo_array == True: |
| 431 | indent = self.decIndent(indent) |
| 432 | create_ndo_code += '%s}\n' % indent |
| 433 | indent = self.decIndent(indent) |
| 434 | create_ndo_code += '%s}\n' % (indent) |
| 435 | return create_ndo_code |
| 436 | # |
| 437 | # Generate source for destroying a non-dispatchable object |
| 438 | def generate_destroy_ndo_code(self, indent, proto, cmd_info): |
| 439 | destroy_ndo_code = '' |
| 440 | ndo_array = False |
| 441 | if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]: |
| 442 | # Check for special case where multiple handles are returned |
| 443 | if cmd_info[-1].len is not None: |
| 444 | ndo_array = True; |
| 445 | param = -1 |
| 446 | else: |
| 447 | param = -2 |
| 448 | if self.isHandleTypeNonDispatchable(cmd_info[param].type) == True: |
| 449 | if ndo_array == True: |
| 450 | # This API is freeing an array of handles. Remove them from the unique_id map. |
| 451 | destroy_ndo_code += '%sif ((VK_SUCCESS == result) && (%s)) {\n' % (indent, cmd_info[param].name) |
| 452 | indent = self.incIndent(indent) |
| 453 | destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent) |
| 454 | destroy_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[param].len) |
| 455 | indent = self.incIndent(indent) |
| 456 | destroy_ndo_code += '%s%s handle = %s[index0];\n' % (indent, cmd_info[param].type, cmd_info[param].name) |
| 457 | destroy_ndo_code += '%suint64_t unique_id = reinterpret_cast<uint64_t &>(handle);\n' % (indent) |
| 458 | destroy_ndo_code += '%sdev_data->unique_id_mapping.erase(unique_id);\n' % (indent) |
| 459 | indent = self.decIndent(indent); |
| 460 | destroy_ndo_code += '%s}\n' % indent |
| 461 | indent = self.decIndent(indent); |
| 462 | destroy_ndo_code += '%s}\n' % indent |
| 463 | else: |
| 464 | # Remove a single handle from the map |
| 465 | destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent) |
| 466 | destroy_ndo_code += '%suint64_t %s_id = reinterpret_cast<uint64_t &>(%s);\n' % (indent, cmd_info[param].name, cmd_info[param].name) |
| 467 | 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) |
| 468 | destroy_ndo_code += '%sdev_data->unique_id_mapping.erase(%s_id);\n' % (indent, cmd_info[param].name) |
| 469 | destroy_ndo_code += '%slock.unlock();\n' % (indent) |
| 470 | return ndo_array, destroy_ndo_code |
| 471 | |
| 472 | # |
| 473 | # Clean up local declarations |
| 474 | def cleanUpLocalDeclarations(self, indent, prefix, name, len): |
| 475 | cleanup = '%sif (local_%s%s)\n' % (indent, prefix, name) |
| 476 | if len is not None: |
| 477 | cleanup += '%s delete[] local_%s%s;\n' % (indent, prefix, name) |
| 478 | else: |
| 479 | cleanup += '%s delete local_%s%s;\n' % (indent, prefix, name) |
| 480 | return cleanup |
| 481 | # |
| 482 | # Output UO code for a single NDO (ndo_count is NULL) or a counted list of NDOs |
| 483 | def outputNDOs(self, ndo_type, ndo_name, ndo_count, prefix, index, indent, destroy_func, destroy_array, top_level): |
| 484 | decl_code = '' |
| 485 | pre_call_code = '' |
| 486 | post_call_code = '' |
| 487 | if ndo_count is not None: |
| 488 | if top_level == True: |
| 489 | decl_code += '%s%s *local_%s%s = NULL;\n' % (indent, ndo_type, prefix, ndo_name) |
| 490 | pre_call_code += '%s if (%s%s) {\n' % (indent, prefix, ndo_name) |
| 491 | indent = self.incIndent(indent) |
| 492 | if top_level == True: |
| 493 | pre_call_code += '%s local_%s%s = new %s[%s];\n' % (indent, prefix, ndo_name, ndo_type, ndo_count) |
| 494 | pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index) |
| 495 | indent = self.incIndent(indent) |
| 496 | 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) |
| 497 | else: |
| 498 | pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index) |
| 499 | indent = self.incIndent(indent) |
| 500 | 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) |
| 501 | indent = self.decIndent(indent) |
| 502 | pre_call_code += '%s }\n' % indent |
| 503 | indent = self.decIndent(indent) |
| 504 | pre_call_code += '%s }\n' % indent |
| 505 | if top_level == True: |
| 506 | post_call_code += '%sif (local_%s%s)\n' % (indent, prefix, ndo_name) |
| 507 | indent = self.incIndent(indent) |
| 508 | post_call_code += '%sdelete[] local_%s;\n' % (indent, ndo_name) |
| 509 | else: |
| 510 | if top_level == True: |
| 511 | if (destroy_func == False) or (destroy_array == True): #### LUGMAL This line needs to be skipped for destroy_ndo and not destroy_array |
| 512 | pre_call_code += '%s %s = (%s)dev_data->unique_id_mapping[reinterpret_cast<uint64_t &>(%s)];\n' % (indent, ndo_name, ndo_type, ndo_name) |
| 513 | else: |
| 514 | # Make temp copy of this var with the 'local' removed. It may be better to not pass in 'local_' |
| 515 | # as part of the string and explicitly print it |
| 516 | fix = str(prefix).strip('local_'); |
| 517 | pre_call_code += '%s if (%s%s) {\n' % (indent, fix, ndo_name) |
| 518 | indent = self.incIndent(indent) |
| 519 | 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) |
| 520 | indent = self.decIndent(indent) |
| 521 | pre_call_code += '%s }\n' % indent |
| 522 | return decl_code, pre_call_code, post_call_code |
| 523 | # |
| 524 | # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct |
| 525 | # create_func means that this is API creates or allocates NDOs |
| 526 | # destroy_func indicates that this API destroys or frees NDOs |
| 527 | # destroy_array means that the destroy_func operated on an array of NDOs |
| 528 | def uniquify_members(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, first_level_param): |
| 529 | decls = '' |
| 530 | pre_code = '' |
| 531 | post_code = '' |
| 532 | struct_member_dict = dict(self.structMembers) |
| 533 | index = 'index%s' % str(array_index) |
| 534 | array_index += 1 |
| 535 | # Process any NDOs in this structure and recurse for any sub-structs in this struct |
| 536 | for member in members: |
| 537 | # Handle NDOs |
| 538 | if self.isHandleTypeNonDispatchable(member.type) == True: |
Jamie Madill | 24aa974 | 2016-12-13 17:02:57 -0500 | [diff] [blame^] | 539 | count_name = member.len |
Mark Lobodzinski | a509c29 | 2016-10-11 14:33:07 -0600 | [diff] [blame] | 540 | if (count_name is not None): |
| 541 | if first_level_param == False: |
| 542 | count_name = '%s%s' % (prefix, member.len) |
| 543 | |
| 544 | if (first_level_param == False) or (create_func == False): |
| 545 | (tmp_decl, tmp_pre, tmp_post) = self.outputNDOs(member.type, member.name, count_name, prefix, index, indent, destroy_func, destroy_array, first_level_param) |
| 546 | decls += tmp_decl |
| 547 | pre_code += tmp_pre |
| 548 | post_code += tmp_post |
| 549 | # Handle Structs that contain NDOs at some level |
| 550 | elif member.type in struct_member_dict: |
| 551 | # All structs at first level will have an NDO |
| 552 | if self.struct_contains_ndo(member.type) == True: |
| 553 | struct_info = struct_member_dict[member.type] |
| 554 | # Struct Array |
| 555 | if member.len is not None: |
| 556 | # Update struct prefix |
| 557 | if first_level_param == True: |
| 558 | new_prefix = 'local_%s' % member.name |
| 559 | # Declare safe_VarType for struct |
| 560 | decls += '%ssafe_%s *%s = NULL;\n' % (indent, member.type, new_prefix) |
| 561 | else: |
| 562 | new_prefix = '%s%s' % (prefix, member.name) |
| 563 | pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name) |
| 564 | indent = self.incIndent(indent) |
| 565 | if first_level_param == True: |
| 566 | pre_code += '%s %s = new safe_%s[%s];\n' % (indent, new_prefix, member.type, member.len) |
| 567 | pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index) |
| 568 | indent = self.incIndent(indent) |
| 569 | if first_level_param == True: |
| 570 | pre_code += '%s %s[%s].initialize(&%s[%s]);\n' % (indent, new_prefix, index, member.name, index) |
| 571 | local_prefix = '%s[%s].' % (new_prefix, index) |
| 572 | # Process sub-structs in this struct |
| 573 | (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, local_prefix, array_index, create_func, destroy_func, destroy_array, False) |
| 574 | decls += tmp_decl |
| 575 | pre_code += tmp_pre |
| 576 | post_code += tmp_post |
| 577 | indent = self.decIndent(indent) |
| 578 | pre_code += '%s }\n' % indent |
| 579 | indent = self.decIndent(indent) |
| 580 | pre_code += '%s }\n' % indent |
| 581 | if first_level_param == True: |
| 582 | post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len) |
| 583 | # Single Struct |
| 584 | else: |
| 585 | # Update struct prefix |
| 586 | if first_level_param == True: |
| 587 | new_prefix = 'local_%s->' % member.name |
| 588 | decls += '%ssafe_%s *local_%s%s = NULL;\n' % (indent, member.type, prefix, member.name) |
| 589 | else: |
| 590 | new_prefix = '%s%s->' % (prefix, member.name) |
| 591 | # Declare safe_VarType for struct |
| 592 | pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name) |
| 593 | indent = self.incIndent(indent) |
| 594 | if first_level_param == True: |
| 595 | pre_code += '%s local_%s%s = new safe_%s(%s);\n' % (indent, prefix, member.name, member.type, member.name) |
| 596 | # Process sub-structs in this struct |
| 597 | (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, False) |
| 598 | decls += tmp_decl |
| 599 | pre_code += tmp_pre |
| 600 | post_code += tmp_post |
| 601 | indent = self.decIndent(indent) |
| 602 | pre_code += '%s }\n' % indent |
| 603 | if first_level_param == True: |
| 604 | post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len) |
| 605 | return decls, pre_code, post_code |
| 606 | # |
| 607 | # For a particular API, generate the non-dispatchable-object wrapping/unwrapping code |
| 608 | def generate_wrapping_code(self, cmd): |
| 609 | indent = ' ' |
| 610 | proto = cmd.find('proto/name') |
| 611 | params = cmd.findall('param') |
| 612 | if proto.text is not None: |
| 613 | cmd_member_dict = dict(self.cmdMembers) |
| 614 | cmd_info = cmd_member_dict[proto.text] |
| 615 | # Handle ndo create/allocate operations |
| 616 | if cmd_info[0].iscreate: |
| 617 | create_ndo_code = self.generate_create_ndo_code(indent, proto, params, cmd_info) |
| 618 | else: |
| 619 | create_ndo_code = '' |
| 620 | # Handle ndo destroy/free operations |
| 621 | if cmd_info[0].isdestroy: |
| 622 | (destroy_array, destroy_ndo_code) = self.generate_destroy_ndo_code(indent, proto, cmd_info) |
| 623 | else: |
| 624 | destroy_array = False |
| 625 | destroy_ndo_code = '' |
| 626 | paramdecl = '' |
| 627 | param_pre_code = '' |
| 628 | param_post_code = '' |
| 629 | create_func = True if create_ndo_code else False |
| 630 | destroy_func = True if destroy_ndo_code else False |
| 631 | (paramdecl, param_pre_code, param_post_code) = self.uniquify_members(cmd_info, indent, '', 0, create_func, destroy_func, destroy_array, True) |
| 632 | param_post_code += create_ndo_code |
| 633 | if destroy_ndo_code: |
| 634 | if destroy_array == True: |
| 635 | param_post_code += destroy_ndo_code |
| 636 | else: |
| 637 | param_pre_code += destroy_ndo_code |
| 638 | if param_pre_code: |
| 639 | if (not destroy_func) or (destroy_array): |
| 640 | param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent) |
| 641 | return paramdecl, param_pre_code, param_post_code |
| 642 | # |
| 643 | # Capture command parameter info needed to wrap NDOs as well as handling some boilerplate code |
| 644 | def genCmd(self, cmdinfo, cmdname): |
| 645 | if cmdname in self.interface_functions: |
| 646 | return |
| 647 | if cmdname in self.no_autogen_list: |
| 648 | decls = self.makeCDecls(cmdinfo.elem) |
| 649 | self.appendSection('command', '') |
| 650 | self.appendSection('command', '// Declare only') |
| 651 | self.appendSection('command', decls[0]) |
| 652 | self.intercepts += [ ' {"%s", reinterpret_cast<PFN_vkVoidFunction>(%s)},' % (cmdname,cmdname[2:]) ] |
| 653 | return |
| 654 | # Add struct-member type information to command parameter information |
| 655 | OutputGenerator.genCmd(self, cmdinfo, cmdname) |
| 656 | members = cmdinfo.elem.findall('.//param') |
| 657 | # Iterate over members once to get length parameters for arrays |
| 658 | lens = set() |
| 659 | for member in members: |
| 660 | len = self.getLen(member) |
| 661 | if len: |
| 662 | lens.add(len) |
| 663 | struct_member_dict = dict(self.structMembers) |
| 664 | # Generate member info |
| 665 | membersInfo = [] |
| 666 | for member in members: |
| 667 | # Get type and name of member |
| 668 | info = self.getTypeNameTuple(member) |
| 669 | type = info[0] |
| 670 | name = info[1] |
| 671 | cdecl = self.makeCParamDecl(member, 0) |
| 672 | # Check for parameter name in lens set |
| 673 | iscount = True if name in lens else False |
| 674 | len = self.getLen(member) |
| 675 | isconst = True if 'const' in cdecl else False |
| 676 | ispointer = self.paramIsPointer(member) |
| 677 | # Mark param as local if it is an array of NDOs |
| 678 | islocal = False; |
| 679 | if self.isHandleTypeNonDispatchable(type) == True: |
| 680 | if (len is not None) and (isconst == True): |
| 681 | islocal = True |
| 682 | # Or if it's a struct that contains an NDO |
| 683 | elif type in struct_member_dict: |
| 684 | if self.struct_contains_ndo(type) == True: |
| 685 | islocal = True |
| 686 | |
| 687 | isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False |
| 688 | iscreate = True if True in [create_txt in cmdname for create_txt in ['Create', 'Allocate']] else False |
| 689 | |
| 690 | membersInfo.append(self.CommandParam(type=type, |
| 691 | name=name, |
| 692 | ispointer=ispointer, |
| 693 | isconst=isconst, |
| 694 | iscount=iscount, |
| 695 | len=len, |
| 696 | extstructs=member.attrib.get('validextensionstructs') if name == 'pNext' else None, |
| 697 | cdecl=cdecl, |
| 698 | islocal=islocal, |
| 699 | iscreate=iscreate, |
| 700 | isdestroy=isdestroy)) |
| 701 | self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo)) |
| 702 | # Generate NDO wrapping/unwrapping code for all parameters |
| 703 | (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem) |
| 704 | # If API doesn't contain an NDO's, don't fool with it |
| 705 | if not api_decls and not api_pre and not api_post: |
| 706 | return |
| 707 | # Record that the function will be intercepted |
| 708 | if (self.featureExtraProtect != None): |
| 709 | self.intercepts += [ '#ifdef %s' % self.featureExtraProtect ] |
| 710 | self.intercepts += [ ' {"%s", reinterpret_cast<PFN_vkVoidFunction>(%s)},' % (cmdname,cmdname[2:]) ] |
| 711 | if (self.featureExtraProtect != None): |
| 712 | self.intercepts += [ '#endif' ] |
| 713 | decls = self.makeCDecls(cmdinfo.elem) |
| 714 | self.appendSection('command', '') |
| 715 | self.appendSection('command', decls[0][:-1]) |
| 716 | self.appendSection('command', '{') |
| 717 | # Setup common to call wrappers, first parameter is always dispatchable |
| 718 | dispatchable_type = cmdinfo.elem.find('param/type').text |
| 719 | dispatchable_name = cmdinfo.elem.find('param/name').text |
| 720 | # Generate local instance/pdev/device data lookup |
| 721 | self.appendSection('command', ' layer_data *dev_data = get_my_data_ptr(get_dispatch_key('+dispatchable_name+'), layer_data_map);') |
| 722 | # Handle return values, if any |
| 723 | resulttype = cmdinfo.elem.find('proto/type') |
| 724 | if (resulttype != None and resulttype.text == 'void'): |
| 725 | resulttype = None |
| 726 | if (resulttype != None): |
| 727 | assignresult = resulttype.text + ' result = ' |
| 728 | else: |
| 729 | assignresult = '' |
| 730 | # Pre-pend declarations and pre-api-call codegen |
| 731 | if api_decls: |
| 732 | self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n"))) |
| 733 | if api_pre: |
| 734 | self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n"))) |
| 735 | # Generate the API call itself |
| 736 | # Gather the parameter items |
| 737 | params = cmdinfo.elem.findall('param/name') |
| 738 | # Pull out the text for each of the parameters, separate them by commas in a list |
| 739 | paramstext = ', '.join([str(param.text) for param in params]) |
| 740 | # If any of these paramters has been replaced by a local var, fix up the list |
| 741 | cmd_member_dict = dict(self.cmdMembers) |
| 742 | params = cmd_member_dict[cmdname] |
| 743 | for param in params: |
| 744 | if param.islocal == True: |
| 745 | if param.ispointer == True: |
| 746 | paramstext = paramstext.replace(param.name, '(%s %s*)local_%s' % ('const', param.type, param.name)) |
| 747 | else: |
| 748 | paramstext = paramstext.replace(param.name, '(%s %s)local_%s' % ('const', param.type, param.name)) |
| 749 | # Use correct dispatch table |
| 750 | if dispatchable_type in ["VkPhysicalDevice", "VkInstance"]: |
| 751 | API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->instance_dispatch_table->',1) |
| 752 | else: |
| 753 | API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->device_dispatch_table->',1) |
| 754 | # Put all this together for the final down-chain call |
| 755 | self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');') |
| 756 | # And add the post-API-call codegen |
| 757 | self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n"))) |
| 758 | # Handle the return result variable, if any |
| 759 | if (resulttype != None): |
| 760 | self.appendSection('command', ' return result;') |
| 761 | self.appendSection('command', '}') |