Turn all function static non-POD variables into global POD variables

Function static non-POD data causes problems with DLL lifetime.
This pull request turns all static info tables into strict POD
tables. Specifically, the capabilities/extensions field of
opcode/operand/extended-instruction table are turned into two
fields, one for the count and the other a pointer to an array of
capabilities/extensions. CapabilitySet/EnumSet are not used in
the static table anymore, but they are still used for checking
inclusion by constructing on the fly, which should be cheap for
the majority cases.

Also moves all these tables into the global namespace to avoid
C++11 function static thread-safe initialization overhead.
This commit is contained in:
Lei Zhang 2017-10-25 12:15:51 -04:00
Родитель 90862fe4b1
Коммит 063dbea0f1
13 изменённых файлов: 297 добавлений и 229 удалений

Просмотреть файл

@ -46,6 +46,9 @@ class EnumSet {
EnumSet(std::initializer_list<EnumType> cs) { EnumSet(std::initializer_list<EnumType> cs) {
for (auto c : cs) Add(c); for (auto c : cs) Add(c);
} }
EnumSet(uint32_t count, const EnumType* ptr) {
for (uint32_t i = 0; i < count; ++i) Add(ptr[i]);
}
// Copy constructor. // Copy constructor.
EnumSet(const EnumSet& other) { *this = other; } EnumSet(const EnumSet& other) { *this = other; }
// Move constructor. The moved-from set is emptied. // Move constructor. The moved-from set is emptied.
@ -95,15 +98,12 @@ class EnumSet {
bool HasAnyOf(const EnumSet<EnumType>& in_set) const { bool HasAnyOf(const EnumSet<EnumType>& in_set) const {
if (in_set.IsEmpty()) return true; if (in_set.IsEmpty()) return true;
if (mask_ & in_set.mask_) if (mask_ & in_set.mask_) return true;
return true;
if (!overflow_ || !in_set.overflow_) if (!overflow_ || !in_set.overflow_) return false;
return false;
for (uint32_t item : *in_set.overflow_) { for (uint32_t item : *in_set.overflow_) {
if (overflow_->find(item) != overflow_->end()) if (overflow_->find(item) != overflow_->end()) return true;
return true;
} }
return false; return false;

Просмотреть файл

@ -19,9 +19,9 @@
#include "spirv/1.1/spirv.h" #include "spirv/1.1/spirv.h"
namespace libspirv { #include "extensions.h"
enum class Extension; namespace libspirv {
// Finds Extension enum corresponding to |str|. Returns false if not found. // Finds Extension enum corresponding to |str|. Returns false if not found.
bool GetExtensionFromString(const std::string& str, Extension* extension); bool GetExtensionFromString(const std::string& str, Extension* extension);

Просмотреть файл

@ -23,56 +23,36 @@
#include "macro.h" #include "macro.h"
#include "glsl.std.450.insts-1.0.inc" // defines glsl_entries
#include "opencl.std.insts-1.0.inc" // defines opencl_entries
#include "spv-amd-gcn-shader.insts.inc"
#include "spv-amd-shader-ballot.insts.inc"
#include "spv-amd-shader-explicit-vertex-parameter.insts.inc"
#include "spv-amd-shader-trinary-minmax.insts.inc"
static const spv_ext_inst_group_t kGroups_1_0[] = {
{SPV_EXT_INST_TYPE_GLSL_STD_450, ARRAY_SIZE(glsl_entries), glsl_entries},
{SPV_EXT_INST_TYPE_OPENCL_STD, ARRAY_SIZE(opencl_entries), opencl_entries},
{SPV_EXT_INST_TYPE_SPV_AMD_SHADER_EXPLICIT_VERTEX_PARAMETER,
ARRAY_SIZE(spv_amd_shader_explicit_vertex_parameter_entries),
spv_amd_shader_explicit_vertex_parameter_entries},
{SPV_EXT_INST_TYPE_SPV_AMD_SHADER_TRINARY_MINMAX,
ARRAY_SIZE(spv_amd_shader_trinary_minmax_entries),
spv_amd_shader_trinary_minmax_entries},
{SPV_EXT_INST_TYPE_SPV_AMD_GCN_SHADER,
ARRAY_SIZE(spv_amd_gcn_shader_entries), spv_amd_gcn_shader_entries},
{SPV_EXT_INST_TYPE_SPV_AMD_SHADER_BALLOT,
ARRAY_SIZE(spv_amd_shader_ballot_entries), spv_amd_shader_ballot_entries},
};
static const spv_ext_inst_table_t kTable_1_0 = {ARRAY_SIZE(kGroups_1_0),
kGroups_1_0};
spv_result_t spvExtInstTableGet(spv_ext_inst_table* pExtInstTable, spv_result_t spvExtInstTableGet(spv_ext_inst_table* pExtInstTable,
spv_target_env env) { spv_target_env env) {
if (!pExtInstTable) return SPV_ERROR_INVALID_POINTER; if (!pExtInstTable) return SPV_ERROR_INVALID_POINTER;
static const spv_ext_inst_desc_t glslStd450Entries_1_0[] = {
#include "glsl.std.450.insts-1.0.inc"
};
static const spv_ext_inst_desc_t openclEntries_1_0[] = {
#include "opencl.std.insts-1.0.inc"
};
static const spv_ext_inst_desc_t
spv_amd_shader_explicit_vertex_parameter_entries[] = {
#include "spv-amd-shader-explicit-vertex-parameter.insts.inc"
};
static const spv_ext_inst_desc_t spv_amd_shader_trinary_minmax_entries[] = {
#include "spv-amd-shader-trinary-minmax.insts.inc"
};
static const spv_ext_inst_desc_t spv_amd_gcn_shader_entries[] = {
#include "spv-amd-gcn-shader.insts.inc"
};
static const spv_ext_inst_desc_t spv_amd_shader_ballot_entries[] = {
#include "spv-amd-shader-ballot.insts.inc"
};
static const spv_ext_inst_group_t groups_1_0[] = {
{SPV_EXT_INST_TYPE_GLSL_STD_450, ARRAY_SIZE(glslStd450Entries_1_0),
glslStd450Entries_1_0},
{SPV_EXT_INST_TYPE_OPENCL_STD, ARRAY_SIZE(openclEntries_1_0),
openclEntries_1_0},
{SPV_EXT_INST_TYPE_SPV_AMD_SHADER_EXPLICIT_VERTEX_PARAMETER,
ARRAY_SIZE(spv_amd_shader_explicit_vertex_parameter_entries),
spv_amd_shader_explicit_vertex_parameter_entries},
{SPV_EXT_INST_TYPE_SPV_AMD_SHADER_TRINARY_MINMAX,
ARRAY_SIZE(spv_amd_shader_trinary_minmax_entries),
spv_amd_shader_trinary_minmax_entries},
{SPV_EXT_INST_TYPE_SPV_AMD_GCN_SHADER,
ARRAY_SIZE(spv_amd_gcn_shader_entries), spv_amd_gcn_shader_entries},
{SPV_EXT_INST_TYPE_SPV_AMD_SHADER_BALLOT,
ARRAY_SIZE(spv_amd_shader_ballot_entries),
spv_amd_shader_ballot_entries},
};
static const spv_ext_inst_table_t table_1_0 = {ARRAY_SIZE(groups_1_0),
groups_1_0};
switch (env) { switch (env) {
// The extended instruction sets are all version 1.0 so far. // The extended instruction sets are all version 1.0 so far.
case SPV_ENV_UNIVERSAL_1_0: case SPV_ENV_UNIVERSAL_1_0:
@ -86,7 +66,7 @@ spv_result_t spvExtInstTableGet(spv_ext_inst_table* pExtInstTable,
case SPV_ENV_OPENGL_4_2: case SPV_ENV_OPENGL_4_2:
case SPV_ENV_OPENGL_4_3: case SPV_ENV_OPENGL_4_3:
case SPV_ENV_OPENGL_4_5: case SPV_ENV_OPENGL_4_5:
*pExtInstTable = &table_1_0; *pExtInstTable = &kTable_1_0;
return SPV_SUCCESS; return SPV_SUCCESS;
default: default:
assert(0 && "Unknown spv_target_env in spvExtInstTableGet()"); assert(0 && "Unknown spv_target_env in spvExtInstTableGet()");

Просмотреть файл

@ -23,7 +23,7 @@
namespace libspirv { namespace libspirv {
// The known SPIR-V extensions. // The known SPIR-V extensions.
enum class Extension { enum Extension {
#include "extension_enum.inc" #include "extension_enum.inc"
}; };

Просмотреть файл

@ -32,13 +32,16 @@ struct OpcodeDescPtrLen {
uint32_t len; uint32_t len;
}; };
OpcodeDescPtrLen getOpcodeTableEntries_1_2() { #include "core.insts-1.0.inc" // defines kOpcodeTableEntries_1_0
static const spv_opcode_desc_t opcodeTableEntries_1_2[] = { #include "core.insts-1.1.inc" // defines kOpcodeTableEntries_1_1
#include "core.insts-1.2.inc" #include "core.insts-1.2.inc" // defines kOpcodeTableEntries_1_2
};
return {opcodeTableEntries_1_2, ARRAY_SIZE(opcodeTableEntries_1_2)}; static const spv_opcode_table_t kTable_1_0 = {
} ARRAY_SIZE(kOpcodeTableEntries_1_0), kOpcodeTableEntries_1_0};
static const spv_opcode_table_t kTable_1_1 = {
ARRAY_SIZE(kOpcodeTableEntries_1_1), kOpcodeTableEntries_1_1};
static const spv_opcode_table_t kTable_1_2 = {
ARRAY_SIZE(kOpcodeTableEntries_1_2), kOpcodeTableEntries_1_2};
// Represents a vendor tool entry in the SPIR-V XML Regsitry. // Represents a vendor tool entry in the SPIR-V XML Regsitry.
struct VendorTool { struct VendorTool {
@ -84,20 +87,6 @@ spv_result_t spvOpcodeTableGet(spv_opcode_table* pInstTable,
// Descriptions of each opcode. Each entry describes the format of the // Descriptions of each opcode. Each entry describes the format of the
// instruction that follows a particular opcode. // instruction that follows a particular opcode.
static const spv_opcode_desc_t opcodeTableEntries_1_0[] = {
#include "core.insts-1.0.inc"
};
static const spv_opcode_desc_t opcodeTableEntries_1_1[] = {
#include "core.insts-1.1.inc"
};
const auto ptr_len = getOpcodeTableEntries_1_2();
static const spv_opcode_table_t table_1_0 = {
ARRAY_SIZE(opcodeTableEntries_1_0), opcodeTableEntries_1_0};
static const spv_opcode_table_t table_1_1 = {
ARRAY_SIZE(opcodeTableEntries_1_1), opcodeTableEntries_1_1};
static const spv_opcode_table_t table_1_2 = {ptr_len.len, ptr_len.ptr};
switch (env) { switch (env) {
case SPV_ENV_UNIVERSAL_1_0: case SPV_ENV_UNIVERSAL_1_0:
@ -108,14 +97,14 @@ spv_result_t spvOpcodeTableGet(spv_opcode_table* pInstTable,
case SPV_ENV_OPENGL_4_2: case SPV_ENV_OPENGL_4_2:
case SPV_ENV_OPENGL_4_3: case SPV_ENV_OPENGL_4_3:
case SPV_ENV_OPENGL_4_5: case SPV_ENV_OPENGL_4_5:
*pInstTable = &table_1_0; *pInstTable = &kTable_1_0;
return SPV_SUCCESS; return SPV_SUCCESS;
case SPV_ENV_UNIVERSAL_1_1: case SPV_ENV_UNIVERSAL_1_1:
*pInstTable = &table_1_1; *pInstTable = &kTable_1_1;
return SPV_SUCCESS; return SPV_SUCCESS;
case SPV_ENV_UNIVERSAL_1_2: case SPV_ENV_UNIVERSAL_1_2:
case SPV_ENV_OPENCL_2_2: case SPV_ENV_OPENCL_2_2:
*pInstTable = &table_1_2; *pInstTable = &kTable_1_2;
return SPV_SUCCESS; return SPV_SUCCESS;
} }
assert(0 && "Unknown spv_target_env in spvOpcodeTableGet()"); assert(0 && "Unknown spv_target_env in spvOpcodeTableGet()");
@ -183,10 +172,9 @@ void spvInstructionCopy(const uint32_t* words, const SpvOp opcode,
const char* spvOpcodeString(const SpvOp opcode) { const char* spvOpcodeString(const SpvOp opcode) {
// Use the latest SPIR-V version, which should be backward-compatible with all // Use the latest SPIR-V version, which should be backward-compatible with all
// previous ones. // previous ones.
const auto entries = getOpcodeTableEntries_1_2(); for (uint32_t i = 0; i < ARRAY_SIZE(kOpcodeTableEntries_1_2); ++i) {
if (kOpcodeTableEntries_1_2[i].opcode == opcode)
for (uint32_t i = 0; i < entries.len; ++i) { return kOpcodeTableEntries_1_2[i].name;
if (entries.ptr[i].opcode == opcode) return entries.ptr[i].name;
} }
assert(0 && "Unreachable!"); assert(0 && "Unreachable!");

Просмотреть файл

@ -20,23 +20,23 @@
#include "macro.h" #include "macro.h"
spv_result_t spvOperandTableGet(spv_operand_table* pOperandTable,
spv_target_env env) {
if (!pOperandTable) return SPV_ERROR_INVALID_POINTER;
#include "operand.kinds-1.0.inc" #include "operand.kinds-1.0.inc"
#include "operand.kinds-1.1.inc" #include "operand.kinds-1.1.inc"
#include "operand.kinds-1.2.inc" #include "operand.kinds-1.2.inc"
static const spv_operand_table_t table_1_0 = { static const spv_operand_table_t kTable_1_0 = {
ARRAY_SIZE(pygen_variable_OperandInfoTable_1_0), ARRAY_SIZE(pygen_variable_OperandInfoTable_1_0),
pygen_variable_OperandInfoTable_1_0}; pygen_variable_OperandInfoTable_1_0};
static const spv_operand_table_t table_1_1 = { static const spv_operand_table_t kTable_1_1 = {
ARRAY_SIZE(pygen_variable_OperandInfoTable_1_1), ARRAY_SIZE(pygen_variable_OperandInfoTable_1_1),
pygen_variable_OperandInfoTable_1_1}; pygen_variable_OperandInfoTable_1_1};
static const spv_operand_table_t table_1_2 = { static const spv_operand_table_t kTable_1_2 = {
ARRAY_SIZE(pygen_variable_OperandInfoTable_1_2), ARRAY_SIZE(pygen_variable_OperandInfoTable_1_2),
pygen_variable_OperandInfoTable_1_2}; pygen_variable_OperandInfoTable_1_2};
spv_result_t spvOperandTableGet(spv_operand_table* pOperandTable,
spv_target_env env) {
if (!pOperandTable) return SPV_ERROR_INVALID_POINTER;
switch (env) { switch (env) {
case SPV_ENV_UNIVERSAL_1_0: case SPV_ENV_UNIVERSAL_1_0:
@ -47,14 +47,14 @@ spv_result_t spvOperandTableGet(spv_operand_table* pOperandTable,
case SPV_ENV_OPENGL_4_2: case SPV_ENV_OPENGL_4_2:
case SPV_ENV_OPENGL_4_3: case SPV_ENV_OPENGL_4_3:
case SPV_ENV_OPENGL_4_5: case SPV_ENV_OPENGL_4_5:
*pOperandTable = &table_1_0; *pOperandTable = &kTable_1_0;
return SPV_SUCCESS; return SPV_SUCCESS;
case SPV_ENV_UNIVERSAL_1_1: case SPV_ENV_UNIVERSAL_1_1:
*pOperandTable = &table_1_1; *pOperandTable = &kTable_1_1;
return SPV_SUCCESS; return SPV_SUCCESS;
case SPV_ENV_UNIVERSAL_1_2: case SPV_ENV_UNIVERSAL_1_2:
case SPV_ENV_OPENCL_2_2: case SPV_ENV_OPENCL_2_2:
*pOperandTable = &table_1_2; *pOperandTable = &kTable_1_2;
return SPV_SUCCESS; return SPV_SUCCESS;
} }
assert(0 && "Unknown spv_target_env in spvOperandTableGet()"); assert(0 && "Unknown spv_target_env in spvOperandTableGet()");

Просмотреть файл

@ -24,7 +24,8 @@
typedef struct spv_opcode_desc_t { typedef struct spv_opcode_desc_t {
const char* name; const char* name;
const SpvOp opcode; const SpvOp opcode;
const libspirv::CapabilitySet capabilities; const uint32_t numCapabilities;
const SpvCapability* capabilities;
// operandTypes[0..numTypes-1] describe logical operands for the instruction. // operandTypes[0..numTypes-1] describe logical operands for the instruction.
// The operand types include result id and result-type id, followed by // The operand types include result id and result-type id, followed by
// the types of arguments. // the types of arguments.
@ -37,12 +38,14 @@ typedef struct spv_opcode_desc_t {
typedef struct spv_operand_desc_t { typedef struct spv_operand_desc_t {
const char* name; const char* name;
const uint32_t value; const uint32_t value;
const libspirv::CapabilitySet capabilities; const uint32_t numCapabilities;
const SpvCapability* capabilities;
// A set of extensions that enable this feature. If empty then this operand // A set of extensions that enable this feature. If empty then this operand
// value is always enabled, i.e. it's in core. The assembler, binary parser, // value is always enabled, i.e. it's in core. The assembler, binary parser,
// and disassembler ignore this rule, so you can freely process invalid // and disassembler ignore this rule, so you can freely process invalid
// modules. // modules.
const libspirv::ExtensionSet extensions; const uint32_t numExtensions;
const libspirv::Extension* extensions;
const spv_operand_type_t operandTypes[16]; // TODO: Smaller/larger? const spv_operand_type_t operandTypes[16]; // TODO: Smaller/larger?
} spv_operand_desc_t; } spv_operand_desc_t;
@ -55,7 +58,8 @@ typedef struct spv_operand_desc_group_t {
typedef struct spv_ext_inst_desc_t { typedef struct spv_ext_inst_desc_t {
const char* name; const char* name;
const uint32_t ext_inst; const uint32_t ext_inst;
const libspirv::CapabilitySet capabilities; const uint32_t numCapabilities;
const SpvCapability* capabilities;
const spv_operand_type_t operandTypes[16]; // TODO: Smaller/larger? const spv_operand_type_t operandTypes[16]; // TODO: Smaller/larger?
} spv_ext_inst_desc_t; } spv_ext_inst_desc_t;

Просмотреть файл

@ -215,15 +215,13 @@ bool ValidationState_t::IsDefinedId(uint32_t id) const {
const Instruction* ValidationState_t::FindDef(uint32_t id) const { const Instruction* ValidationState_t::FindDef(uint32_t id) const {
auto it = all_definitions_.find(id); auto it = all_definitions_.find(id);
if (it == all_definitions_.end()) if (it == all_definitions_.end()) return nullptr;
return nullptr;
return it->second; return it->second;
} }
Instruction* ValidationState_t::FindDef(uint32_t id) { Instruction* ValidationState_t::FindDef(uint32_t id) {
auto it = all_definitions_.find(id); auto it = all_definitions_.find(id);
if (it == all_definitions_.end()) if (it == all_definitions_.end()) return nullptr;
return nullptr;
return it->second; return it->second;
} }
@ -283,8 +281,8 @@ void ValidationState_t::RegisterCapability(SpvCapability cap) {
spv_operand_desc desc; spv_operand_desc desc;
if (SPV_SUCCESS == if (SPV_SUCCESS ==
grammar_.lookupOperand(SPV_OPERAND_TYPE_CAPABILITY, cap, &desc)) { grammar_.lookupOperand(SPV_OPERAND_TYPE_CAPABILITY, cap, &desc)) {
desc->capabilities.ForEach( CapabilitySet(desc->numCapabilities, desc->capabilities)
[this](SpvCapability c) { RegisterCapability(c); }); .ForEach([this](SpvCapability c) { RegisterCapability(c); });
} }
switch (cap) { switch (cap) {
@ -464,8 +462,7 @@ uint32_t ValidationState_t::GetComponentType(uint32_t id) const {
break; break;
} }
if (inst->type_id()) if (inst->type_id()) return GetComponentType(inst->type_id());
return GetComponentType(inst->type_id());
assert(0); assert(0);
return 0; return 0;
@ -489,8 +486,7 @@ uint32_t ValidationState_t::GetDimension(uint32_t id) const {
break; break;
} }
if (inst->type_id()) if (inst->type_id()) return GetDimension(inst->type_id());
return GetDimension(inst->type_id());
assert(0); assert(0);
return 0; return 0;
@ -504,8 +500,7 @@ uint32_t ValidationState_t::GetBitWidth(uint32_t id) const {
if (inst->opcode() == SpvOpTypeFloat || inst->opcode() == SpvOpTypeInt) if (inst->opcode() == SpvOpTypeFloat || inst->opcode() == SpvOpTypeInt)
return inst->word(2); return inst->word(2);
if (inst->opcode() == SpvOpTypeBool) if (inst->opcode() == SpvOpTypeBool) return 1;
return 1;
assert(0); assert(0);
return 0; return 0;
@ -607,16 +602,15 @@ bool ValidationState_t::IsFloatMatrixType(uint32_t id) const {
return false; return false;
} }
bool ValidationState_t::GetMatrixTypeInfo( bool ValidationState_t::GetMatrixTypeInfo(uint32_t id, uint32_t* num_rows,
uint32_t id, uint32_t* num_rows, uint32_t* num_cols, uint32_t* num_cols,
uint32_t* column_type, uint32_t* component_type) const { uint32_t* column_type,
if (!id) uint32_t* component_type) const {
return false; if (!id) return false;
const Instruction* mat_inst = FindDef(id); const Instruction* mat_inst = FindDef(id);
assert(mat_inst); assert(mat_inst);
if (mat_inst->opcode() != SpvOpTypeMatrix) if (mat_inst->opcode() != SpvOpTypeMatrix) return false;
return false;
const uint32_t vec_type = mat_inst->word(2); const uint32_t vec_type = mat_inst->word(2);
const Instruction* vec_inst = FindDef(vec_type); const Instruction* vec_inst = FindDef(vec_type);
@ -638,19 +632,16 @@ bool ValidationState_t::GetMatrixTypeInfo(
bool ValidationState_t::GetStructMemberTypes( bool ValidationState_t::GetStructMemberTypes(
uint32_t struct_type_id, std::vector<uint32_t>* member_types) const { uint32_t struct_type_id, std::vector<uint32_t>* member_types) const {
member_types->clear(); member_types->clear();
if (!struct_type_id) if (!struct_type_id) return false;
return false;
const Instruction* inst = FindDef(struct_type_id); const Instruction* inst = FindDef(struct_type_id);
assert(inst); assert(inst);
if (inst->opcode() != SpvOpTypeStruct) if (inst->opcode() != SpvOpTypeStruct) return false;
return false;
*member_types = std::vector<uint32_t>(inst->words().cbegin() + 2, *member_types =
inst->words().cend()); std::vector<uint32_t>(inst->words().cbegin() + 2, inst->words().cend());
if (member_types->empty()) if (member_types->empty()) return false;
return false;
return true; return true;
} }
@ -661,15 +652,13 @@ bool ValidationState_t::IsPointerType(uint32_t id) const {
return inst->opcode() == SpvOpTypePointer; return inst->opcode() == SpvOpTypePointer;
} }
bool ValidationState_t::GetPointerTypeInfo( bool ValidationState_t::GetPointerTypeInfo(uint32_t id, uint32_t* data_type,
uint32_t id, uint32_t* data_type, uint32_t* storage_class) const { uint32_t* storage_class) const {
if (!id) if (!id) return false;
return false;
const Instruction* inst = FindDef(id); const Instruction* inst = FindDef(id);
assert(inst); assert(inst);
if (inst->opcode() != SpvOpTypePointer) if (inst->opcode() != SpvOpTypePointer) return false;
return false;
*storage_class = inst->word(2); *storage_class = inst->word(2);
*data_type = inst->word(3); *data_type = inst->word(3);
@ -677,12 +666,11 @@ bool ValidationState_t::GetPointerTypeInfo(
} }
uint32_t ValidationState_t::GetOperandTypeId( uint32_t ValidationState_t::GetOperandTypeId(
const spv_parsed_instruction_t* inst, const spv_parsed_instruction_t* inst, size_t operand_index) const {
size_t operand_index) const {
assert(operand_index < inst->num_operands); assert(operand_index < inst->num_operands);
const spv_parsed_operand_t& operand = inst->operands[operand_index]; const spv_parsed_operand_t& operand = inst->operands[operand_index];
assert(operand.num_words == 1); assert(operand.num_words == 1);
return GetTypeId(inst->words[operand.offset]); return GetTypeId(inst->words[operand.offset]);
} }
} /// namespace libspirv } // namespace libspirv

Просмотреть файл

@ -80,17 +80,18 @@ bool IsSupportOptionalVulkan_1_0(uint32_t capability) {
// Checks if |capability| was enabled by extension. // Checks if |capability| was enabled by extension.
bool IsEnabledByExtension(ValidationState_t& _, uint32_t capability) { bool IsEnabledByExtension(ValidationState_t& _, uint32_t capability) {
spv_operand_desc operand_desc = nullptr; spv_operand_desc operand_desc = nullptr;
_.grammar().lookupOperand( _.grammar().lookupOperand(SPV_OPERAND_TYPE_CAPABILITY, capability,
SPV_OPERAND_TYPE_CAPABILITY, capability, &operand_desc); &operand_desc);
// operand_desc is expected to be not null, otherwise validator would have // operand_desc is expected to be not null, otherwise validator would have
// failed at an earlier stage. This 'assert' is 'just in case'. // failed at an earlier stage. This 'assert' is 'just in case'.
assert(operand_desc); assert(operand_desc);
if (operand_desc->extensions.IsEmpty()) ExtensionSet operand_exts(operand_desc->numExtensions,
return false; operand_desc->extensions);
if (operand_exts.IsEmpty()) return false;
return _.HasAnyOfExtensions(operand_desc->extensions); return _.HasAnyOfExtensions(operand_exts);
} }
} // namespace } // namespace
@ -100,8 +101,7 @@ bool IsEnabledByExtension(ValidationState_t& _, uint32_t capability) {
spv_result_t CapabilityPass(ValidationState_t& _, spv_result_t CapabilityPass(ValidationState_t& _,
const spv_parsed_instruction_t* inst) { const spv_parsed_instruction_t* inst) {
const SpvOp opcode = static_cast<SpvOp>(inst->opcode); const SpvOp opcode = static_cast<SpvOp>(inst->opcode);
if (opcode != SpvOpCapability) if (opcode != SpvOpCapability) return SPV_SUCCESS;
return SPV_SUCCESS;
assert(inst->num_operands == 1); assert(inst->num_operands == 1);
@ -118,9 +118,9 @@ spv_result_t CapabilityPass(ValidationState_t& _,
!IsSupportOptionalVulkan_1_0(capability) && !IsSupportOptionalVulkan_1_0(capability) &&
!IsEnabledByExtension(_, capability)) { !IsEnabledByExtension(_, capability)) {
return _.diag(SPV_ERROR_INVALID_CAPABILITY) return _.diag(SPV_ERROR_INVALID_CAPABILITY)
<< "Capability value " << capability << "Capability value " << capability
<< " is not allowed by Vulkan 1.0 specification" << " is not allowed by Vulkan 1.0 specification"
<< " (or requires extension)"; << " (or requires extension)";
} }
} }

Просмотреть файл

@ -94,7 +94,8 @@ CapabilitySet RequiredCapabilities(const ValidationState_t& state,
spv_operand_desc operand_desc; spv_operand_desc operand_desc;
const auto ret = state.grammar().lookupOperand(type, operand, &operand_desc); const auto ret = state.grammar().lookupOperand(type, operand, &operand_desc);
if (ret == SPV_SUCCESS) { if (ret == SPV_SUCCESS) {
CapabilitySet result = operand_desc->capabilities; CapabilitySet result(operand_desc->numCapabilities,
operand_desc->capabilities);
// Allow FPRoundingMode decoration if requested // Allow FPRoundingMode decoration if requested
if (state.features().free_fp_rounding_mode && if (state.features().free_fp_rounding_mode &&
@ -115,7 +116,7 @@ ExtensionSet RequiredExtensions(const ValidationState_t& state,
if (state.grammar().lookupOperand(type, operand, &operand_desc) == if (state.grammar().lookupOperand(type, operand, &operand_desc) ==
SPV_SUCCESS) { SPV_SUCCESS) {
assert(operand_desc); assert(operand_desc);
return operand_desc->extensions; return {operand_desc->numExtensions, operand_desc->extensions};
} }
return ExtensionSet(); return ExtensionSet();
@ -127,14 +128,17 @@ namespace libspirv {
spv_result_t CapabilityCheck(ValidationState_t& _, spv_result_t CapabilityCheck(ValidationState_t& _,
const spv_parsed_instruction_t* inst) { const spv_parsed_instruction_t* inst) {
spv_opcode_desc opcode_desc; spv_opcode_desc opcode_desc = {};
const SpvOp opcode = static_cast<SpvOp>(inst->opcode); const SpvOp opcode = static_cast<SpvOp>(inst->opcode);
if (SPV_SUCCESS == _.grammar().lookupOpcode(opcode, &opcode_desc) && if (SPV_SUCCESS == _.grammar().lookupOpcode(opcode, &opcode_desc)) {
!_.HasAnyOfCapabilities(opcode_desc->capabilities)) CapabilitySet opcode_caps(opcode_desc->numCapabilities,
return _.diag(SPV_ERROR_INVALID_CAPABILITY) opcode_desc->capabilities);
<< "Opcode " << spvOpcodeString(opcode) if (!_.HasAnyOfCapabilities(opcode_caps))
<< " requires one of these capabilities: " return _.diag(SPV_ERROR_INVALID_CAPABILITY)
<< ToString(opcode_desc->capabilities, _.grammar()); << "Opcode " << spvOpcodeString(opcode)
<< " requires one of these capabilities: "
<< ToString(opcode_caps, _.grammar());
}
for (int i = 0; i < inst->num_operands; ++i) { for (int i = 0; i < inst->num_operands; ++i) {
const auto& operand = inst->operands[i]; const auto& operand = inst->operands[i];
const auto word = inst->words[operand.offset]; const auto word = inst->words[operand.offset];
@ -176,10 +180,10 @@ spv_result_t ExtensionCheck(ValidationState_t& _,
RequiredExtensions(_, operand.type, word); RequiredExtensions(_, operand.type, word);
if (!_.HasAnyOfExtensions(required_extensions)) { if (!_.HasAnyOfExtensions(required_extensions)) {
return _.diag(SPV_ERROR_MISSING_EXTENSION) return _.diag(SPV_ERROR_MISSING_EXTENSION)
<< spvutils::CardinalToOrdinal(operand_index + 1) << " operand of " << spvutils::CardinalToOrdinal(operand_index + 1) << " operand of "
<< spvOpcodeString(opcode) << ": operand " << word << spvOpcodeString(opcode) << ": operand " << word
<< " requires one of these extensions: " << " requires one of these extensions: "
<< ExtensionSetToString(required_extensions); << ExtensionSetToString(required_extensions);
} }
} }
return SPV_SUCCESS; return SPV_SUCCESS;
@ -194,8 +198,8 @@ spv_result_t ReservedCheck(ValidationState_t& _,
case SpvOpImageSparseSampleProjExplicitLod: case SpvOpImageSparseSampleProjExplicitLod:
case SpvOpImageSparseSampleProjDrefImplicitLod: case SpvOpImageSparseSampleProjDrefImplicitLod:
case SpvOpImageSparseSampleProjDrefExplicitLod: case SpvOpImageSparseSampleProjDrefExplicitLod:
return _.diag(SPV_ERROR_INVALID_VALUE) << spvOpcodeString(opcode) return _.diag(SPV_ERROR_INVALID_VALUE)
<< " is reserved for future use."; << spvOpcodeString(opcode) << " is reserved for future use.";
default: default:
return SPV_SUCCESS; return SPV_SUCCESS;
} }
@ -393,8 +397,7 @@ void CheckIfKnownExtension(ValidationState_t& _,
spv_result_t InstructionPass(ValidationState_t& _, spv_result_t InstructionPass(ValidationState_t& _,
const spv_parsed_instruction_t* inst) { const spv_parsed_instruction_t* inst) {
const SpvOp opcode = static_cast<SpvOp>(inst->opcode); const SpvOp opcode = static_cast<SpvOp>(inst->opcode);
if (opcode == SpvOpExtension) if (opcode == SpvOpExtension) CheckIfKnownExtension(_, inst);
CheckIfKnownExtension(_, inst);
if (opcode == SpvOpCapability) { if (opcode == SpvOpCapability) {
_.RegisterCapability( _.RegisterCapability(
static_cast<SpvCapability>(inst->words[inst->operands[0].offset])); static_cast<SpvCapability>(inst->words[inst->operands[0].offset]));

Просмотреть файл

@ -37,8 +37,9 @@ TEST_P(OpcodeTableCapabilitiesTest, TableEntryMatchesExpectedCapabilities) {
spv_opcode_desc entry; spv_opcode_desc entry;
ASSERT_EQ(SPV_SUCCESS, ASSERT_EQ(SPV_SUCCESS,
spvOpcodeTableValueLookup(opcodeTable, GetParam().opcode, &entry)); spvOpcodeTableValueLookup(opcodeTable, GetParam().opcode, &entry));
EXPECT_EQ(ElementsIn(GetParam().capabilities), EXPECT_EQ(
ElementsIn(entry->capabilities)); ElementsIn(GetParam().capabilities),
ElementsIn(CapabilitySet(entry->numCapabilities, entry->capabilities)));
} }
INSTANTIATE_TEST_CASE_P( INSTANTIATE_TEST_CASE_P(

Просмотреть файл

@ -51,8 +51,9 @@ TEST_P(EnumCapabilityTest, Sample) {
ASSERT_EQ(SPV_SUCCESS, ASSERT_EQ(SPV_SUCCESS,
spvOperandTableValueLookup(operandTable, get<1>(GetParam()).type, spvOperandTableValueLookup(operandTable, get<1>(GetParam()).type,
get<1>(GetParam()).value, &entry)); get<1>(GetParam()).value, &entry));
EXPECT_THAT(ElementsIn(entry->capabilities), EXPECT_THAT(
Eq(ElementsIn(get<1>(GetParam()).expected_capabilities))) ElementsIn(CapabilitySet(entry->numCapabilities, entry->capabilities)),
Eq(ElementsIn(get<1>(GetParam()).expected_capabilities)))
<< " capability value " << get<1>(GetParam()).value; << " capability value " << get<1>(GetParam()).value;
} }
@ -279,30 +280,30 @@ INSTANTIATE_TEST_CASE_P(
// See SPIR-V Section 3.12 Image Channel Order // See SPIR-V Section 3.12 Image Channel Order
INSTANTIATE_TEST_CASE_P( INSTANTIATE_TEST_CASE_P(
ImageChannelOrder, EnumCapabilityTest, ImageChannelOrder, EnumCapabilityTest,
Combine( Combine(Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1),
Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1), ValuesIn(std::vector<EnumCapabilityCase>{
ValuesIn(std::vector<EnumCapabilityCase>{ CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderR, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderR, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderA, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderA, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderRG, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderRG, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderRA, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderRA, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderRGB, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderRGB, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderRGBA, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderRGBA, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderBGRA, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderBGRA, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderARGB, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderARGB, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderIntensity, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderIntensity, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderLuminance, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderLuminance, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderRx, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderRx, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderRGx, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderRGx, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderRGBx, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderRGBx, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderDepth, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderDepth, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderDepthStencil,
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderDepthStencil, Kernel), Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrdersRGB, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrdersRGB, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrdersRGBx, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrdersRGBx, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrdersRGBA, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrdersRGBA, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrdersBGRA, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrdersBGRA, Kernel),
CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderABGR, Kernel), CASE1(IMAGE_CHANNEL_ORDER, ImageChannelOrderABGR, Kernel),
})), ); })), );
// See SPIR-V Section 3.13 Image Channel Data Type // See SPIR-V Section 3.13 Image Channel Data Type
INSTANTIATE_TEST_CASE_P( INSTANTIATE_TEST_CASE_P(

Просмотреть файл

@ -24,7 +24,7 @@ import re
# Prefix for all C variables generated by this script. # Prefix for all C variables generated by this script.
PYGEN_VARIABLE_PREFIX = 'pygen_variable' PYGEN_VARIABLE_PREFIX = 'pygen_variable'
# Extensions to recognize, but which don't necessarily come from the SPIRV-V # Extensions to recognize, but which don't necessarily come from the SPIR-V
# core grammar. Get this list from the SPIR-V registery web page. # core grammar. Get this list from the SPIR-V registery web page.
EXTENSIONS_FROM_SPIRV_REGISTRY = """ EXTENSIONS_FROM_SPIRV_REGISTRY = """
SPV_AMD_shader_explicit_vertex_parameter SPV_AMD_shader_explicit_vertex_parameter
@ -56,7 +56,6 @@ SPV_AMD_shader_fragment_mask
""" """
def make_path_to_file(f): def make_path_to_file(f):
"""Makes all ancestor directories to the given file, if they """Makes all ancestor directories to the given file, if they
don't yet exist. don't yet exist.
@ -86,6 +85,33 @@ def compose_capability_list(caps):
return "{" + ", ".join(['SpvCapability{}'.format(c) for c in caps]) + "}" return "{" + ", ".join(['SpvCapability{}'.format(c) for c in caps]) + "}"
def get_capability_array_name(caps, version):
"""Returns the name of the array containing all the given capabilities.
Args:
- caps: a sequence of capability names
"""
if not caps:
return 'nullptr'
else:
return '{}_caps_{}_{}'.format(
PYGEN_VARIABLE_PREFIX, ''.join(caps), version)
def generate_capability_arrays(caps, version):
"""Returns the arrays of capabilities.
Arguments:
- caps: a sequence of sequence of capability names
"""
caps = sorted(set([tuple(c) for c in caps if c]))
arrays = [
'static const SpvCapability {}[] = {};'.format(
get_capability_array_name(c, version), compose_capability_list(c))
for c in caps]
return '\n'.join(arrays)
def compose_extension_list(exts): def compose_extension_list(exts):
"""Returns a string containing a braced list of extensions as enums. """Returns a string containing a braced list of extensions as enums.
@ -99,6 +125,33 @@ def compose_extension_list(exts):
['libspirv::Extension::k{}'.format(e) for e in exts]) + "}" ['libspirv::Extension::k{}'.format(e) for e in exts]) + "}"
def get_extension_array_name(extensions, version):
"""Returns the name of the array containing all the given extensions.
Args:
- extensions: a sequence of extension names
"""
if not extensions:
return 'nullptr'
else:
return '{}_exts_{}_{}'.format(
PYGEN_VARIABLE_PREFIX, ''.join(extensions), version)
def generate_extension_arrays(extensions, version):
"""Returns the arrays of extensions.
Arguments:
- caps: a sequence of sequence of extension names
"""
extensions = sorted(set([tuple(e) for e in extensions if e]))
arrays = [
'static const libspirv::Extension {}[] = {};'.format(
get_extension_array_name(e, version), compose_extension_list(e))
for e in extensions]
return '\n'.join(arrays)
def convert_operand_kind(operand_tuple): def convert_operand_kind(operand_tuple):
"""Returns the corresponding operand type used in spirv-tools for """Returns the corresponding operand type used in spirv-tools for
the given operand kind and quantifier used in the JSON grammar. the given operand kind and quantifier used in the JSON grammar.
@ -166,17 +219,19 @@ class InstInitializer(object):
"""Instances holds a SPIR-V instruction suitable for printing as """Instances holds a SPIR-V instruction suitable for printing as
the initializer for spv_opcode_desc_t.""" the initializer for spv_opcode_desc_t."""
def __init__(self, opname, caps, operands): def __init__(self, opname, caps, operands, version):
"""Initialization. """Initialization.
Arguments: Arguments:
- opname: opcode name (with the 'Op' prefix) - opname: opcode name (with the 'Op' prefix)
- caps: a sequence of capability names required by this opcode - caps: a sequence of capability names required by this opcode
- operands: a sequence of (operand-kind, operand-quantifier) tuples - operands: a sequence of (operand-kind, operand-quantifier) tuples
- version: version of the instruction set
""" """
assert opname.startswith('Op') assert opname.startswith('Op')
self.opname = opname[2:] # Remove the "Op" prefix. self.opname = opname[2:] # Remove the "Op" prefix.
self.caps_mask = compose_capability_list(caps) self.num_caps = len(caps)
self.caps_mask = get_capability_array_name(caps, version)
self.operands = [convert_operand_kind(o) for o in operands] self.operands = [convert_operand_kind(o) for o in operands]
self.fix_syntax() self.fix_syntax()
@ -198,11 +253,13 @@ class InstInitializer(object):
self.operands.pop() self.operands.pop()
def __str__(self): def __str__(self):
template = ['{{"{opname}"', 'SpvOp{opname}', '{caps_mask}', template = ['{{"{opname}"', 'SpvOp{opname}',
'{num_caps}', '{caps_mask}',
'{num_operands}', '{{{operands}}}', '{num_operands}', '{{{operands}}}',
'{def_result_id}', '{ref_type_id}}}'] '{def_result_id}', '{ref_type_id}}}']
return ', '.join(template).format( return ', '.join(template).format(
opname=self.opname, opname=self.opname,
num_caps=self.num_caps,
caps_mask=self.caps_mask, caps_mask=self.caps_mask,
num_operands=len(self.operands), num_operands=len(self.operands),
operands=', '.join(self.operands), operands=', '.join(self.operands),
@ -214,7 +271,7 @@ class ExtInstInitializer(object):
"""Instances holds a SPIR-V extended instruction suitable for printing as """Instances holds a SPIR-V extended instruction suitable for printing as
the initializer for spv_ext_inst_desc_t.""" the initializer for spv_ext_inst_desc_t."""
def __init__(self, opname, opcode, caps, operands): def __init__(self, opname, opcode, caps, operands, version):
"""Initialization. """Initialization.
Arguments: Arguments:
@ -222,24 +279,27 @@ class ExtInstInitializer(object):
- opcode: enumerant value for this opcode - opcode: enumerant value for this opcode
- caps: a sequence of capability names required by this opcode - caps: a sequence of capability names required by this opcode
- operands: a sequence of (operand-kind, operand-quantifier) tuples - operands: a sequence of (operand-kind, operand-quantifier) tuples
- version: version of the extended instruction set
""" """
self.opname = opname self.opname = opname
self.opcode = opcode self.opcode = opcode
self.caps_mask = compose_capability_list(caps) self.num_caps = len(caps)
self.caps_mask = get_capability_array_name(caps, version)
self.operands = [convert_operand_kind(o) for o in operands] self.operands = [convert_operand_kind(o) for o in operands]
self.operands.append('SPV_OPERAND_TYPE_NONE') self.operands.append('SPV_OPERAND_TYPE_NONE')
def __str__(self): def __str__(self):
template = ['{{"{opname}"', '{opcode}', '{caps_mask}', template = ['{{"{opname}"', '{opcode}', '{num_caps}', '{caps_mask}',
'{{{operands}}}}}'] '{{{operands}}}}}']
return ', '.join(template).format( return ', '.join(template).format(
opname=self.opname, opname=self.opname,
opcode=self.opcode, opcode=self.opcode,
num_caps=self.num_caps,
caps_mask=self.caps_mask, caps_mask=self.caps_mask,
operands=', '.join(self.operands)) operands=', '.join(self.operands))
def generate_instruction(inst, is_ext_inst): def generate_instruction(inst, version, is_ext_inst):
"""Returns the C initializer for the given SPIR-V instruction. """Returns the C initializer for the given SPIR-V instruction.
Arguments: Arguments:
@ -260,27 +320,49 @@ def generate_instruction(inst, is_ext_inst):
assert opname is not None assert opname is not None
if is_ext_inst: if is_ext_inst:
return str(ExtInstInitializer(opname, opcode, caps, operands)) return str(ExtInstInitializer(opname, opcode, caps, operands, version))
else: else:
return str(InstInitializer(opname, caps, operands)) return str(InstInitializer(opname, caps, operands, version))
def generate_instruction_table(inst_table, is_ext_inst): def generate_instruction_table(inst_table, version):
"""Returns the info table containing all SPIR-V instructions. """Returns the info table containing all SPIR-V instructions,
prefixed by capability arrays.
Arguments: Arguments:
- inst_table: a dict containing all SPIR-V instructions. - inst_table: a dict containing all SPIR-V instructions.
- is_ext_inst: a bool indicating whether |inst_table| is for - vesion: SPIR-V version.
an extended instruction set.
""" """
return ',\n'.join([generate_instruction(inst, is_ext_inst) caps_arrays = generate_capability_arrays(
for inst in inst_table]) [inst.get('capabilities', []) for inst in inst_table], version)
insts = [generate_instruction(inst, version, False) for inst in inst_table]
insts = ['static const spv_opcode_desc_t kOpcodeTableEntries_{}[] = {{\n'
' {}\n}};'.format(version, ',\n '.join(insts))]
return '{}\n\n{}'.format(caps_arrays, '\n'.join(insts))
def generate_extended_instruction_table(inst_table, set_name, version):
"""Returns the info table containing all SPIR-V extended instructions,
prefixed by capability arrays.
Arguments:
- inst_table: a dict containing all SPIR-V instructions.
- set_name: the name of the extended instruction set.
"""
caps = [inst.get('capabilities', []) for inst in inst_table]
caps_arrays = generate_capability_arrays(caps, version)
insts = [generate_instruction(inst, version, True) for inst in inst_table]
insts = ['static const spv_ext_inst_desc_t {}_entries[] = {{\n'
' {}\n}};'.format(set_name, ',\n '.join(insts))]
return '{}\n\n{}'.format(caps_arrays, '\n'.join(insts))
class EnumerantInitializer(object): class EnumerantInitializer(object):
"""Prints an enumerant as the initializer for spv_operand_desc_t.""" """Prints an enumerant as the initializer for spv_operand_desc_t."""
def __init__(self, enumerant, value, caps, exts, parameters): def __init__(self, enumerant, value, caps, exts, parameters, version):
"""Initialization. """Initialization.
Arguments: Arguments:
@ -292,22 +374,26 @@ class EnumerantInitializer(object):
""" """
self.enumerant = enumerant self.enumerant = enumerant
self.value = value self.value = value
self.caps = compose_capability_list(caps) self.num_caps = len(caps)
self.exts = compose_extension_list(exts) self.caps = get_capability_array_name(caps, version)
self.num_exts = len(exts)
self.exts = get_extension_array_name(exts, version)
self.parameters = [convert_operand_kind(p) for p in parameters] self.parameters = [convert_operand_kind(p) for p in parameters]
def __str__(self): def __str__(self):
template = ['{{"{enumerant}"', '{value}', template = ['{{"{enumerant}"', '{value}', '{num_caps}',
'{caps}', '{exts}', '{{{parameters}}}}}'] '{caps}', '{num_exts}', '{exts}', '{{{parameters}}}}}']
return ', '.join(template).format( return ', '.join(template).format(
enumerant=self.enumerant, enumerant=self.enumerant,
value=self.value, value=self.value,
num_caps=self.num_caps,
caps=self.caps, caps=self.caps,
num_exts=self.num_exts,
exts=self.exts, exts=self.exts,
parameters=', '.join(self.parameters)) parameters=', '.join(self.parameters))
def generate_enum_operand_kind_entry(entry): def generate_enum_operand_kind_entry(entry, version):
"""Returns the C initializer for the given operand enum entry. """Returns the C initializer for the given operand enum entry.
Arguments: Arguments:
@ -327,7 +413,8 @@ def generate_enum_operand_kind_entry(entry):
assert enumerant is not None assert enumerant is not None
assert value is not None assert value is not None
return str(EnumerantInitializer(enumerant, value, caps, exts, params)) return str(EnumerantInitializer(
enumerant, value, caps, exts, params, version))
def generate_enum_operand_kind(enum, version): def generate_enum_operand_kind(enum, version):
@ -336,7 +423,7 @@ def generate_enum_operand_kind(enum, version):
assert kind is not None assert kind is not None
name = '{}_{}Entries_{}'.format(PYGEN_VARIABLE_PREFIX, kind, version) name = '{}_{}Entries_{}'.format(PYGEN_VARIABLE_PREFIX, kind, version)
entries = [' {}'.format(generate_enum_operand_kind_entry(e)) entries = [' {}'.format(generate_enum_operand_kind_entry(e, version))
for e in enum.get('enumerants', [])] for e in enum.get('enumerants', [])]
template = ['static const spv_operand_desc_t {name}[] = {{', template = ['static const spv_operand_desc_t {name}[] = {{',
@ -351,9 +438,19 @@ def generate_enum_operand_kind(enum, version):
def generate_operand_kind_table(enums, version): def generate_operand_kind_table(enums, version):
"""Returns the info table containing all SPIR-V operand kinds.""" """Returns the info table containing all SPIR-V operand kinds."""
# We only need to output info tables for those operand kinds that are enums. # We only need to output info tables for those operand kinds that are enums.
enums = [generate_enum_operand_kind(e, version) enums = [e for e in enums if e.get('category') in ['ValueEnum', 'BitEnum']]
for e in enums
if e.get('category') in ['ValueEnum', 'BitEnum']] caps = [entry.get('capabilities', [])
for enum in enums
for entry in enum.get('enumerants', [])]
caps_arrays = generate_capability_arrays(caps, version)
exts = [entry.get('extensions', [])
for enum in enums
for entry in enum.get('enumerants', [])]
exts_arrays = generate_extension_arrays(exts, version)
enums = [generate_enum_operand_kind(e, version) for e in enums]
# We have three operand kinds that requires their optional counterpart to # We have three operand kinds that requires their optional counterpart to
# exist in the operand info table. # exist in the operand info table.
three_optional_enums = ['ImageOperands', 'AccessQualifier', 'MemoryAccess'] three_optional_enums = ['ImageOperands', 'AccessQualifier', 'MemoryAccess']
@ -377,7 +474,7 @@ def generate_operand_kind_table(enums, version):
table = '\n'.join(template).format( table = '\n'.join(template).format(
p=PYGEN_VARIABLE_PREFIX, v=version, enums=',\n'.join(table_entries)) p=PYGEN_VARIABLE_PREFIX, v=version, enums=',\n'.join(table_entries))
return '\n\n'.join(enum_entries + (table,)) return '\n\n'.join((caps_arrays,) + (exts_arrays,) + enum_entries + (table,))
def get_extension_list(operands): def get_extension_list(operands):
@ -580,11 +677,11 @@ def main():
if args.core_insts_output is not None: if args.core_insts_output is not None:
make_path_to_file(args.core_insts_output) make_path_to_file(args.core_insts_output)
make_path_to_file(args.operand_kinds_output) make_path_to_file(args.operand_kinds_output)
print(generate_instruction_table(
grammar['instructions'], False),
file=open(args.core_insts_output, 'w'))
version = '{}_{}'.format(grammar['major_version'], version = '{}_{}'.format(grammar['major_version'],
grammar['minor_version']) grammar['minor_version'])
print(generate_instruction_table(
grammar['instructions'], version),
file=open(args.core_insts_output, 'w'))
print(generate_operand_kind_table( print(generate_operand_kind_table(
grammar['operand_kinds'], version), grammar['operand_kinds'], version),
file=open(args.operand_kinds_output, 'w')) file=open(args.operand_kinds_output, 'w'))
@ -602,21 +699,27 @@ def main():
with open(args.extinst_glsl_grammar) as json_file: with open(args.extinst_glsl_grammar) as json_file:
grammar = json.loads(json_file.read()) grammar = json.loads(json_file.read())
make_path_to_file(args.glsl_insts_output) make_path_to_file(args.glsl_insts_output)
print(generate_instruction_table(grammar['instructions'], True), print(generate_extended_instruction_table(
grammar['instructions'], "glsl", "1_0"),
file=open(args.glsl_insts_output, 'w')) file=open(args.glsl_insts_output, 'w'))
if args.extinst_opencl_grammar is not None: if args.extinst_opencl_grammar is not None:
with open(args.extinst_opencl_grammar) as json_file: with open(args.extinst_opencl_grammar) as json_file:
grammar = json.loads(json_file.read()) grammar = json.loads(json_file.read())
make_path_to_file(args.opencl_insts_output) make_path_to_file(args.opencl_insts_output)
print(generate_instruction_table(grammar['instructions'], True), print(generate_extended_instruction_table(
grammar['instructions'], "opencl", "1_0"),
file=open(args.opencl_insts_output, 'w')) file=open(args.opencl_insts_output, 'w'))
if args.extinst_vendor_grammar is not None: if args.extinst_vendor_grammar is not None:
with open(args.extinst_vendor_grammar) as json_file: with open(args.extinst_vendor_grammar) as json_file:
grammar = json.loads(json_file.read()) grammar = json.loads(json_file.read())
make_path_to_file(args.vendor_insts_output) make_path_to_file(args.vendor_insts_output)
print(generate_instruction_table(grammar['instructions'], True), name = args.extinst_vendor_grammar
start = name.find("extinst.") + len("extinst.")
name = name[start:-len(".grammar.json")].replace("-", "_")
print(generate_extended_instruction_table(
grammar['instructions'], name, "1_0"),
file=open(args.vendor_insts_output, 'w')) file=open(args.vendor_insts_output, 'w'))