1#!/usr/bin/python3 -i 2# 3# Copyright (c) 2015-2020 The Khronos Group Inc. 4# Copyright (c) 2015-2020 Valve Corporation 5# Copyright (c) 2015-2020 LunarG, Inc. 6# Copyright (c) 2015-2020 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: Mark Lobodzinski <mark@lunarg.com> 21 22import os,re,sys 23import xml.etree.ElementTree as etree 24from generator import * 25from collections import namedtuple 26from common_codegen import * 27 28# 29# DispatchTableHelperOutputGeneratorOptions - subclass of GeneratorOptions. 30class DispatchTableHelperOutputGeneratorOptions(GeneratorOptions): 31 def __init__(self, 32 conventions = None, 33 filename = None, 34 directory = '.', 35 genpath = None, 36 apiname = None, 37 profile = None, 38 versions = '.*', 39 emitversions = '.*', 40 defaultExtensions = None, 41 addExtensions = None, 42 removeExtensions = None, 43 emitExtensions = None, 44 sortProcedure = regSortFeatures, 45 prefixText = "", 46 genFuncPointers = True, 47 apicall = '', 48 apientry = '', 49 apientryp = '', 50 alignFuncParam = 0, 51 expandEnumerants = True): 52 GeneratorOptions.__init__(self, 53 conventions = conventions, 54 filename = filename, 55 directory = directory, 56 genpath = genpath, 57 apiname = apiname, 58 profile = profile, 59 versions = versions, 60 emitversions = emitversions, 61 defaultExtensions = defaultExtensions, 62 addExtensions = addExtensions, 63 removeExtensions = removeExtensions, 64 emitExtensions = emitExtensions, 65 sortProcedure = sortProcedure) 66 self.prefixText = prefixText 67 self.genFuncPointers = genFuncPointers 68 self.prefixText = None 69 self.apicall = apicall 70 self.apientry = apientry 71 self.apientryp = apientryp 72 self.alignFuncParam = alignFuncParam 73# 74# DispatchTableHelperOutputGenerator - subclass of OutputGenerator. 75# Generates dispatch table helper header files for LVL 76class DispatchTableHelperOutputGenerator(OutputGenerator): 77 """Generate dispatch table helper header based on XML element attributes""" 78 def __init__(self, 79 errFile = sys.stderr, 80 warnFile = sys.stderr, 81 diagFile = sys.stdout): 82 OutputGenerator.__init__(self, errFile, warnFile, diagFile) 83 # Internal state - accumulators for different inner block text 84 self.instance_dispatch_list = [] # List of entries for instance dispatch list 85 self.device_dispatch_list = [] # List of entries for device dispatch list 86 self.dev_ext_stub_list = [] # List of stub functions for device extension functions 87 self.stub_list = [] # List of functions with stubs (promoted or extensions) 88 self.extension_type = '' 89 90 # 91 # Called once at the beginning of each run 92 def beginFile(self, genOpts): 93 OutputGenerator.beginFile(self, genOpts) 94 95 # Initialize members that require the tree 96 self.handle_types = GetHandleTypes(self.registry.tree) 97 98 write("#pragma once", file=self.outFile) 99 # User-supplied prefix text, if any (list of strings) 100 if (genOpts.prefixText): 101 for s in genOpts.prefixText: 102 write(s, file=self.outFile) 103 # File Comment 104 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n' 105 file_comment += '// See dispatch_helper_generator.py for modifications\n' 106 write(file_comment, file=self.outFile) 107 # Copyright Notice 108 copyright = '/*\n' 109 copyright += ' * Copyright (c) 2015-2020 The Khronos Group Inc.\n' 110 copyright += ' * Copyright (c) 2015-2020 Valve Corporation\n' 111 copyright += ' * Copyright (c) 2015-2020 LunarG, Inc.\n' 112 copyright += ' *\n' 113 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n' 114 copyright += ' * you may not use this file except in compliance with the License.\n' 115 copyright += ' * You may obtain a copy of the License at\n' 116 copyright += ' *\n' 117 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n' 118 copyright += ' *\n' 119 copyright += ' * Unless required by applicable law or agreed to in writing, software\n' 120 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n' 121 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n' 122 copyright += ' * See the License for the specific language governing permissions and\n' 123 copyright += ' * limitations under the License.\n' 124 copyright += ' *\n' 125 copyright += ' * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>\n' 126 copyright += ' * Author: Jon Ashburn <jon@lunarg.com>\n' 127 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n' 128 copyright += ' */\n' 129 130 preamble = '' 131 preamble += '#include <vulkan/vulkan.h>\n' 132 preamble += '#include <vulkan/vk_layer.h>\n' 133 preamble += '#include <cstring>\n' 134 preamble += '#include <string>\n' 135 preamble += '#include <unordered_set>\n' 136 preamble += '#include <unordered_map>\n' 137 preamble += '#include "vk_layer_dispatch_table.h"\n' 138 preamble += '#include "vk_extension_helper.h"\n' 139 140 write(copyright, file=self.outFile) 141 write(preamble, file=self.outFile) 142 # 143 # Write generate and write dispatch tables to output file 144 def endFile(self): 145 ext_enabled_fcn = '' 146 device_table = '' 147 instance_table = '' 148 ext_enabled_fcn += self.OutputExtEnabledFunction() 149 device_table += self.OutputDispatchTableHelper('device') 150 instance_table += self.OutputDispatchTableHelper('instance') 151 152 for stub in self.dev_ext_stub_list: 153 write(stub, file=self.outFile) 154 155 write("\n\n", file=self.outFile) 156 write(ext_enabled_fcn, file=self.outFile) 157 write("\n", file=self.outFile) 158 write(device_table, file=self.outFile); 159 write("\n", file=self.outFile) 160 write(instance_table, file=self.outFile); 161 162 # Finish processing in superclass 163 OutputGenerator.endFile(self) 164 # 165 # Processing at beginning of each feature or extension 166 def beginFeature(self, interface, emit): 167 OutputGenerator.beginFeature(self, interface, emit) 168 self.featureExtraProtect = GetFeatureProtect(interface) 169 self.extension_type = interface.get('type') 170 # 171 # Process commands, adding to appropriate dispatch tables 172 def genCmd(self, cmdinfo, name, alias): 173 OutputGenerator.genCmd(self, cmdinfo, name, alias) 174 175 avoid_entries = ['vkCreateInstance', 176 'vkCreateDevice'] 177 # Get first param type 178 params = cmdinfo.elem.findall('param') 179 info = self.getTypeNameTuple(params[0]) 180 181 if name not in avoid_entries: 182 self.AddCommandToDispatchList(name, info[0], self.featureExtraProtect, cmdinfo) 183 184 # 185 # Determine if this API should be ignored or added to the instance or device dispatch table 186 def AddCommandToDispatchList(self, name, handle_type, protect, cmdinfo): 187 if handle_type not in self.handle_types: 188 return 189 extension = "VK_VERSION" not in self.featureName 190 promoted = not extension and "VK_VERSION_1_0" != self.featureName 191 if promoted or extension: 192 # We want feature written for all promoted entrypoints in addition to extensions 193 self.stub_list.append([name, self.featureName]) 194 # Build up stub function 195 return_type = '' 196 decl = self.makeCDecls(cmdinfo.elem)[1] 197 if decl.startswith('typedef VkResult'): 198 return_type = 'return VK_SUCCESS;' 199 elif decl.startswith('typedef VkDeviceAddress'): 200 return_type = 'return 0;' 201 elif decl.startswith('typedef uint32_t'): 202 return_type = 'return 0;' 203 elif decl.startswith('typedef uint64_t'): 204 return_type = 'return 0;' 205 elif decl.startswith('typedef VkBool32'): 206 return_type = 'return VK_FALSE;' 207 pre_decl, decl = decl.split('*PFN_vk') 208 pre_decl = pre_decl.replace('typedef ', '') 209 pre_decl = pre_decl.split(' (')[0] 210 decl = decl.replace(')(', '(') 211 decl = 'static VKAPI_ATTR ' + pre_decl + ' VKAPI_CALL Stub' + decl 212 func_body = ' { ' + return_type + ' };' 213 decl = decl.replace (';', func_body) 214 if self.featureExtraProtect is not None: 215 self.dev_ext_stub_list.append('#ifdef %s' % self.featureExtraProtect) 216 self.dev_ext_stub_list.append(decl) 217 if self.featureExtraProtect is not None: 218 self.dev_ext_stub_list.append('#endif // %s' % self.featureExtraProtect) 219 if handle_type != 'VkInstance' and handle_type != 'VkPhysicalDevice' and name != 'vkGetInstanceProcAddr': 220 self.device_dispatch_list.append((name, self.featureExtraProtect)) 221 else: 222 self.instance_dispatch_list.append((name, self.featureExtraProtect)) 223 return 224 # 225 # Retrieve the type and name for a parameter 226 def getTypeNameTuple(self, param): 227 type = '' 228 name = '' 229 for elem in param: 230 if elem.tag == 'type': 231 type = noneStr(elem.text) 232 elif elem.tag == 'name': 233 name = noneStr(elem.text) 234 return (type, name) 235 # 236 # Output a function that'll determine if an extension is in the enabled list 237 def OutputExtEnabledFunction(self): 238 ext_fcn = '' 239 # First, write out our static data structure -- map of all APIs that are part of extensions to their extension. 240 ext_fcn += 'const std::unordered_map<std::string, std::string> api_extension_map {\n' 241 api_ext = dict() 242 handles = GetHandleTypes(self.registry.tree) 243 features = self.registry.tree.findall('feature') + self.registry.tree.findall('extensions/extension') 244 for feature in features: 245 feature_name = feature.get('name') 246 if 'VK_VERSION_1_0' == feature_name: 247 continue 248 for require_element in feature.findall('require'): 249 for command in require_element.findall('command'): 250 command_name = command.get('name') 251 if 'EnumerateInstanceVersion' in command_name: 252 continue 253 disp_obj = self.registry.tree.find("commands/command/[@name='%s']/param/type" % command_name) 254 if disp_obj is None: 255 cmd_info = self.registry.tree.find("commands/command/[@name='%s']" % command_name) 256 alias_name = cmd_info.get('alias') 257 if alias_name is not None: 258 disp_obj = self.registry.tree.find("commands/command/[@name='%s']/param/type" % alias_name) 259 if 'VkInstance' != disp_obj.text and 'VkPhysicalDevice' != disp_obj.text: 260 # Ensure APIs belonging to multiple extensions match the existing order 261 if command_name not in api_ext: 262 api_ext[command_name] = feature_name 263 for api in sorted(api_ext): 264 ext_fcn += ' {"%s", "%s"},\n' % (api, api_ext[api]) 265 ext_fcn += '};\n\n' 266 ext_fcn += '// Using the above code-generated map of APINames-to-parent extension names, this function will:\n' 267 ext_fcn += '// o Determine if the API has an associated extension\n' 268 ext_fcn += '// o If it does, determine if that extension name is present in the passed-in set of enabled_ext_names \n' 269 ext_fcn += '// If the APIname has no parent extension, OR its parent extension name is IN the set, return TRUE, else FALSE\n' 270 ext_fcn += 'static inline bool ApiParentExtensionEnabled(const std::string api_name, const DeviceExtensions *device_extension_info) {\n' 271 ext_fcn += ' auto has_ext = api_extension_map.find(api_name);\n' 272 ext_fcn += ' // Is this API part of an extension or feature group?\n' 273 ext_fcn += ' if (has_ext != api_extension_map.end()) {\n' 274 ext_fcn += ' // Was the extension for this API enabled in the CreateDevice call?\n' 275 ext_fcn += ' auto info = device_extension_info->get_info(has_ext->second.c_str());\n' 276 ext_fcn += ' if ((!info.state) || (device_extension_info->*(info.state) != kEnabledByCreateinfo)) {\n' 277 ext_fcn += ' return false;\n' 278 ext_fcn += ' }\n' 279 ext_fcn += ' }\n' 280 ext_fcn += ' return true;\n' 281 ext_fcn += '}\n' 282 return ext_fcn 283 # 284 # Create a dispatch table from the appropriate list and return it as a string 285 def OutputDispatchTableHelper(self, table_type): 286 entries = [] 287 table = '' 288 if table_type == 'device': 289 entries = self.device_dispatch_list 290 table += 'static inline void layer_init_device_dispatch_table(VkDevice device, VkLayerDispatchTable *table, PFN_vkGetDeviceProcAddr gpa) {\n' 291 table += ' memset(table, 0, sizeof(*table));\n' 292 table += ' // Device function pointers\n' 293 else: 294 entries = self.instance_dispatch_list 295 table += 'static inline void layer_init_instance_dispatch_table(VkInstance instance, VkLayerInstanceDispatchTable *table, PFN_vkGetInstanceProcAddr gpa) {\n' 296 table += ' memset(table, 0, sizeof(*table));\n' 297 table += ' // Instance function pointers\n' 298 299 stubbed_functions = dict(self.stub_list) 300 for item in entries: 301 # Remove 'vk' from proto name 302 base_name = item[0][2:] 303 304 if item[1] is not None: 305 table += '#ifdef %s\n' % item[1] 306 307 # If we're looking for the proc we are passing in, just point the table to it. This fixes the issue where 308 # a layer overrides the function name for the loader. 309 if ('device' in table_type and base_name == 'GetDeviceProcAddr'): 310 table += ' table->GetDeviceProcAddr = gpa;\n' 311 elif ('device' not in table_type and base_name == 'GetInstanceProcAddr'): 312 table += ' table->GetInstanceProcAddr = gpa;\n' 313 else: 314 table += ' table->%s = (PFN_%s) gpa(%s, "%s");\n' % (base_name, item[0], table_type, item[0]) 315 if item[0] in stubbed_functions: 316 stub_check = ' if (table->%s == nullptr) { table->%s = (PFN_%s)Stub%s; }\n' % (base_name, base_name, item[0], base_name) 317 table += stub_check 318 if item[1] is not None: 319 table += '#endif // %s\n' % item[1] 320 321 table += '}' 322 return table 323